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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
61,157,024 | Compatible side by side NDK version was not found. Default is 20.0.5594570 | <p>I am getting the above error</p>
<p>My gradle looks like this </p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.hypersignwalletcorekotlin"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
project.ext {
walletcore_version = "2.0.5"
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "com.trustwallet:wallet-core:$walletcore_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code></pre>
<p>Not able to understand why is this happening.</p>
<p>Thanks</p> | 61,510,602 | 8 | 1 | null | 2020-04-11 12:45:04.113 UTC | 7 | 2022-08-01 12:45:41.13 UTC | null | null | null | null | 3,196,956 | null | 1 | 28 | android|android-ndk | 57,423 | <p><strong>The Fix:</strong>
add <a href="https://developer.android.com/studio/projects/install-ndk#apply-specific-version" rel="noreferrer">ndkVersion</a> to your module's build.gradle</p>
<pre><code> android.ndkVersion "your-installed-ndk-version"
</code></pre>
<p>as in <a href="https://github.com/android/ndk-samples/blob/master/teapots/classic-teapot/build.gradle#L6" rel="noreferrer">some examples</a>. You could find your NDK version from the file $NDK/source.properties.</p>
<p><strong>Background Info:</strong>
You probably using AGP/Android Studio version 3.6+: "From Android Gradle Plugin ( AGP ) 3.6+, there is a <code>known good NDK</code> concept added, which is the <code>known good/tested NDK version</code> when that AGP version was released". AGP will use that internal NDK version if:</p>
<ul>
<li>you are not using the <a href="https://developer.android.com/studio/projects/install-ndk#apply-specific-version" rel="noreferrer">ndkVersion</a> feature added in AGP 3.5</li>
</ul>
<p>That internal NDKs are expected to be installed as side-by-side NDK place:
$SDK\ndk<br />
if not installed:</p>
<ul>
<li>AGP 3.6, AGP 4.0 will error out</li>
<li>AGP 4.1 would auto install it.</li>
</ul>
<p>The internally embedded NDK version, most likely, will be out-of-date pretty quickly as newer NDKs are constantly being released: if you want to use a newer NDK version, you do need to configure gradle with <a href="https://developer.android.com/studio/projects/install-ndk#apply-specific-version" rel="noreferrer">ndkVersion</a>.</p>
<p><strong>Additional Doc:</strong>
Refer to <a href="https://developer.android.com/studio/projects/configure-agp-ndk" rel="noreferrer">the official documentation</a> for details.</p> |
34,247,337 | Object-fit not affecting images | <p>I've been trying to use <code>object-fit</code> on a few images placed inside <code>article</code> elements, but it doesn't seem to affect them at all.</p>
<p>The desired value for the <code>object-fit</code> property would be <code>cover</code>, but as of right now, none of the other values seem to work either.</p>
<p>When I change it's value, they don't shrink, don't grow, don't ... nothing.</p>
<p>If you see the CodePen, there are white spaces between the two rows, and the images don't take all the same space/height (as it would be expected with <code>object-fit: cover</code>).</p>
<p><a href="http://codepen.io/anon/pen/PZPKGy?editors=110" rel="noreferrer">Here's a CodePen</a></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>body{
margin: 0 auto; padding: 0;
}
main{
min-height: 70vh;
padding: 0;
}
main > section.posts{
box-sizing: border-box;
margin: 0; padding: 0;
display: flex;
flex-flow: row wrap;
}
main > section.posts > article{
outline: 1px solid red;
width: 22vw;
min-height: 100vh;
margin: 0; padding: 0;
flex-grow: 1;
overflow: hidden;
box-sizing: border-box;
}
main > section.posts > article > img{ /* Our suspect */
object-fit: cover;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--
Basic structure of this file is
<main>
<section.posts>
<article> (six of them)
<image>
-->
<main>
<section class="posts">
<article>
<img src="http://41.media.tumblr.com/tumblr_m6s6d65lE11qdnz8wo1_400.jpg">
</article>
<article>
<img src="http://41.media.tumblr.com/71c1fe7c899cd048fb961d3c1953411b/tumblr_nj24pvINyW1qzq8p3o1_400.jpg">
</article>
<article>
<img src="http://36.media.tumblr.com/3358cb6ac8eaa0e61dffd53bc1bab93d/tumblr_n92l475hol1qlmppmo1_400.png">
</article>
<article>
<img src="http://36.media.tumblr.com/9ad997ca0385a23a8d82ec919da2392c/tumblr_nwcewbFVAL1s71gzco1_400.jpg">
</article>
<article>
<img src="http://41.media.tumblr.com/tumblr_mbl45xDSwj1qfn79co1_400.jpg">
</article>
<article>
<img src="http://41.media.tumblr.com/1c3718e71a2aa5acaaaf4af654991c91/tumblr_nx6psaH67d1tvh80lo1_400.jpg">
</article>
</section>
</main></code></pre>
</div>
</div>
</p> | 34,247,563 | 6 | 9 | null | 2015-12-13 02:21:07.433 UTC | 23 | 2021-08-18 09:39:59.497 UTC | 2015-12-13 02:40:24.5 UTC | null | 3,435,901 | null | 3,435,901 | null | 1 | 99 | html|css | 141,678 | <h1><code>object-fit</code> only affects the way the picture displays inside of the <code>img</code> boundaries.</h1>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit" rel="noreferrer"><strong>Object-Fit</strong></a></p>
<blockquote>
<p>The object-fit CSS property sets how the content of a replaced element, such as an <code><img></code> or <code><video></code>, should be resized to fit its container.</p>
</blockquote>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element" rel="noreferrer"><strong>Replaced Element</strong></a></p>
<blockquote>
<p>elements whose contents are not affected by the current document's styles. The position of the replaced element can be affected using CSS, but not the contents of the replaced element itself.</p>
</blockquote>
<p>This means that the object-fit is independent of your <code>article</code> elements as object-fit only cares about the dimensions of the <code>img</code> element.</p>
<p>The point of this is that you need to get the <code>img</code> elements to stretch to those dimensions first. The <code>object-fit</code> only affects the way the picture displays inside of the <code>img</code> boundaries.</p>
<h2>Sample Code / Demonstration</h2>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $("img").resizable(); });</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
width: 300px;
height: 300px;
border: 1px solid #FF0000;
background-color: #00FF00;
}
.fill {
object-fit: fill;
}
.contain {
object-fit: contain;
}
.cover {
object-fit: cover;
}
.none {
object-fit: none;
}
.scaledown {
object-fit: scale-down;
}
.variant1 {
max-width: 100px;
}
.variant2 {
max-height: 100px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<p>Resize images to see properties with different dimensions.</p>
<h1>fill (default)</h1>
<img src="https://i.stack.imgur.com/EtYb2.jpg" class="fill" />
<h1>contain</h1>
<img src="https://i.stack.imgur.com/EtYb2.jpg" class="contain" />
<h1>cover</h1>
<img src="https://i.stack.imgur.com/EtYb2.jpg" class="cover" />
<h1>none</h1>
<img src="https://i.stack.imgur.com/EtYb2.jpg" class="none" />
<h1>scale-down</h1>
<img src="https://i.stack.imgur.com/EtYb2.jpg" class="scaledown" />
<!-- Spacer for scale down scroll annoyance -->
<br /><br /><br /><br /><br /><br /><br /></code></pre>
</div>
</div>
</p>
<h2>Solutions to Question</h2>
<p><strong>Solution 1: More flex</strong></p>
<p>Using your current HTML structure you can use the snippet below to apply an additional flex inside of each <code>article</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>//
// Image styles are near the end of file
// (Line 28)
//
body{
margin: 0 auto; padding: 0;
}
main{
min-height: 70vh;
padding: 0;
}
main > section.posts{
box-sizing: border-box;
margin: 0; padding: 0;
display: flex;
align-content: stretch;
flex-flow: row wrap;
}
main > section.posts > article{
outline: 1px solid red;
width: 22vw;
min-height: 100vh;
margin: 0; padding: 0;
flex-grow: 1;
overflow: hidden;
box-sizing: border-box;
display: flex;
align-content: stretch;
align-items: stretch;
}
main > section.posts > article > img{
object-fit: cover;
flex: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--
Basic structure of this file is
<main>
<section.posts>
<article> (six of them)
<image>
-->
<main>
<section class="posts">
<article>
<img src="https://41.media.tumblr.com/tumblr_m6s6d65lE11qdnz8wo1_400.jpg">
</article>
<article>
<img src="https://41.media.tumblr.com/71c1fe7c899cd048fb961d3c1953411b/tumblr_nj24pvINyW1qzq8p3o1_400.jpg">
</article>
<article>
<img src="https://36.media.tumblr.com/3358cb6ac8eaa0e61dffd53bc1bab93d/tumblr_n92l475hol1qlmppmo1_400.png">
</article>
<article>
<img src="https://36.media.tumblr.com/9ad997ca0385a23a8d82ec919da2392c/tumblr_nwcewbFVAL1s71gzco1_400.jpg">
</article>
<article>
<img src="https://41.media.tumblr.com/tumblr_mbl45xDSwj1qfn79co1_400.jpg">
</article>
<article>
<img src="https://41.media.tumblr.com/1c3718e71a2aa5acaaaf4af654991c91/tumblr_nx6psaH67d1tvh80lo1_400.jpg">
</article>
</section>
</main></code></pre>
</div>
</div>
</p>
<p><strong>Solution 2: Remove article elements</strong></p>
<p>Or you could restructure your html to remove the <code>article</code> elements and flex the <code>img</code> elements.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code> body{
margin: 0 auto; padding: 0;
}
main{
min-height: 70vh;
padding: 0;
}
main > section.posts{
box-sizing: border-box;
margin: 0; padding: 0;
display: flex;
flex-flow: row wrap;
}
main > section.posts > img{
outline: 1px solid red;
width: 22vw;
min-height: 100vh;
margin: 0; padding: 0;
flex-grow: 1;
overflow: hidden;
box-sizing: border-box;
}
main > section.posts > img{ /* Our suspect */
object-fit: cover;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <main>
<section class="posts">
<img src="http://41.media.tumblr.com/tumblr_m6s6d65lE11qdnz8wo1_400.jpg">
<img src="http://41.media.tumblr.com/71c1fe7c899cd048fb961d3c1953411b/tumblr_nj24pvINyW1qzq8p3o1_400.jpg">
<img src="http://36.media.tumblr.com/3358cb6ac8eaa0e61dffd53bc1bab93d/tumblr_n92l475hol1qlmppmo1_400.png">
<img src="http://36.media.tumblr.com/9ad997ca0385a23a8d82ec919da2392c/tumblr_nwcewbFVAL1s71gzco1_400.jpg">
<img src="http://41.media.tumblr.com/tumblr_mbl45xDSwj1qfn79co1_400.jpg">
<img src="http://41.media.tumblr.com/1c3718e71a2aa5acaaaf4af654991c91/tumblr_nx6psaH67d1tvh80lo1_400.jpg">
</section>
</main></code></pre>
</div>
</div>
</p> |
5,107,134 | Find the Rotation and Skew of a Matrix transformation | <p>I have the the following Transform Matrix in CSS</p>
<pre><code>// rotate the element 60deg
element.style.transform = "matrix(0.5,0.866025,-0.866025,0.5,0,0)"
</code></pre>
<p>And i can find the rotation using this...</p>
<pre><code>// where a = [0.710138,0.502055,-0.57735,1,0,0]
var rotation = ((180/Math.PI) * Math.atan2( ((0*a[2])+(1*a[3])),((0*a[0])-(1*a[1]))) - 90
console.log(rotation); // ~60
</code></pre>
<p>Similarly for skew if...</p>
<pre><code>// skew(30deg,-50deg)
element.style.transform = "matrix(1,-1.19175,0.57735,1,0,0)"
var skewY = ((180/Math.PI) * Math.atan2( ((0*a[2])+(1*a[3])),((0*a[0])-(1*a[1]))) - 90;
var skewX = (180/Math.PI) * Math.atan2( ((1*a[2])+(0*a[3])),((1*a[0])-(0*a[1])));
console.log([skewX,skewY]); // ~= [30,-50]
</code></pre>
<p>However as soon as i use both skew and rotation everything goes weird not least because the formula for rotation is identical to that of skew... so the formulas can't be right. </p>
<p>How do i determine both rotation & skew where both attributes have been applied and all i know is the Matrix Transform.</p>
<p>Also scale messed up my skew values, which i dont think it should.</p> | 32,125,700 | 2 | 3 | null | 2011-02-24 16:02:41.587 UTC | 9 | 2018-12-13 16:59:02.573 UTC | 2015-11-12 12:53:24.41 UTC | null | 2,655,678 | null | 160,755 | null | 1 | 17 | javascript|matrix|qr-decomposition | 11,285 | <p>I needed same functionality and today I ended up with this code that works very good.</p>
<p>I took inspiration from here:
<a href="https://www.youtube.com/watch?v=51MRHjKSbtk" rel="noreferrer">https://www.youtube.com/watch?v=51MRHjKSbtk</a>
and from the <a href="https://stackoverflow.com/a/5108516/363437">answer below</a>, without the hint <strong>QR decomposition</strong> i would never find it out</p>
<p>I worked on a 2x2 case, i will try to expand to 2x3 to include also translations.
But it should be easy</p>
<pre><code>var a = [a, b, c, d, e, f];
var qrDecompone = function(a) {
var angle = Math.atan2(a[1], a[0]),
denom = Math.pow(a[0], 2) + Math.pow(a[1], 2),
scaleX = Math.sqrt(denom),
scaleY = (a[0] * a[3] - a[2] * a[1]) / scaleX,
skewX = Math.atan2(a[0] * a[2] + a[1] * a[3], denom);
return {
angle: angle / (Math.PI / 180), // this is rotation angle in degrees
scaleX: scaleX, // scaleX factor
scaleY: scaleY, // scaleY factor
skewX: skewX / (Math.PI / 180), // skewX angle degrees
skewY: 0, // skewY angle degrees
translateX: a[4], // translation point x
translateY: a[5] // translation point y
};
};
</code></pre>
<p>It looks like that the last two items in the transformMatrix, before decomposition, are translation values. You can extract them directly.</p> |
5,129,386 | How to detect when history.pushState and history.replaceState are used? | <p>Is there some event I can subscribe to when the history state is modified? How?</p> | 5,134,732 | 2 | 0 | null | 2011-02-26 20:00:19.07 UTC | 9 | 2015-08-06 21:49:30.193 UTC | 2014-09-08 13:51:44.933 UTC | null | 312,681 | null | 340,760 | null | 1 | 49 | javascript|html|browser-history|pushstate | 68,037 | <p>The onpopstate event should be fired when the history changes, you can bind to it in your code like this:</p>
<pre><code>window.onpopstate = function (event) {
// do stuff here
}
</code></pre>
<p>This event may also be fired when the page loads, you can determine whether the event was fired from a page load, or by using pushState/replaceState by checking the event object for a state property, it will be undefined if the event was caused by a page load</p>
<pre><code>window.onpopstate = function (event) {
if (event.state) {
// history changed because of pushState/replaceState
} else {
// history changed because of a page load
}
}
</code></pre>
<p>There currently is no onpushstate event unfortunately, to get around this you need to wrap both the pushState and replaceState methods to implement your own onpushstate event.</p>
<p>I have a library that makes working with pushState a bit easier, it might be worth checking it out called <a href="https://github.com/olivernn/davis.js" rel="noreferrer">Davis.js</a>, it provides a simple api for working with routing based on pushState.</p> |
222,456 | Enable and disable "Step into" debugging on certain project in a Visual Studio solution | <p>I have a Visual Studio solution with four C# projects in it. I want to step into the code of a supporting project in the solution from my main project, but when I use the "Step into" key, it just skips over the call into that other project. I've set breakpoints in the supporting project, and they're ignored, and I can't for the life of me get it to step into any references to that project.</p>
<p>Everything is set to compile as "Debug", and I've seen Visual Studio warn me that my breakpoints won't be hit before - it doesn't do that in this case. It's as though it looks as though my code will debug, but then at run-time, there's a setting somewhere that tells Visual Studio not to step through the code in that project. All the other projects in my solutions debug without problems.</p>
<p>What box have I checked to cause this behavior?</p>
<p><strong>UPDATE FOR CLARITY</strong>: The "Just my code" option is currently disabled. Also, since the code belongs to a project in my same solution, I don't think the "Just my code" option applies here. I thought it only applied to pre-compiled code that I didn't have the source for, but since I have the source in my project, I don't think this option has any effect.</p> | 222,477 | 7 | 0 | null | 2008-10-21 16:10:46.63 UTC | 3 | 2022-08-30 07:23:51.797 UTC | 2011-12-30 18:46:06.673 UTC | moocha | 63,550 | rwmnau | 8,114 | null | 1 | 23 | c#|visual-studio|debugging|step-into | 43,095 | <p>One thing to check for is that your supporting project assembly has not been installed in the GAC. Open a command prompt and run the following to make sure...</p>
<p>gacutil /l <em>assemblyName</em></p> |
1,202,322 | MySQL Error "Too many connections" | <p>I am using MySQL 5.0 for a site that is hosted by GoDaddy (linux). </p>
<p>I was doing some testing on my web app, and suddenly I noticed that the pages were refreshing really slowly. Finally, after a long wait, I got to a page that said something along the lines of "MySQL Error, Too many connections...", and it pointed to my config.php file which connects to the database.</p>
<p>It has just been me connecting to the database, no other users. On each of my pages, I include the config.php file at the top, and close the mysql connection at the end of the page. There may be several queries in between. I fear that I am not closing mysql connections enough (mysql_close()).</p>
<p>However, when I try to close them after running a query, I receive connection errors on the page. My pages are PHP and HTML. When I try to close a query, it seems that the next one won't connect. Would I have to include config.php again after the close in order to connect?</p>
<p>This error scared me because in 2 weeks, about 84 people start using this web application.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>Here is some pseudo-code of my page:</p>
<pre><code> require_once('../scripts/config.php');
<?php
mysql_query..
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
if(this button is pressed){
mysql_query...
}
?>
some html..
..
..
..
..
<?php
another mysql_query...
?>
some more html..
..
..
<?php mysql_close(); ?>
</code></pre>
<p>I figured that this way, each time the page opens, the connection opens, and then the connection closes when the page is done loading. Then, the connection opens again when someone clicks a button on the page, and so on...</p>
<p>EDIT:</p>
<p>Okay, so I just got off the phone with GoDaddy. Apparently, with my Economy Package, I'm limited to 50 connections at a time. While my issue today happened with only me accessing the site, they said that they were having some server problems earlier. However, seeing as how I am going to have 84 users for my web app, I should probably upgrade to "Deluxe", which allows for 100 connections at a time. On a given day, there may be around 30 users accessing my site at a time, so I think the 100 would be a safer bet. Do you guys agree?</p> | 1,203,350 | 7 | 4 | null | 2009-07-29 18:55:13.593 UTC | 8 | 2017-12-11 10:24:27.27 UTC | 2009-07-30 00:56:17.6 UTC | null | 123,891 | null | 123,891 | null | 1 | 23 | php|mysql|connection | 90,102 | <p>Shared-hosting providers generally allow a pretty small amount of simultaneous connections for the same user.</p>
<p>What your code does is :</p>
<ul>
<li>open a connection to the MySQL server</li>
<li>do it's stuff (generating the page)</li>
<li>close the connection at the end of the page.</li>
</ul>
<p>The last step, when done at the end of the page is not <strong>mandatory</strong> : (quoting <a href="http://php.net/mysql_close" rel="noreferrer"><code>mysql_close</code></a>'s manual) :</p>
<blockquote>
<p>Using mysql_close() isn't usually
necessary, as non-persistent open
links are automatically closed at the
end of the script's execution.</p>
</blockquote>
<p>But note you probably shouldn't use persistent connections anyway...</p>
<p>Two tips :</p>
<ul>
<li>use <code>mysql_connect</code> insead of <code>mysql_pconnect</code> <em>(already OK for you)</em></li>
<li>Set the fourth parameter of mysql_connect to false <em>(already OK for you, as it's the default value)</em> : (quoting the manual) :</li>
</ul>
<blockquote>
<p>If a second call is made to
mysql_connect() with the same
arguments, no new link will be
established, but instead, the link
identifier of the already opened link
will be returned. </p>
<p>The new_link
parameter modifies this behavior and
makes mysql_connect() always open a
new link, even if mysql_connect() was
called before with the same
parameters.</p>
</blockquote>
<p><br></p>
<hr>
<p>What could cause the problem, then ?</p>
<p>Maybe you are trying to access several pages in parallel <em>(using multiple tabs in your browser, for instance)</em>, which will simulate several users using the website at the same time ?</p>
<p>If you have many users using the site at the same time and the code between <code>mysql_connect</code> and the closing of the connection takes lots of time, it will mean many connections being opened at the same time... And you'll reach the limit <strong>:-(</strong></p>
<p>Still, as you are the only user of the application, considering you have up to 200 simultaneous connections allowed, there is something odd going on...</p>
<p><br></p>
<hr>
<p>Well, thinking about "<em>too many connections</em>" and "<code>max_connections</code>"...</p>
<p>If I remember correctly, <code>max_connections</code> does not limit the number of connections <strong>you</strong> can open to the MySQL Server, but the <strong>total number of connections</strong> that can bo opened to that server, <strong>by anyone connecting to it</strong>.</p>
<p>Quoting MySQL's documentation on <a href="http://dev.mysql.com/doc/refman/5.0/en/too-many-connections.html" rel="noreferrer">Too many connections</a> :</p>
<blockquote>
<p>If you get a Too many connections
error when you try to connect to the
mysqld server, this means that all
available connections are in use by
other clients.</p>
<p>The number of connections allowed is
controlled by the max_connections
system variable. Its default value is
100. If you need to support more connections, you should set a larger
value for this variable.</p>
</blockquote>
<p>So, actually, the problem might not come from you nor your code <em>(which looks fine, actually)</em> : it might "just" be that you are not the only one trying to connect to that MySQL server <em>(remember, "shared hosting")</em>, and that there are too many people using it at the same time...</p>
<p>... And <strong>if I'm right and it's that</strong>, there's nothing you can do to solve the problem : as long as there are too many databases / users on that server and that <code>max_connection</code> is set to 200, you will continue suffering...</p>
<p><br>
As a sidenote : before going back to GoDaddy asking them about that, it would be nice if someone could validate what I just said ^^</p> |
212,657 | How do I disable query results when executing a stored procedure from a stored procedure? | <p>Within a stored procedure, another stored procedure is being called within a cursor. For every call, the SQL Management Studio results window is showing a result. The cursor loops over 100 times and at that point the results window gives up with an error. Is there a way I can stop the stored procedure within the cursor from outputting any results?</p>
<pre><code> WHILE @@FETCH_STATUS = 0
BEGIN
EXEC @RC = dbo.NoisyProc
SELECT @RValue2 = 1 WHERE @@ROWCOUNT = 0
FETCH NEXT FROM RCursor INTO @RValue1, @RValue2
END
</code></pre>
<p>Thanks!</p> | 212,833 | 7 | 2 | null | 2008-10-17 15:30:40.643 UTC | 6 | 2020-07-04 14:15:20.683 UTC | null | null | null | Alex Angas | 6,651 | null | 1 | 24 | sql-server|stored-procedures|cursors | 58,981 | <p>you could insert the results into a temp table, then drop the temp table</p>
<pre><code>create table #tmp (columns)
while
...
insert into #tmp exec @RC=dbo.NoisyProc
...
end
drop table #tmp
</code></pre>
<p>otherwise, can you modify the proc being called to accept a flag telling it not to output a result-set?</p> |
330,391 | Markdown in outlook | <p>Because this is not the kind of company where wiki's are accepted, we tend to do a lot of communication through outlook. Sending code snippets through it is painfull.
Is there some way to get the markdown thing we have here, but in outlook?</p> | 17,409,971 | 7 | 5 | null | 2008-12-01 09:46:50.633 UTC | 13 | 2019-03-12 17:53:39.4 UTC | null | null | null | boris callens | 11,333 | null | 1 | 48 | outlook|markdown | 43,852 | <p>For future visitors: <a href="https://github.com/mmanela/MarkdownOutlook" rel="noreferrer">https://github.com/mmanela/MarkdownOutlook</a></p>
<p>Per their wiki:</p>
<blockquote>
<p>A simple plugin for Outlook 2013 which adds a button to the compose mail menu to enable Markdown mode. When enabled your email will be turned from Markdown syntax to html when sending.</p>
<ul>
<li>Uses MarkdownSharp for the markdown conversion</li>
<li>Uses VSTO to integrate with Outlook</li>
<li>Uses an Installer Project to build an installer</li>
</ul>
</blockquote> |
692,856 | Set start value for AUTOINCREMENT in SQLite | <p>How can I set the start value for an AUTOINCREMENT field in SQLite?</p> | 692,861 | 7 | 0 | null | 2009-03-28 14:44:19.053 UTC | 18 | 2022-03-15 08:02:25.94 UTC | null | null | null | Christian D | 12,534 | null | 1 | 63 | sqlite | 69,526 | <p>Explicitly insert the <code>value-1</code> into the table, then delete the row.</p>
<p>Edit: the next comment down, which discusses editing the <code>SQLITE_SEQUENCE</code> table directly is probably preferable: <a href="https://stackoverflow.com/a/692871/10093">https://stackoverflow.com/a/692871/10093</a></p> |
180,030 | How can I find out when a picture was actually taken in C# running on Vista? | <p>In windows XP "FileInfo.LastWriteTime" will return the date a picture is taken - regardless of how many times the file is moved around in the filesystem.</p>
<p>In Vista it instead returns the date that the picture is copied from the camera.</p>
<p>How can I find out when a picture is taken in Vista? In windows explorer this field is referred to as "Date Taken".</p> | 7,713,780 | 8 | 0 | null | 2008-10-07 19:43:12.337 UTC | 18 | 2020-01-27 11:25:16.643 UTC | 2008-10-07 19:49:17.91 UTC | Rich B | 5,640 | rolle | 25,930 | null | 1 | 51 | c# | 46,257 | <p>Here's as fast and clean as you can get it. By using FileStream, you can tell GDI+ not to load the whole image for verification. It runs over 10 × as fast on my machine.</p>
<pre><code>//we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
private static Regex r = new Regex(":");
//retrieves the datetime WITHOUT loading the whole image
public static DateTime GetDateTakenFromImage(string path)
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (Image myImage = Image.FromStream(fs, false, false))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
return DateTime.Parse(dateTaken);
}
}
</code></pre>
<p>And yes, the correct id is 36867, not 306.</p>
<p>The other Open Source projects below should take note of this. It is a <em>huge</em> performance hit when processing thousands of files.</p> |
617,182 | How can I suppress all output from a command using Bash? | <p>I have a Bash script that runs a program with parameters. That program outputs some status (doing this, doing that...). There isn't any option for this program to be quiet. How can I prevent the script from displaying anything?</p>
<p>I am looking for something like Windows' <a href="https://ss64.com/nt/echo.html" rel="noreferrer">"echo off"</a>.</p> | 617,184 | 8 | 0 | null | 2009-03-05 23:38:25.81 UTC | 90 | 2020-06-04 14:11:59.623 UTC | 2020-02-21 19:50:46.523 UTC | Eddie | 63,550 | Wojtek | 74,480 | null | 1 | 360 | bash|shell|scripting|echo | 415,935 | <p>The following sends standard output to the null device (bit bucket).</p>
<pre><code>scriptname >/dev/null
</code></pre>
<p>And if you also want error messages to be sent there, use one of (the first may not work in all shells):</p>
<pre><code>scriptname &>/dev/null
scriptname >/dev/null 2>&1
scriptname >/dev/null 2>/dev/null
</code></pre>
<p>And, if you want to record the messages, but not see them, replace <code>/dev/null</code> with an actual file, such as:</p>
<pre><code>scriptname &>scriptname.out
</code></pre>
<p>For completeness, under Windows cmd.exe (where "nul" is the equivalent of "/dev/null"), it is:</p>
<pre><code>scriptname >nul 2>nul
</code></pre> |
392,135 | What exactly does Perl's "bless" do? | <p>I understand one uses the "bless" keyword in Perl inside a class's "new" method:</p>
<pre><code>sub new {
my $self = bless { };
return $self;
}
</code></pre>
<p>But what exactly is "bless" doing to that hash reference ? </p> | 392,146 | 8 | 1 | null | 2008-12-24 19:48:51.993 UTC | 33 | 2022-09-22 22:28:11.313 UTC | 2022-06-10 16:59:30.983 UTC | brian d foy | 1,255,289 | null | 47,145 | null | 1 | 153 | perl | 112,866 | <p>In general, <code>bless</code> associates an object with a class.</p>
<pre><code>package MyClass;
my $object = { };
bless $object, "MyClass";
</code></pre>
<p>Now when you invoke a method on <code>$object</code>, Perl know which package to search for the method.</p>
<p>If the second argument is omitted, as in your example, the current package/class is used.</p>
<p>For the sake of clarity, your example might be written as follows:</p>
<pre><code>sub new {
my $class = shift;
my $self = { };
bless $self, $class;
}
</code></pre>
<p>EDIT: See <a href="https://stackoverflow.com/users/11260/kixx">kixx</a>'s good <a href="https://stackoverflow.com/questions/392135/what-exactly-does-perls-bless-do#392194">answer</a> for a little more detail.</p> |
941,813 | How can I determine if a file is a PDF file? | <p>I am using PdfBox in Java to extract text from PDF files. Some of the input files provided are not valid and PDFTextStripper halts on these files. Is there a clean way to check if the provided file is indeed a valid PDF?</p> | 959,646 | 13 | 1 | null | 2009-06-02 20:44:33.223 UTC | 11 | 2020-05-08 11:26:55.99 UTC | 2015-08-16 16:31:05.06 UTC | null | 1,606,632 | user116219 | null | null | 1 | 39 | java|validation|pdf|text | 67,608 | <p>you can find out the mime type of a file (or byte array), so you dont dumbly rely on the extension. I do it with aperture's MimeExtractor (<a href="http://aperture.sourceforge.net/" rel="noreferrer">http://aperture.sourceforge.net/</a>) or I saw some days ago a library just for that (<a href="http://sourceforge.net/projects/mime-util" rel="noreferrer">http://sourceforge.net/projects/mime-util</a>)</p>
<p>I use aperture to extract text from a variety of files, not only pdf, but have to tweak thinks for pdfs for example (aperture uses pdfbox, but i added another library as fallback when pdfbox fails) </p> |
23,569 | Calculating Distance Between 2 Cities | <p>How do you calculate the distance between 2 cities? </p> | 23,700 | 14 | 1 | null | 2008-08-22 21:39:41.917 UTC | 13 | 2018-03-05 04:41:59.86 UTC | 2008-08-29 18:26:58.407 UTC | OysterD | 2,638 | Krishna Kumar | 2,141 | null | 1 | 16 | algorithm|math|trigonometry|geography | 15,769 | <p>If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="nofollow noreferrer">The Wikipedia article</a> probably does a better job of explaining how the formula works than me, and there's also <a href="http://www.edwilliams.org/avform.htm" rel="nofollow noreferrer">this aviation formulary page</a> that covers that goes into more detail.</p>
<p>The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from <a href="http://www.geonames.org/" rel="nofollow noreferrer">Geonames.org</a>, although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in <a href="http://en.wikipedia.org/wiki/Great-circle%5Fdistance#Worked_example" rel="nofollow noreferrer">the Wikipedia Worked Example</a>.</p>
<p>Other suggestions:</p>
<ul>
<li>For a full commercial solution,
there's <a href="http://www.alk.com/pcmiler/pcmiler-system-req.asp" rel="nofollow noreferrer">PC Miler</a> which is used
by many trucking companies to
calculate shipping rates.</li>
<li>Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server.</li>
<li>Also <strong>very important</strong> is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem.</li>
</ul>
<p>Last but not least, Joel wrote an article about this problem a while back, so here you go: <a href="http://www.joelonsoftware.com/items/2006/10/09.html" rel="nofollow noreferrer">New Feature: Job Search</a></p> |
274,861 | How do I calculate the week number given a date? | <p>If I have a date, how do I calculate the week number for that date within that year?</p>
<p>For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.</p>
<p>An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.</p>
<h3>Related:</h3>
<blockquote>
<p><a href="https://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005">Getting week number off a date in MS SQL Server 2005?</a></p>
</blockquote> | 274,913 | 15 | 1 | null | 2008-11-08 16:02:59.827 UTC | 20 | 2020-03-04 16:58:58.413 UTC | 2020-06-20 09:12:55.06 UTC | Jonathan Leffler | -1 | GH | 15,669 | null | 1 | 32 | c++|windows|algorithm|time | 83,544 | <p>Pseudocode:</p>
<pre><code>int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day
// int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this)
int weekNum = ((julian + 6) / 7) // probably better. CHECK THIS LINE. (See comments.)
if (dow < dowJan1) // adjust for being after Saturday of week #1
++weekNum;
return (weekNum)
</code></pre>
<p>To clarify, this algorithm assumes you number your weeks like this:</p>
<pre><code>S M T W R F S
1 2 3 <-- week #1
4 5 6 7 8 9 10 <-- week #2
[etc.]
</code></pre>
<p>getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.</p>
<p>If you're going to implement your own date counting routines, remember that years that are divisible by 100 are <strong>NOT</strong> leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see <a href="http://en.wikipedia.org/wiki/Calendar_reform" rel="noreferrer">Wikipedia</a> for loads of info on that.</p>
<p><a href="http://www.codeproject.com/KB/datetime/datetimedisc.aspx" rel="noreferrer">This link</a> talks about date/time functions in Windows/C++ in greater detail.</p> |
105,721 | How do I move to end of line in Vim? | <p>I know how to generally move around in command mode, specifically, jumping to lines, etc. But what is the command to jump to the end of the line that I am currently on?</p> | 105,734 | 15 | 1 | null | 2008-09-19 21:19:47.227 UTC | 307 | 2022-02-05 13:40:37.507 UTC | 2017-07-13 16:52:48.357 UTC | Stephen Deken | 331,858 | salt.racer | 757 | null | 1 | 1,367 | vim|editor|keyboard-shortcuts|vi | 907,560 | <p>Just the <kbd>$</kbd> <em>(dollar sign)</em> key. You can use <kbd>A</kbd> to move to the end of the line and switch to editing mode (Append). To jump the last non-blank character, you can press <kbd>g</kbd> then <kbd>_</kbd> keys.</p>
<p>The opposite of <kbd>A</kbd> is <kbd>I</kbd> (Insert mode at beginning of line), as an aside. Pressing just the <kbd>^</kbd> will place your cursor at the first non-white-space character of the line.</p> |
41,590 | How do you properly use namespaces in C++? | <p>I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++.</p>
<p>How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?</p> | 41,598 | 16 | 0 | null | 2008-09-03 12:54:06.637 UTC | 108 | 2021-03-22 10:23:08.403 UTC | 2014-05-23 10:11:39.347 UTC | null | 1,271,598 | Marius | 1,585 | null | 1 | 240 | c++|namespaces | 196,151 | <p>Namespaces are packages essentially. They can be used like this:</p>
<pre><code>namespace MyNamespace
{
class MyClass
{
};
}
</code></pre>
<p>Then in code:</p>
<pre><code>MyNamespace::MyClass* pClass = new MyNamespace::MyClass();
</code></pre>
<p>Or, if you want to always use a specific namespace, you can do this:</p>
<pre><code>using namespace MyNamespace;
MyClass* pClass = new MyClass();
</code></pre>
<p><strong>Edit:</strong> Following what <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41624">bernhardrusch</a> has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed).</p>
<p>And as you asked <a href="https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#41615">below</a>, you can use as many namespaces as you like.</p> |
1,337,424 | Android Spinner: Get the selected item change event | <p>How can you set the event listener for a Spinner when the selected item changes?</p>
<p>Basically what I am trying to do is something similar to this:</p>
<pre><code>spinner1.onSelectionChange = handleSelectionChange;
void handleSelectionChange(Object sender){
//handle event
}
</code></pre> | 1,714,426 | 17 | 1 | null | 2009-08-26 20:53:46.687 UTC | 79 | 2020-11-24 21:01:44.08 UTC | 2019-07-26 10:38:56.983 UTC | null | 1,000,551 | null | 93,141 | null | 1 | 444 | android|events|spinner|android-spinner | 558,532 | <p>Some of the previous answers are not correct. They work for other widgets and views, but the documentation for the <a href="http://developer.android.com/reference/android/widget/Spinner.html#setOnItemClickListener%28android.widget.AdapterView.OnItemClickListener%29" rel="noreferrer">Spinner widget</a> clearly states: </p>
<blockquote>
<p>A spinner does not support item click
events. Calling this method will raise
an exception.</p>
</blockquote>
<p>Better use <a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html" rel="noreferrer">OnItemSelectedListener()</a> instead:</p>
<pre><code>spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
</code></pre>
<p>This works for me.</p>
<p>Note that onItemSelected method is also invoked when the view is being build, so you can consider putting it inside <code>onCreate()</code> method call. </p> |
775,049 | How do I convert seconds to hours, minutes and seconds? | <p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.</p>
<p>Is there an easy way to convert the seconds to this format in Python?</p> | 775,095 | 18 | 1 | null | 2009-04-21 23:08:16.55 UTC | 134 | 2022-08-25 16:03:14.487 UTC | 2021-07-19 22:56:11.443 UTC | null | 9,868,653 | null | 54,316 | null | 1 | 656 | python|datetime | 564,763 | <p>You can use <a href="https://docs.python.org/library/datetime.html#datetime.timedelta" rel="noreferrer"><code>datetime.timedelta</code></a> function:</p>
<pre><code>>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
</code></pre> |
1,250,079 | How to escape single quotes within single quoted strings | <p>Let's say, you have a Bash <code>alias</code> like:</p>
<pre><code>alias rxvt='urxvt'
</code></pre>
<p>which works fine.</p>
<p>However:</p>
<pre class="lang-none prettyprint-override"><code>alias rxvt='urxvt -fg '#111111' -bg '#111111''
</code></pre>
<p>won't work, and neither will:</p>
<pre><code>alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''
</code></pre>
<p>So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?</p>
<pre><code>alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''
</code></pre>
<p>seems ungainly although it would represent the same string if you're allowed to concatenate them like that.</p> | 1,250,279 | 25 | 6 | null | 2009-08-08 22:50:10.983 UTC | 282 | 2022-02-02 05:04:20.06 UTC | 2019-08-27 13:34:14.63 UTC | null | 63,550 | null | 152,404 | null | 1 | 1,299 | bash|syntax|quoting | 639,475 | <p>If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:</p>
<pre><code> alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234
</code></pre>
<p>Explanation of how <code>'"'"'</code> is interpreted as just <code>'</code>:</p>
<ol>
<li><code>'</code> End first quotation which uses single quotes.</li>
<li><code>"</code> Start second quotation, using double-quotes.</li>
<li><code>'</code> Quoted character.</li>
<li><code>"</code> End second quotation, using double-quotes.</li>
<li><code>'</code> Start third quotation, using single quotes.</li>
</ol>
<p>If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.</p> |
600,743 | How to get div height to auto-adjust to background size? | <p>How do I get a div to automatically adjust to the size of the background I set for it without setting a specific height (or min-height) for it?</p> | 12,098,334 | 28 | 1 | null | 2009-03-01 23:01:20.083 UTC | 135 | 2021-11-26 20:20:31.107 UTC | 2015-10-25 01:15:01.883 UTC | null | 5,299,236 | JohnIdol | 1,311,500 | null | 1 | 330 | css|html|background|height | 549,516 | <p>Another, perhaps inefficient, solution would be to include the image under an <code>img</code> element set to <code>visibility: hidden;</code>. Then make the <code>background-image</code> of the surrounding div the same as the image.</p>
<p>This will set the surrounding div to the size of the image in the <code>img</code> element but display it as a background. </p>
<pre><code><div style="background-image: url(http://your-image.jpg);">
<img src="http://your-image.jpg" style="visibility: hidden;" />
</div>
</code></pre> |
406,230 | Regular expression to match a line that doesn't contain a word | <p>I know it's possible to match a word and then reverse the matches using other tools (e.g. <code>grep -v</code>). However, is it possible to match lines that do not contain a specific word, e.g. <code>hede</code>, using a regular expression?</p>
<h5>Input:</h5>
<pre><code>hoho
hihi
haha
hede
</code></pre>
<h5>Code:</h5>
<pre><code>grep "<Regex for 'doesn't contain hede'>" input
</code></pre>
<h5>Desired output:</h5>
<pre><code>hoho
hihi
haha
</code></pre> | 406,408 | 32 | 6 | 2009-01-02 07:30:16.097 UTC | 2009-01-02 07:30:16.097 UTC | 1,814 | 2022-07-24 23:56:29.73 UTC | 2022-07-24 23:56:29.73 UTC | unknoble | 365,102 | unknoble | 36,830 | null | 1 | 5,042 | regex|pattern-matching|regex-negation | 4,489,344 | <p>The notion that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:</p>
<pre><code>^((?!hede).)*$
</code></pre>
<p>Non-capturing variant:</p>
<pre class="lang-regex prettyprint-override"><code>^(?:(?!:hede).)*$
</code></pre>
<p>The regex above will match any string, or line without a line break, <strong>not</strong> containing the (sub)string 'hede'. As mentioned, this is not something regex is "good" at (or should do), but still, it <em>is</em> possible.</p>
<p>And if you need to match line break chars as well, use the <a href="http://perldoc.perl.org/perlre.html#Modifiers" rel="noreferrer">DOT-ALL modifier</a> (the trailing <code>s</code> in the following pattern):</p>
<pre><code>/^((?!hede).)*$/s
</code></pre>
<p>or use it inline:</p>
<pre><code>/(?s)^((?!hede).)*$/
</code></pre>
<p><em>(where the <code>/.../</code> are the regex delimiters, i.e., not part of the pattern)</em></p>
<p>If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class <code>[\s\S]</code>:</p>
<pre><code>/^((?!hede)[\s\S])*$/
</code></pre>
<h2>Explanation</h2>
<p>A string is just a list of <code>n</code> characters. Before, and after each character, there's an empty string. So a list of <code>n</code> characters will have <code>n+1</code> empty strings. Consider the string <code>"ABhedeCD"</code>:</p>
<pre><code> ┌──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┐
S = │e1│ A │e2│ B │e3│ h │e4│ e │e5│ d │e6│ e │e7│ C │e8│ D │e9│
└──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┘
index 0 1 2 3 4 5 6 7
</code></pre>
<p>where the <code>e</code>'s are the empty strings. The regex <code>(?!hede).</code> looks ahead to see if there's no substring <code>"hede"</code> to be seen, and if that is the case (so something else is seen), then the <code>.</code> (dot) will match any character except a line break. Look-arounds are also called <em>zero-width-assertions</em> because they don't <em>consume</em> any characters. They only assert/validate something.</p>
<p>So, in my example, every empty string is first validated to see if there's no <code>"hede"</code> up ahead, before a character is consumed by the <code>.</code> (dot). The regex <code>(?!hede).</code> will do that only once, so it is wrapped in a group, and repeated zero or more times: <code>((?!hede).)*</code>. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: <code>^((?!hede).)*$</code></p>
<p>As you can see, the input <code>"ABhedeCD"</code> will fail because on <code>e3</code>, the regex <code>(?!hede)</code> fails (there <em>is</em> <code>"hede"</code> up ahead!).</p> |
574,463 | Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine | <p>Like everyone else, I need to test my code on Internet Explorer 6 and Internet Explorer 7. Now Internet Explorer 8 has some great tools for developer, which I'd like to use. I'd also like to start testing my code with Internet Explorer 8, as it will soon be released.</p>
<p>The question is: how to run Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine. So far with Internet Explorer 6 and Internet Explorer 7 I've been using <a href="http://tredosoft.com/Multiple_IE?page=6" rel="noreferrer">Multiple IE</a>. But people have reported (see comments on the page linked in the previous sentence) issue with Internet Explorer 6 after installing Internet Explorer 8. Those errors are related to focus in form fields. Running Internet Explorer 7 wouldn't matter so much as Internet Explorer 8 can use the Internet Explorer 7 rendering engine, but we still need Internet Explorer 6.</p>
<p>How to run Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine?</p> | 574,465 | 38 | 8 | 2010-01-07 10:46:53.69 UTC | 2009-02-22 06:30:24.72 UTC | 168 | 2021-01-10 06:11:20.823 UTC | 2012-10-19 23:16:00.167 UTC | Techmaddy | 58,792 | Alessandro Vernet | 5,295 | null | 1 | 338 | internet-explorer|browser|internet-explorer-8|internet-explorer-7|internet-explorer-6 | 297,624 | <p>I wouldn't do it. Use virtual PCs instead. It might take a little setup, but you'll thank yourself in the long run. In my experience, you can't really get them cleanly installed side by side and unless they are standalone installs you can't really verify that it is 100% true-to-browser rendering.</p>
<p><strong>Update:</strong> Looks like one of the better ways to accomplish this (if running Windows 7) is using Windows XP mode to set up multiple virtual machines: <a href="https://docs.microsoft.com/en-us/archive/blogs/ie/testing-multiple-versions-of-ie-on-one-pc" rel="nofollow noreferrer">Testing Multiple Versions of IE on one PC</a> at the <a href="https://docs.microsoft.com/en-us/archive/blogs/ie/" rel="nofollow noreferrer">IEBlog</a>.</p>
<p><strong>Update 2:</strong> (11/2014) There are new solutions since this was last updated. Microsoft now provides VMs for any environment to test multiple versions of IE: <a href="https://web.archive.org/web/20150505043654/https://www.modern.ie/en-us/virtualization-tools" rel="nofollow noreferrer">Modern.IE</a></p> |
254,514 | Enumerations on PHP | <p>I know that PHP doesn't yet have native Enumerations. But I have become accustomed to them from the Java world. I would love to use enums as a way to give predefined values which IDEs' auto-completion features could understand.</p>
<p>Constants do the trick, but there's the namespace collision problem and (or actually <em>because</em>) they're global. Arrays don't have the namespace problem, but they're too vague, they can be overwritten at runtime and IDEs rarely know how to autofill their keys without additional static analysis annotations or attributes.</p>
<p>Are there any solutions/workarounds you commonly use? Does anyone recall whether the PHP guys have had any thoughts or decisions around enumerations?</p> | 254,543 | 39 | 6 | null | 2008-10-31 18:51:14.84 UTC | 335 | 2021-12-28 12:16:52.613 UTC | 2021-02-16 07:17:57.933 UTC | null | 1,426,539 | wolfie | 2,238 | null | 1 | 1,291 | php|enumeration | 630,525 | <p>Depending upon use case, I would normally use something <em>simple</em> like the following:</p>
<pre><code>abstract class DaysOfWeek
{
const Sunday = 0;
const Monday = 1;
// etc.
}
$today = DaysOfWeek::Sunday;
</code></pre>
<p>However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and <a href="https://stackoverflow.com/a/21536800/102937">a few other notes</a>, here's an expanded example which may better serve a much wider range of cases:</p>
<pre><code>abstract class BasicEnum {
private static $constCacheArray = NULL;
private static function getConstants() {
if (self::$constCacheArray == NULL) {
self::$constCacheArray = [];
}
$calledClass = get_called_class();
if (!array_key_exists($calledClass, self::$constCacheArray)) {
$reflect = new ReflectionClass($calledClass);
self::$constCacheArray[$calledClass] = $reflect->getConstants();
}
return self::$constCacheArray[$calledClass];
}
public static function isValidName($name, $strict = false) {
$constants = self::getConstants();
if ($strict) {
return array_key_exists($name, $constants);
}
$keys = array_map('strtolower', array_keys($constants));
return in_array(strtolower($name), $keys);
}
public static function isValidValue($value, $strict = true) {
$values = array_values(self::getConstants());
return in_array($value, $values, $strict);
}
}
</code></pre>
<p>By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:</p>
<pre><code>abstract class DaysOfWeek extends BasicEnum {
const Sunday = 0;
const Monday = 1;
const Tuesday = 2;
const Wednesday = 3;
const Thursday = 4;
const Friday = 5;
const Saturday = 6;
}
DaysOfWeek::isValidName('Humpday'); // false
DaysOfWeek::isValidName('Monday'); // true
DaysOfWeek::isValidName('monday'); // true
DaysOfWeek::isValidName('monday', $strict = true); // false
DaysOfWeek::isValidName(0); // false
DaysOfWeek::isValidValue(0); // true
DaysOfWeek::isValidValue(5); // true
DaysOfWeek::isValidValue(7); // false
DaysOfWeek::isValidValue('Friday'); // false
</code></pre>
<p>As a side note, any time I use reflection at least once <strong>on a static/const class where the data won't change</strong> (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).</p>
<p>Now that most people have <strong>finally</strong> upgraded to at least 5.3, and <code>SplEnum</code> is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum <em>instantiations</em> throughout your codebase. In the above example, <code>BasicEnum</code> and <code>DaysOfWeek</code> cannot be instantiated at all, nor should they be.</p> |
6,562,403 | I don't understand -Wl,-rpath -Wl, | <p>For convenience I added the relevant manpages below.</p>
<p>My (mis)understanding first: If I need to separate options with <code>,</code>, that means that the second <code>-Wl</code> is not another option because it comes before <code>,</code> which means it is an argument to the <code>-rpath</code> option.</p>
<p>I don't understand how <code>-rpath</code> can have a <code>-Wl,.</code> argument!</p>
<p>What would make sense in my mind would be this:</p>
<pre><code>-Wl,-rpath .
</code></pre>
<p>This should invoke <code>-rpath</code> linker option with the current directory argument.</p>
<hr />
<p>man gcc:</p>
<blockquote>
<p>-Wl,option</p>
<p>Pass option as an option to the
linker. If option contains commas, it
is split into multiple options at the
commas. You can use this syntax to
pass an argument to the option. For
example, <code>-Wl,-Map,output.map</code> passes
<code>-Map output.map</code> to the linker. When
using the GNU linker, you can also get
the same effect with
`-Wl,-Map=output.map'.</p>
</blockquote>
<p>man ld:</p>
<blockquote>
<p>-rpath=dir</p>
</blockquote>
<blockquote>
<p>Add a directory to the
runtime library search path. This is
used when linking an ELF executable
with shared objects. All -rpath
arguments are concatenated and passed
to the runtime linker, which uses them
to locate shared objects at runtime.
The -rpath option is also used when
locating shared objects which are
needed by shared objects explicitly
included in the link;</p>
</blockquote> | 6,562,437 | 4 | 2 | null | 2011-07-03 10:41:48.257 UTC | 100 | 2021-05-14 14:27:03.227 UTC | 2021-05-14 14:27:03.227 UTC | null | 4,298,200 | null | 335,355 | null | 1 | 301 | gcc|ld|rpath | 235,353 | <p>The <code>-Wl,xxx</code> option for <strong>gcc</strong> passes a comma-separated list of tokens as a space-separated list of arguments to the <strong>linker</strong>. So</p>
<pre><code>gcc -Wl,aaa,bbb,ccc
</code></pre>
<p>eventually becomes a linker call</p>
<pre><code>ld aaa bbb ccc
</code></pre>
<p>In your case, you want to say "<code>ld -rpath .</code>", so you pass this to gcc as <code>-Wl,-rpath,.</code> Alternatively, you can specify repeat instances of <code>-Wl</code>:</p>
<pre><code>gcc -Wl,aaa -Wl,bbb -Wl,ccc
</code></pre>
<p>Note that there is no comma between <code>aaa</code> and the second <code>-Wl</code>.</p>
<p>Or, in your case, <code>-Wl,-rpath -Wl,.</code>.</p> |
6,570,206 | Reinstalling NuGet packages with NuGet installed as VS Extension | <p>I would like to be able to install all of the NuGet packages in the packages.config, as per <a href="http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages" rel="noreferrer">The NuGet docs</a>. NuGet is installed as a VS Extension, and I can't seem to find nuget.exe. Is it possible to run:</p>
<blockquote>
<p>nuget i packages.config -o Packages</p>
</blockquote>
<p>Without maintaining a seperate copy of nuget.exe on a per project basis?</p> | 9,846,407 | 5 | 0 | null | 2011-07-04 10:27:22.267 UTC | 6 | 2018-08-23 23:38:32.773 UTC | null | null | null | null | 2,240 | null | 1 | 40 | visual-studio|nuget|nuget-package | 42,899 | <p>As an update to this post, NuGet 1.6 added support for the workflow to restore the packages at build time if missing.
Right-Click on the solution, click "Enable Package Restore Mode" to set it on.</p>
<p>More details at:
<a href="http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages">http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages</a></p> |
6,879,501 | Filter git diff by type of change | <p>Is there a way to limit <code>git diff</code> to changed files?</p>
<p>I'd like to see the differences between two commits, but exclude paths that don't exist in one or the other (additions/deletions). The following Perl one-liner illustrates most of what I want:</p>
<pre><code>git diff master.. | perl -lnwe 'print unless /^(new|deleted) file/../^diff/ and not /^diff/'
</code></pre>
<p>But that leaves <code>diff --git a/path b/path</code> lines for the files that were new or deleted. Plus it'd be much nicer if I didn't have to parse (also fails if any hunk contains anything matching /^diff/, for example).</p>
<p>Another alternative I tried was:</p>
<pre><code>git diff --name-status (args) | perl -lnwe 'print if s/^M\s+//' | xargs git diff (args) --
</code></pre>
<p>Its output is better, but it still feels hackish.</p> | 6,879,568 | 5 | 0 | null | 2011-07-29 22:05:35.537 UTC | 54 | 2022-02-19 23:34:10.567 UTC | null | null | null | null | 82,723 | null | 1 | 146 | git|diff | 66,107 | <p>You are looking for <code>--diff-filter=M</code> to show only files *<em>M</em>*odified between the two branches. </p>
<p>From <code>man git-diff</code></p>
<blockquote>
<p><code>--diff-filter=[ACDMRTUXB*]</code></p>
<p>Select only files that are</p>
<ul>
<li><code>A</code> Added</li>
<li><code>C</code> Copied</li>
<li><code>D</code> Deleted</li>
<li><code>M</code> Modified</li>
<li><code>R</code> Renamed</li>
<li><code>T</code> have their type (mode) changed</li>
<li><code>U</code> Unmerged</li>
<li><code>X</code> Unknown</li>
<li><code>B</code> have had their pairing Broken</li>
<li><code>*</code> All-or-none</li>
</ul>
<p>Any combination of the filter characters may be used. </p>
<p>When * (All-or-none) is added to the combination, all paths are
selected if there is any file that matches other criteria in the
comparison; if there is no file that matches other criteria, nothing
is selected.</p>
</blockquote> |
6,579,287 | Magento get language code in template file | <p>I need a helper function to get the current language code. I want to use it in a templete file, like /products/view.phtml, only for testing purposes.</p>
<p>Does it already exist?</p>
<p>I have something in mind like the URL-helper</p>
<pre><code>$url = $this->helper('core/url')->getCurrentUrl();
</code></pre> | 6,579,763 | 6 | 0 | null | 2011-07-05 07:36:28.173 UTC | 7 | 2015-08-20 08:44:05.177 UTC | null | null | null | null | 95,914 | null | 1 | 19 | php|magento | 59,285 | <p>You can get the current locale code this way :</p>
<pre><code>$locale = Mage::app()->getLocale()->getLocaleCode();
</code></pre> |
6,746,649 | How can I hide an element off the edge of the screen? | <p>I've got a div that I want to position partially off-screen like so:</p>
<pre class="lang-css prettyprint-override"><code>div {
position: absolute;
height: 100px;
width: 100px;
right: -50px;
top: 50px;
}
</code></pre>
<p>But this increases the size of the page, allowing it to be scrolled to the right. Is there any way to keep half of this div hidden and prevent scrolling to view it?</p> | 6,746,694 | 8 | 0 | null | 2011-07-19 11:49:59.87 UTC | 9 | 2022-08-24 14:27:19.427 UTC | 2022-06-05 02:29:28.52 UTC | null | 1,864,883 | null | 464,154 | null | 1 | 37 | html|css | 107,512 | <p>Yes, just create an enclosing div with <code>overflow: hidden</code>, like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer {
overflow: hidden;
position: relative;
}
.inner {
position: absolute;
height: 100px;
width: 100px;
right: -50px;
top: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
<div class="inner">
CONTENT
</div>
</div></code></pre>
</div>
</div>
</p>
<p>Example: <a href="http://jsfiddle.net/Uj3eQ/" rel="noreferrer">http://jsfiddle.net/Uj3eQ/</a></p> |
6,324,826 | Converting ArrayList of Characters to a String? | <p>How to convert an <code>ArrayList<Character></code> to a <code>String</code> in Java?</p>
<p>The <code>List.toString</code> method returns it as <code>[a,b,c]</code> string - I want to get rid of the brackets (etcetera) and store it as <code>abc</code>.</p> | 6,324,852 | 11 | 0 | null | 2011-06-12 21:34:31.933 UTC | 10 | 2021-08-28 01:20:44.773 UTC | 2021-08-28 01:20:44.773 UTC | null | 139,985 | null | 701,441 | null | 1 | 40 | java|string|collections | 77,020 | <p>You can iterate through the list and create the string.</p>
<pre><code>String getStringRepresentation(ArrayList<Character> list)
{
StringBuilder builder = new StringBuilder(list.size());
for(Character ch: list)
{
builder.append(ch);
}
return builder.toString();
}
</code></pre>
<p>Setting the capacity of the <code>StringBuilder</code> to the list size is an important optimization. If you don't do this, some of the <code>append</code> calls may trigger an internal resize of the builder.</p>
<p>As an aside, <code>toString()</code> returns a human-readable format of the ArrayList's contents. It is not worth the time to filter out the unnecessary characters from it. It's implementation could change tomorrow, and you will have to rewrite your filtering code.</p> |
41,580,798 | How to Play Audio File Into Channel? | <p>How do you play an audio file from a Discord bot? Needs to play a local file, be in JS, and upon a certain message being sent it will join the user who typed the message, and will play the file to that channel.</p> | 41,580,799 | 5 | 1 | null | 2017-01-11 00:24:55.767 UTC | 15 | 2021-01-01 01:26:41.623 UTC | 2018-03-24 17:17:49.903 UTC | null | 6,195,472 | null | 5,101,446 | null | 1 | 19 | javascript|bots|discord|discord.js | 110,187 | <p>GitHub Project: <a href="https://github.com/NickJohn547745/DiscordBotSpeak" rel="noreferrer">LINK</a></p>
<p>In order to do this there are a few things you have to make sure of first.</p>
<ol>
<li>Have FFMPEG installed & the environment path set for it in Windows [<a href="http://adaptivesamples.com/how-to-install-ffmpeg-on-windows/" rel="noreferrer">link</a>]</li>
<li>Have Microsoft Visual Studio (VS) installed [<a href="https://go.microsoft.com/fwlink/?LinkId=691978&clcid=0x409" rel="noreferrer">link</a>]</li>
<li>Have Node.js installed.[<a href="https://nodejs.org/dist/v7.4.0/node-v7.4.0-x64.msi" rel="noreferrer">link</a>]</li>
<li>Have Discord.js installed in VS.</li>
</ol>
<p>From there the steps are quite simple. After making your project <code>index.js</code> you will start typing some code. Here are the steps:</p>
<ol>
<li>Add the Discord.js dependency to the project;</li>
</ol>
<p><code>var Discord = require('discord.js');</code></p>
<ol start="2">
<li>Create out client variable called <em>bot</em>;</li>
</ol>
<p><code>var bot = new Discord.Client();</code>
3. Create a Boolean variable to make sure that the system doesn't overload of requests;</p>
<p><code>var isReady = true;</code></p>
<ol start="4">
<li>Next make the function to intercept the correct message;</li>
</ol>
<p><code>bot.on('message', message =>{ENTER CODE HERE});</code></p>
<ol start="5">
<li>Create an <em>if statement</em> to check if the message is correct & if the bot is ready;</li>
</ol>
<p><code>if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}</code></p>
<ol start="6">
<li>Set the bot to unready so that it cannot process events until it finishes;</li>
</ol>
<p><code>isReady = false;</code></p>
<ol start="7">
<li>Create a variable for the channel that the message-sender is currently in;</li>
</ol>
<p><code>var voiceChannel = message.member.voice.channel;</code></p>
<ol start="8">
<li>Join that channel and keep track of all errors;</li>
</ol>
<p><code>voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));</code></p>
<ol start="9">
<li>Create a refrence to and play the audio file;</li>
</ol>
<p><code>const dispatcher = connection.play('./audiofile.mp3');</code></p>
<ol start="10">
<li>Slot to wait until the audio file is done playing;</li>
</ol>
<p><code>dispatcher.on("end", end => {ENTER CODE HERE});</code></p>
<ol start="11">
<li>Leave channel after audio is done playing;</li>
</ol>
<p><code>voiceChannel.leave();</code></p>
<ol start="12">
<li>Login to the application;</li>
</ol>
<p><code>bot.login('CLIENT TOKEN HERE');</code></p>
<p>After you are all finished with this, make sure to check for any un-closed brackets or parentheses. i made this because it took my hours until I finally found a good solution so I just wanted to share it with anybody who is out there looking for something like this.</p> |
15,995,461 | Node.js pass variable to route | <p>I have very simple node.js noob question. How do I pass a variable to an exported route function?</p>
<p>Routes file</p>
<pre><code>exports.gettop = function(n, req, res) {
console.log(n);
res.send(200);
};
</code></pre>
<p>Server file</p>
<pre><code>app.get('/api/v1/top100', routes.gettop(100));
</code></pre>
<p>Error: .get() requires callback functions but got a [object Undefined]</p> | 15,995,649 | 4 | 0 | null | 2013-04-14 03:28:34.047 UTC | 8 | 2018-08-14 19:33:36.69 UTC | null | null | null | null | 1,071,182 | null | 1 | 15 | node.js|express | 24,726 | <p>For your example, you want to create a new function that will close around your value of <code>n</code>. In your case, you are executing <code>gettop</code> and passing the returned value to express as your route, which means <code>gettop</code> needs to return the route handler.</p>
<pre><code>exports.gettop = function(n){
return function(req, res) {
console.log(n);
res.send(200);
};
};
</code></pre> |
15,925,319 | How to disable android map marker click auto center | <p>I am looking for a way to disable my map fragment's auto centre on selected marker functionality. I still want the markers InfoWindow to show up, but just not centre the entire map on the marker I have selected.</p> | 15,925,395 | 4 | 1 | null | 2013-04-10 12:04:35.887 UTC | 6 | 2020-06-28 09:12:27.153 UTC | 2013-04-10 12:05:49.58 UTC | null | 928,814 | null | 1,225,552 | null | 1 | 37 | android|android-fragments|google-maps-api-2 | 22,442 | <p>Take a look at the following post:</p>
<p><a href="https://stackoverflow.com/questions/14497734/dont-snap-to-marker-after-click-in-android-map-v2">Don't snap to marker after click in android map v2</a></p>
<p>There is a method given there by <strong>@DMan</strong>, basically you need to consume the <code>OnMarkerClick</code> event and override the default behavior:</p>
<pre><code>// Since we are consuming the event this is necessary to
// manage closing openned markers before openning new ones
Marker lastOpenned = null;
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
// Check if there is an open info window
if (lastOpenned != null) {
// Close the info window
lastOpenned.hideInfoWindow();
// Is the marker the same marker that was already open
if (lastOpenned.equals(marker)) {
// Nullify the lastOpenned object
lastOpenned = null;
// Return so that the info window isn't openned again
return true;
}
}
// Open the info window for the marker
marker.showInfoWindow();
// Re-assign the last openned such that we can close it later
lastOpenned = marker;
// Event was handled by our code do not launch default behaviour.
return true;
}
});
</code></pre> |
15,511,874 | File to import not found or unreadable: compass | <p>I successfully installed Sass, but I'm having trouble importing Compass.</p>
<p>The following is the error detail:</p>
<pre><code>*Syntax error: File to import not found or unreadable: compass.
Load path: H:/HTML/___keoFull/sass
.....
Backtrace:
mainKeo.scss:2
style.scss:2
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/import_node.rb:67:in `rescue in import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/import_node.rb:45:in `import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/import_node.rb:28:in `imported_file'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/import_node.rb:37:in `css_import?'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:217:in `visit_import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:227:in `block in visit_import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:227:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:227:in `visit_import'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:53:in `map'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:53:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:121:in `with_environment'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:108:in `visit_children'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:37:in `block in visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:128:in `visit_root'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/base.rb:37:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:100:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/visitors/perform.rb:7:in `visit'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/tree/root_node.rb:20:in `render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/engine.rb:315:in `_render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/engine.rb:262:in `render'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin/compiler.rb:341:in `update_stylesheet'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin/compiler.rb:203:in `block in update_stylesheets'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin/compiler.rb:201:in `each'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin/compiler.rb:201:in `update_stylesheets'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin/compiler.rb:235:in `watch'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/plugin.rb:107:in `method_missing'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/exec.rb:444:in `watch_or_update'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/exec.rb:307:in `process_result'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/exec.rb:41:in `parse'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/lib/sass/exec.rb:21:in `parse!'
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sass-3.2.6/bin/sass:9:in `<top (required)>'*
</code></pre> | 15,591,530 | 5 | 2 | null | 2013-03-19 22:39:08.853 UTC | 10 | 2016-09-26 22:06:52.853 UTC | 2013-03-19 22:55:47.363 UTC | null | 1,052,923 | null | 1,391,284 | null | 1 | 46 | sass|compass-sass | 129,404 | <p>Compass adjusts the way partials are imported. It allows importing components based solely on their name, without specifying the path.</p>
<p>Before you can do <code>@import 'compass';</code>, you should:</p>
<p>Install Compass as a Ruby gem:</p>
<pre><code>gem install compass
</code></pre>
<p>After that, you should use Compass's own command line tool to compile your SASS code:</p>
<pre><code>cd path/to/your/project/
compass compile
</code></pre>
<p>Note that Compass reqiures a configuration file called <code>config.rb</code>. You should create it for Compass to work.</p>
<p>The minimal <code>config.rb</code> can be as simple as this:
</p>
<pre><code>css_dir = "css"
sass_dir = "sass"
</code></pre>
<p>And your SASS code should reside in <code>sass/</code>.</p>
<p>Instead of creating a configuration file manually, you can create an empty Compass project with <code>compass create <project-name></code> and then copy your SASS code inside it.</p>
<p>Note that if you want to use Compass extensions, you will have to:</p>
<ol>
<li>require them from the <code>config.rb</code>;</li>
<li>import them from your SASS file.</li>
</ol>
<p>More info here: <a href="http://compass-style.org/help/">http://compass-style.org/help/</a></p> |
10,437,058 | How to make Entity Framework Data Context Readonly | <p>I need to expose an Entity Framework Data Context to 3rd party plugins. The purpose is to allow these plugins to fetch data only and not to let them issue inserts, updates or deletes or any other database modification commands. Hence how can I make a data context or entity readonly.</p> | 10,438,977 | 8 | 3 | null | 2012-05-03 18:12:56.41 UTC | 45 | 2022-09-15 12:09:20.67 UTC | 2012-12-03 23:04:22.54 UTC | null | 41,956 | null | 454,378 | null | 1 | 134 | .net|entity-framework|entity-framework-4|datacontext|readonly | 65,283 | <p>In addition to connecting with a read-only user, there are a few other things you can do to your DbContext.</p>
<pre><code>public class MyReadOnlyContext : DbContext
{
// Use ReadOnlyConnectionString from App/Web.config
public MyContext()
: base("Name=ReadOnlyConnectionString")
{
}
// Don't expose Add(), Remove(), etc.
public DbQuery<Customer> Customers
{
get
{
// Don't track changes to query results
return Set<Customer>().AsNoTracking();
}
}
public override int SaveChanges()
{
// Throw if they try to call this
throw new InvalidOperationException("This context is read-only.");
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Need this since there is no DbSet<Customer> property
modelBuilder.Entity<Customer>();
}
}
</code></pre> |
10,588,291 | Git branching: master vs. origin/master vs. remotes/origin/master | <p>I think I'm on the right track to understand the basic concepts of git.</p>
<p>I've already set up and cloned a remote repository. I also created a server side empty repository, and linked my local repository to it.</p>
<p>My problem is that I don't understand the difference between:</p>
<ul>
<li>origin/master vs. remotes/origin/master</li>
</ul>
<p>As far as I have understood, <strong>master</strong> is a local branch, and <strong>remotes/origin/master</strong> is a remote one. </p>
<p>But what exactly is <strong>origin/master</strong>?</p> | 10,588,561 | 7 | 5 | null | 2012-05-14 17:33:26.583 UTC | 108 | 2022-02-24 23:18:00.233 UTC | 2022-02-24 23:18:00.233 UTC | null | 6,862,601 | null | 1,020,719 | null | 1 | 225 | git|git-branch|git-remote | 133,854 | <p>Take a clone of a remote repository and run <code>git branch -a</code> (to show all the branches git knows about). It will probably look something like this:</p>
<pre><code>* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
</code></pre>
<p>Here, <code>master</code> is a branch in the local repository. <code>remotes/origin/master</code> is a branch named <code>master</code> on the remote named <code>origin</code>. You can refer to this as either <code>origin/master</code>, as in:</p>
<pre><code>git diff origin/master..master
</code></pre>
<p>You can also refer to it as <code>remotes/origin/master</code>:</p>
<pre><code>git diff remotes/origin/master..master
</code></pre>
<p>These are just two different ways of referring to the same thing (incidentally, both of these commands mean "show me the changes between the remote <code>master</code> branch and my <code>master</code> branch).</p>
<p><code>remotes/origin/HEAD</code> is the <code>default branch</code> for the remote named <code>origin</code>. This lets you simply say <code>origin</code> instead of <code>origin/master</code>.</p> |
33,759,514 | model->save() Not Working In Yii2 | <p>Previously, I was not using <code>$model->save()</code> function for inserting or updating any data. I was simply using <code>createCommand()</code> to execute query and it was working successfully. But, my team members asked me to avoid <code>createCommand()</code> and use <code>$model->save();</code> </p>
<p>Now, I started cleaning my code and problem is <code>$model->save();</code> not working for me. I don't know where i did mistake.</p>
<p><strong>UsersController.php</strong> (Controller)</p>
<pre><code><?php
namespace app\modules\users\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\swiftmailer\Mailer;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use app\modules\users\models\Users;
use app\controllers\CommonController;
class UsersController extends CommonController
{
.
.
public function actionRegister() {
$model = new Users();
// For Ajax Email Exist Validation
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post())) {
$post = Yii::$app->request->post('Users');
$CheckExistingUser = $model->findOne(['email' => $post['email']]);
// Ok. Email Doesn't Exist
if(!$CheckExistingUser) {
$auth_key = $model->getConfirmationLink();
$password = md5($post['password']);
$registration_ip = Yii::$app->getRequest()->getUserIP();
$created_at = date('Y-m-d h:i:s');
$model->auth_key = $auth_key;
$model->password = $password;
$model->registration_ip = $registration_ip;
$model->created_at = $created_at;
if($model->save()) {
print_r("asd");
}
}
}
}
.
.
}
</code></pre>
<p>Everything OK in this except <code>$model->save();</code> Not printing <strong>'asd'</strong> as i echoed it. </p>
<p>And, if i write </p>
<pre><code>else if ($model->load(Yii::$app->request->post() && $model->validate()) {
}
</code></pre>
<p>It's not entering to this <code>if</code> condition. </p>
<p>And, if i write</p>
<pre><code>if($model->save(false)) {
print_r("asd");
}
</code></pre>
<p>It insert NULL to all columns and print <strong>'asd'</strong></p>
<p><strong>Users.php</strong> (model)</p>
<pre><code><?php
namespace app\modules\users\models;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
use app\modules\users\models\UserType;
class Users extends ActiveRecord implements IdentityInterface
{
public $id;
public $first_name;
public $last_name;
public $email;
public $password;
public $rememberMe;
public $confirm_password;
public $user_type;
public $company_name;
public $status;
public $auth_key;
public $confirmed_at;
public $registration_ip;
public $verify_code;
public $created_at;
public $updated_at;
public $_user = false;
public static function tableName() {
return 'users';
}
public function rules() {
return [
//First Name
'FirstNameLength' => ['first_name', 'string', 'min' => 3, 'max' => 255],
'FirstNameTrim' => ['first_name', 'filter', 'filter' => 'trim'],
'FirstNameRequired' => ['first_name', 'required'],
//Last Name
'LastNameLength' => ['last_name', 'string', 'min' => 3, 'max' => 255],
'LastNameTrim' => ['last_name', 'filter', 'filter' => 'trim'],
'LastNameRequired' => ['last_name', 'required'],
//Email ID
'emailTrim' => ['email', 'filter', 'filter' => 'trim'],
'emailRequired' => ['email', 'required'],
'emailPattern' => ['email', 'email'],
'emailUnique' => ['email', 'unique', 'message' => 'Email already exists!'],
//Password
'passwordRequired' => ['password', 'required'],
'passwordLength' => ['password', 'string', 'min' => 6],
//Confirm Password
'ConfirmPasswordRequired' => ['confirm_password', 'required'],
'ConfirmPasswordLength' => ['confirm_password', 'string', 'min' => 6],
['confirm_password', 'compare', 'compareAttribute' => 'password'],
//Admin Type
['user_type', 'required'],
//company_name
['company_name', 'required', 'when' => function($model) {
return ($model->user_type == 2 ? true : false);
}, 'whenClient' => "function (attribute, value) {
return $('input[type=\"radio\"][name=\"Users[user_type]\"]:checked').val() == 2;
}"], #'enableClientValidation' => false
//Captcha
['verify_code', 'captcha'],
[['auth_key','registration_ip','created_at'],'safe']
];
}
public function attributeLabels() {
return [
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email',
'password' => 'Password',
'user_type' => 'User Type',
'company_name' => 'Company Name',
'status' => 'Status',
'auth_key' => 'Auth Key',
'confirmed_at' => 'Confirmed At',
'registration_ip' => 'Registration Ip',
'confirm_id' => 'Confirm ID',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'verify_code' => 'Verification Code',
];
}
//custom methods
public static function findIdentity($id) {
return static::findOne($id);
}
public static function instantiate($row) {
return new static($row);
}
public static function findIdentityByAccessToken($token, $type = null) {
throw new NotSupportedException('Method "' . __CLASS__ . '::' . __METHOD__ . '" is not implemented.');
}
public function getId() {
return $this->id;
}
public function getAuthKey() {
return $this->auth_key;
}
public function validateAuthKey($authKey) {
return $this->auth_key === $auth_key;
}
public function validatePassword($password) {
return $this->password === $password;
}
public function getFirstName() {
return $this->first_name;
}
public function getLastName() {
return $this->last_name;
}
public function getEmail() {
return $this->email;
}
public function getCompanyName() {
return $this->company_name;
}
public function getUserType() {
return $this->user_type;
}
public function getStatus() {
return $this->status;
}
public function getUserTypeValue() {
$UserType = $this->user_type;
$UserTypeValue = UserType::find()->select(['type'])->where(['id' => $UserType])->one();
return $UserTypeValue['type'];
}
public function getCreatedAtDate() {
$CreatedAtDate = $this->created_at;
$CreatedAtDate = date('d-m-Y h:i:s A', strtotime($CreatedAtDate));
return $CreatedAtDate;
}
public function getLastUpdatedDate() {
$UpdatedDate = $this->updated_at;
if ($UpdatedDate != 0) {
$UpdatedDate = date('d-m-Y h:i:s A', strtotime($UpdatedDate));
return $UpdatedDate;
} else {
return '';
}
}
public function register() {
if ($this->validate()) {
return true;
}
return false;
}
public static function findByEmailAndPassword($email, $password) {
$password = md5($password);
$model = Yii::$app->db->createCommand("SELECT * FROM users WHERE email ='{$email}' AND password='{$password}' AND status=1");
$users = $model->queryOne();
if (!empty($users)) {
return new Users($users);
} else {
return false;
}
}
public static function getConfirmationLink() {
$characters = 'abcedefghijklmnopqrstuvwxyzzyxwvutsrqponmlk';
$confirmLinkID = '';
for ($i = 0; $i < 10; $i++) {
$confirmLinkID .= $characters[rand(0, strlen($characters) - 1)];
}
return $confirmLinkID = md5($confirmLinkID);
}
}
</code></pre>
<p>Any help is appreciable. Please Help me.</p> | 33,761,428 | 10 | 19 | null | 2015-11-17 14:33:18.737 UTC | 4 | 2019-05-14 10:00:27.46 UTC | 2015-11-17 17:09:51.78 UTC | null | 3,682,583 | null | 3,682,583 | null | 1 | 17 | php|yii2|yii2-basic-app|yii2-model | 78,701 | <p>It could be a problem related with your validation rules.</p>
<p>Try, as a test, to save the model without any validation in this way: </p>
<pre><code>$model->save(false);
</code></pre>
<p>If the model is saved you have conflict with your validation rules. Try selectively removing your validation rule(s) to find the validation conflict.</p>
<p>If you have redefined the value present in active record you don't assign the value to the var for db but for this new var and then are not save. </p>
<p>Try removing the duplicated var.. (only the vars non mapped to db should be declared here.)</p> |
35,352,638 | How to get parameter value from query string? | <p>How can I define a route in my routes.jsx file to capture the <code>__firebase_request_key</code> parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers?</p>
<pre><code>http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
</code></pre>
<p>I tried with the following routes configuration, but the <code>:redirectParam</code> is not catching the mentioned param:</p>
<pre><code><Router>
<Route path="/" component={Main}>
<Route path="signin" component={SignIn}>
<Route path=":redirectParam" component={TwitterSsoButton} />
</Route>
</Route>
</Router>
</code></pre> | 37,568,368 | 45 | 5 | null | 2016-02-12 00:19:13.203 UTC | 149 | 2022-09-24 03:05:09.497 UTC | 2021-11-27 20:31:40.103 UTC | null | 13,699,024 | null | 1,865,075 | null | 1 | 732 | reactjs|react-router | 1,525,458 | <p><strong>React Router v6, using hooks</strong></p>
<p>In react-router-dom v6 there's a new hook named <a href="https://reactrouter.com/docs/en/v6/hooks/use-search-params" rel="noreferrer">useSearchParams</a>. So with</p>
<pre><code>const [searchParams, setSearchParams] = useSearchParams();
searchParams.get("__firebase_request_key")
</code></pre>
<p>you will get <code>"blablabla"</code>. Note, that searchParams is an instance of URLSearchParams, which also implements an iterator, e.g. for using Object.fromEntries etc.</p>
<p><strong>React Router v4/v5, without hooks, generic</strong></p>
<p>React Router v4 does not parse the query for you any more, but you can only access it via <code>this.props.location.search</code> (or useLocation, see below). For reasons see <a href="https://stackoverflow.com/a/48256676/969483">nbeuchat's answer</a>.</p>
<p>E.g. with <a href="https://github.com/ljharb/qs" rel="noreferrer">qs</a> library imported as <code>qs</code> you could do</p>
<pre><code>qs.parse(this.props.location.search, { ignoreQueryPrefix: true }).__firebase_request_key
</code></pre>
<p>Another library would be <a href="https://github.com/sindresorhus/query-string" rel="noreferrer">query-string</a>. See <a href="https://stackoverflow.com/a/53079875/969483">this answer</a> for some more ideas on parsing the search string. If you do not need <a href="https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams" rel="noreferrer">IE-compatibility</a> you can also use</p>
<pre><code>new URLSearchParams(this.props.location.search).get("__firebase_request_key")
</code></pre>
<p>For functional components you would replace <code>this.props.location</code> with the hook <a href="https://reacttraining.com/react-router/core/api/Hooks/uselocation" rel="noreferrer">useLocation</a>. Note, you could use <code>window.location.search</code>, but this won't allow to trigger React rendering on changes.
If your (non-functional) component is not a direct child of a <code>Switch</code> you need to use <a href="https://reacttraining.com/react-router/web/api/withRouter" rel="noreferrer">withRouter</a> to access any of the router provided props.</p>
<p><strong>React Router v3</strong></p>
<p>React Router already parses the location for you and passes it to your <a href="https://reacttraining.com/react-router/core/api/Route/Route-props" rel="noreferrer">RouteComponent</a> as props. You can access the query (after ? in the url) part via</p>
<pre><code>this.props.location.query.__firebase_request_key
</code></pre>
<p>If you are looking for the path parameter values, separated with a colon (:) inside the router, these are accessible via</p>
<pre><code>this.props.match.params.redirectParam
</code></pre>
<p>This applies to late React Router v3 versions (not sure which). Older router versions were reported to use <code>this.props.params.redirectParam</code>.</p>
<p><strong>General</strong></p>
<p>nizam.sp's suggestion to do</p>
<pre><code>console.log(this.props)
</code></pre>
<p>will be helpful in any case.</p> |
33,495,617 | How to use async lambda with SelectMany? | <p>I'm getting the following error when trying to use an <code>async</code> lambda within <code>IEnumerable.SelectMany</code>:</p>
<pre><code>var result = myEnumerable.SelectMany(async (c) => await Functions.GetDataAsync(c.Id));
</code></pre>
<blockquote>
<p>The type arguments for method 'IEnumerable
System.Linq.Enumerable.SelectMany(this
IEnumerable, Func>)' cannot be
inferred from the usage. Try specifying the type arguments explicitly</p>
</blockquote>
<p>Where <code>GetDataAsync</code> is defined as:</p>
<pre><code>public interface IFunctions {
Task<IEnumerable<DataItem>> GetDataAsync(string itemId);
}
public class Functions : IFunctions {
public async Task<IEnumerable<DataItem>> GetDataAsync(string itemId) {
// return await httpCall();
}
}
</code></pre>
<p>I guess because my <code>GetDataAsync</code> method actually returns a <code>Task<IEnumerable<T>></code>. But why does <code>Select</code> work, surely it should throw the same error?</p>
<pre><code>var result = myEnumerable.Select(async (c) => await Functions.GetDataAsync(c.Id));
</code></pre>
<p>Is there any way around this?</p> | 33,495,923 | 4 | 10 | null | 2015-11-03 09:32:58.6 UTC | 1 | 2021-10-15 12:22:42.593 UTC | 2015-11-03 09:48:01.343 UTC | null | 571,194 | null | 571,194 | null | 1 | 39 | c#|linq|lambda|linq-to-objects | 16,159 | <p>async lambda expression cannot be converted to simple <code>Func<TSource, TResult></code>.</p>
<p>So, select many cannot be used. You can run in synchronized context:</p>
<pre><code>myEnumerable.Select(c => Functions.GetDataAsync(c.Id)).SelectMany(task => task.Result);
</code></pre>
<p>or</p>
<pre><code>List<DataItem> result = new List<DataItem>();
foreach (var ele in myEnumerable)
{
result.AddRange(await Functions.GetDataAsyncDo(ele.Id));
}
</code></pre>
<p>You cannot neither use <code>yield return</code> - it is by design. f.e.:</p>
<pre><code>public async Task<IEnuemrable<DataItem>> Do()
{
...
foreach (var ele in await Functions.GetDataAsyncDo(ele.Id))
{
yield return ele; // compile time error, async method
// cannot be used with yield return
}
}
</code></pre> |
22,771,425 | Window.Open with PDF stream instead of PDF location | <p>Based on the question <a href="https://stackoverflow.com/q/20401006/1366033">Open PDF in new browser full window</a>, it looks like I can use JavaScript to open a new window with a PDF file with the following code:</p>
<pre class="lang-js prettyprint-override"><code>window.open('MyPDF.pdf', '_blank');
</code></pre>
<p>I'd like to do so on a return trip from the server by adding a byte array instead of the file name to use as the URL location in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.open" rel="noreferrer"><code>window.open</code></a></p>
<p>I'm currently returning PDF files like <a href="https://stackoverflow.com/a/2057883/1366033">this</a>:</p>
<pre class="lang-cs prettyprint-override"><code>Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(pdfByteArray);
Response.Flush();
</code></pre>
<p>Is there a way to open a new window with a PDF byte array in javascript. </p>
<p>Something like this:</p>
<pre class="lang-cs prettyprint-override"><code>var script = "window.open('" + pdfByteArray + "', '_blank');";
ScriptManager.RegisterClientScriptBlock(Parent.Page, typeof(Page), "pdf", script, true);
</code></pre> | 22,772,841 | 3 | 2 | null | 2014-03-31 20:21:18.947 UTC | 11 | 2021-11-11 18:01:30.333 UTC | 2017-05-23 12:03:05.75 UTC | null | -1 | null | 1,366,033 | null | 1 | 33 | javascript|asp.net|.net|pdf|window.open | 144,316 | <p>It looks like <code>window.open</code> will take a Data URI as the location parameter.</p>
<p>So you can open it like this from the question: <a href="https://stackoverflow.com/q/2805330/1366033">Opening PDF String in new window with javascript</a>:</p>
<pre class="lang-js prettyprint-override"><code>window.open("data:application/pdf;base64, " + base64EncodedPDF);
</code></pre>
<p>Here's an <a href="https://run.plnkr.co/plunks/tv3Cma/" rel="noreferrer">runnable</a> <a href="https://plnkr.co/edit/tv3Cma/" rel="noreferrer">example in plunker</a>, and <a href="https://run.plnkr.co/plunks/tv3Cma/global-vars.js" rel="noreferrer">sample pdf file</a> that's already base64 encoded.</p>
<p>Then on the server, you can convert the byte array to base64 encoding like this:</p>
<pre class="lang-cs prettyprint-override"><code>string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
</code></pre>
<p><strong>NOTE</strong>: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.</p> |
22,547,575 | execute commands as user after Vagrant provisioning | <p>There are some commands that have to be run as a normal user after the initial provisioning. I thought I could do this using a separate shell script and the command <code>su --login -c <command> vagrant</code>, but it's not getting the user's path or other environment settings from .bashrc.</p>
<p>e.g.:</p>
<pre><code>#!/usr/bin/env bash
su --login -c "rbenv install 2.0.0-p353" vagrant
su --login -c "rbenv global 2.0.0-p353" vagrant
su --login -c "gem update --system" vagrant
su --login -c "yes | gem update" vagrant
su --login -c "gem install rdoc" vagrant
su --login -c "gem install rails pg" vagrant
</code></pre>
<p>Is there a way to do this? Maybe it has to be done with another provisioning tool like Puppet or Chef? I've thought of creating another shell script that sources the <code>.bashrc</code>, copying it to the box using a :file provisioner and executing the commands like that, but it seems sort of like a hack.</p>
<p>What's the right way to do this?</p> | 22,556,979 | 4 | 2 | null | 2014-03-20 23:53:38.987 UTC | 19 | 2020-04-08 08:52:20.837 UTC | null | null | null | null | 2,948,042 | null | 1 | 83 | shell|vagrant | 39,644 | <p>You should be able to do this using the <a href="http://docs.vagrantup.com/v2/provisioning/shell.html" rel="noreferrer">Vagrant Shell provisioner</a>, e.g.</p>
<pre><code>Vagrant.configure("2") do |config|
$script = <<-SCRIPT
rbenv install 2.0.0-p353
rbenv global 2.0.0-p353
gem update --system
yes | gem update
gem install rdoc
gem install rails pg
SCRIPT
config.vm.provision "shell", inline: $script, privileged: false
end
</code></pre>
<p>The key is to specify <code>privileged: false</code> so that it will use the default user and not <code>root</code>.</p> |
22,635,613 | What is the difference between ssh proxycommand -W, nc, exec nc | <p>I have seen a few blogs about .ssh/config and <code>proxycommand</code> </p>
<p>now what is the difference between the next commands</p>
<p><code>ProxyCommand ssh proxyserver -W [%h]:%p</code></p>
<p><code>ProxyCommand ssh proxyserver nc -q0 %h %p 2> /dev/null</code></p>
<p><code>ProxyCommand ssh proxyserver exec nc -q0 %h %p 2> /dev/null</code></p>
<p>Some of these commands work on some machines, and don't work on others.</p> | 29,176,698 | 1 | 3 | null | 2014-03-25 13:07:49.197 UTC | 13 | 2015-04-06 21:22:56.593 UTC | null | null | null | null | 696,208 | null | 1 | 43 | ssh | 41,399 | <p>Here's how I understand it:</p>
<hr>
<ol>
<li><p><code>ProxyCommand ssh proxyserver -W [%h]:%p</code></p>
<ul>
<li><p>The <code>-W</code> option is built into new(er) versions of OpenSSH, so this will only work on machines that have the minimum version (5.4, unless your distro back-ported any features; e.g., RHEL6 OpenSSH 5.3p1 includes this feature). Per the release notes: <a href="http://www.openssh.com/txt/release-5.4" rel="noreferrer">http://www.openssh.com/txt/release-5.4</a></p>
<blockquote>
<p>Added a 'netcat mode' to ssh(1): "ssh -W host:port ..." This connects stdio on the client to a single port forward on the server. This allows, for example, using ssh as a ProxyCommand to route connections via intermediate servers.</p>
</blockquote></li>
</ul></li>
<li><p><code>ProxyCommand ssh proxyserver nc -q0 %h %p 2> /dev/null</code></p>
<ul>
<li>Before the <code>-W</code> option was available, we used the <code>nc</code> (or netcat) utility. <code>nc</code> allows you to forward TCP & UDP packets to specified (alternate) locations and essentially behaves the same as <code>ssh -W</code> (as <code>ssh -W</code> was modeled after <code>nc</code>). In order for this variation to work the intermediate host(s) require(s) that <code>nc</code> be installed and the option <code>AllowTcpForwarding</code> must be enabled in the host's sshd_config (default: yes). The option <code>-q0</code> to <code>nc</code> is (supposed to be) for quieting errors, but I can't find which version this was introduced. (Note: <code>2> /dev/null</code> is probably to quite <code>ssh</code> errors, but one can use <code>ssh -q</code> instead.)</li>
</ul></li>
<li><p><code>ProxyCommand ssh proxyserver exec nc -q0 %h %p 2> /dev/null</code></p>
<ul>
<li><p>This is very much the same as the second variation, except you're calling the shell's built-in function <code>exec</code>. I'm not sure, but I believe there is no difference between including or excluding <code>exec</code> from the <code>ProxyCommand</code>; this variation should function everywhere the variation above does. For example, the Bash manual says something like this:</p>
<blockquote>
<p>exec [-cl] [-a name] [command [arguments]]</p>
<p>If command is specified, it replaces the shell. No new process is created. The arguments
become the arguments to command. If the -l option is supplied, the shell places a dash at the
beginning of the zeroth argument passed to command. This is what login(1) does. The -c
option causes command to be executed with an empty environment. If -a is supplied, the shell
passes name as the zeroth argument to the executed command. If command cannot be executed for
some reason, a non-interactive shell exits, unless the shell option execfail is enabled, in
which case it returns failure. An interactive shell returns failure if the file cannot be
executed. If command is not specified, any redirections take effect in the current shell, and
the return status is 0. If there is a redirection error, the return status is 1.</p>
</blockquote></li>
</ul></li>
</ol> |
13,323,976 | How to extract a JSON object that was defined in a HTML page javascript block using Python? | <p>I am downloading HTML pages that have data defined in them in the following way:</p>
<pre><code>... <script type= "text/javascript"> window.blog.data = {"activity":{"type":"read"}}; </script> ...
</code></pre>
<p>I would like to extract the JSON object defined in 'window.blog.data'.
Is there a simpler way than parsing it manually? (I am looking into Beautiful Soap but can't seem to find a method that will return the exact object without parsing)</p>
<p>Thanks</p>
<p><strong>Edit:</strong>
Would it be possible and more correct to do this with a python headless browser (e.g., Ghost.py)?</p> | 13,325,474 | 4 | 4 | null | 2012-11-10 16:51:24.66 UTC | 10 | 2021-08-17 03:10:48.567 UTC | 2012-11-10 19:57:30.87 UTC | null | 971,956 | null | 971,956 | null | 1 | 19 | python|html-parsing|beautifulsoup|headless-browser | 35,133 | <p>BeautifulSoup is an html parser; you also need a javascript parser here. btw, some javascript object literals are not valid json (though in your example the literal is also a valid json object).</p>
<p>In simple cases you could:</p>
<ol>
<li>extract <code><script></code>'s text using an html parser</li>
<li>assume that <code>window.blog...</code> is a single line or there is no <code>';'</code> inside the object and extract the javascript object literal using simple string manipulations or a regex</li>
<li>assume that the string is a valid json and parse it using json module</li>
</ol>
<p>Example:</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
html = """<!doctype html>
<title>extract javascript object as json</title>
<script>
// ..
window.blog.data = {"activity":{"type":"read"}};
// ..
</script>
<p>some other html here
"""
import json
import re
from bs4 import BeautifulSoup # $ pip install beautifulsoup4
soup = BeautifulSoup(html)
script = soup.find('script', text=re.compile('window\.blog\.data'))
json_text = re.search(r'^\s*window\.blog\.data\s*=\s*({.*?})\s*;\s*$',
script.string, flags=re.DOTALL | re.MULTILINE).group(1)
data = json.loads(json_text)
assert data['activity']['type'] == 'read'
</code></pre>
<p>If the assumptions are incorrect then the code fails.</p>
<p>To relax the second assumption, a javascript parser could be used instead of a regex e.g., <a href="http://slimit.readthedocs.org/" rel="noreferrer"><code>slimit</code></a> (<a href="https://ru.stackoverflow.com/questions/501556/%d0%9a%d0%b0%d0%ba-%d0%bf%d0%be%d0%bb%d1%83%d1%87%d0%b8%d1%82%d1%8c-%d0%b8%d0%bd%d1%84%d0%be%d1%80%d0%bc%d0%b0%d1%86%d0%b8%d1%8e-%d0%b8%d0%b7-%d1%81%d1%82%d1%80%d0%be%d0%ba%d0%b8-json-%d0%ba%d0%be%d1%82%d0%be%d1%80%d0%b0%d1%8f-%d1%83%d0%ba%d0%b0%d0%b7%d0%b0%d0%bd%d0%b0-%d0%b2-javascript-%d0%ba%d0%be%d0%b4%d0%b5-%d0%b2%d0%bd%d1%83%d1%82%d1%80%d0%b8/501630#comment598944_501562">suggested by @approximatenumber</a>):</p>
<pre class="lang-py prettyprint-override"><code>from slimit import ast # $ pip install slimit
from slimit.parser import Parser as JavascriptParser
from slimit.visitors import nodevisitor
soup = BeautifulSoup(html, 'html.parser')
tree = JavascriptParser().parse(soup.script.string)
obj = next(node.right for node in nodevisitor.visit(tree)
if (isinstance(node, ast.Assign) and
node.left.to_ecma() == 'window.blog.data'))
# HACK: easy way to parse the javascript object literal
data = json.loads(obj.to_ecma()) # NOTE: json format may be slightly different
assert data['activity']['type'] == 'read'
</code></pre>
<p>There is no need to treat the object literal (<code>obj</code>) as a json object. To get the necessary info, <code>obj</code> can be visited recursively like other ast nodes. It would allow to support arbitrary javascript code (that can be parsed by <a href="http://slimit.readthedocs.org/" rel="noreferrer"><code>slimit</code></a>).</p> |
13,631,537 | Create CSS to enlarge checkboxes | <p>I am trying to double the size of my checkboxes on a few pages. How do I make that happen in CSS? I don't want to style the hover.</p>
<p>Ideas?</p> | 13,631,813 | 9 | 1 | null | 2012-11-29 17:40:29.047 UTC | 4 | 2018-01-16 12:31:06.08 UTC | null | null | null | null | 1,842,729 | null | 1 | 30 | css|resize|label|checkbox | 88,399 | <p>You could always use the checkbox hack to make your own checkbox. This allows for a much more cross browser compatible solution.</p>
<p>I made a quick demo <a href="http://jsfiddle.net/EZHwR/1/" rel="noreferrer">here</a>, obviously you would have to get a transparent .png of a tick, not the one I got.</p>
<pre><code>input[type=checkbox]:checked ~ div label{
background: url(http://ramyasspace.files.wordpress.com/2011/06/tick.jpg);
background-size: 100%;
}
</code></pre>
<hr>
<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>input {
display: none;
}
label input[type=checkbox] ~ span {
display: inline-block;
vertical-align: middle;
cursor: pointer;
background: #fff;
border: 1px solid #888;
padding: 1px;
height: 20px;
width: 20px;
}
label input[type=checkbox]:checked ~ span {
/* image: Picol.org, cc-by 3.0, https://commons.wikimedia.org/wiki/File:Accept_Picol_icon.svg */
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><path d="M14 18L26 6l4 4-16 16L4 16l4-4z"/></svg>');
background-size: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
Click me:
<input type="checkbox" />
<span></span>
</label></code></pre>
</div>
</div>
</p> |
39,707,115 | Data families vs Injective type families | <p>Now that we have injective type families, is there any remaining use case for using data families over type families?</p>
<p>Looking at past StackOverflow questions about data families, there is <a href="https://stackoverflow.com/questions/20870432/type-family-vs-data-family-in-brief-haskell">this question</a> from a couple years ago discussing the difference between type families and data families, and <a href="https://stackoverflow.com/a/14196921/3072788">this answer</a> about use cases of data families. Both say that the injectivity of data families is their greatest strength.</p>
<p>Looking at the <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#data-families" rel="noreferrer">docs on data families</a>, I see reason not to rewrite all uses of data families using <a href="https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#injective-type-families" rel="noreferrer">injective type families</a>.</p>
<p>For example, say I have a data family (I've merged some examples from the docs to try to squeeze in all the features of data families)</p>
<pre><code>data family G a b
data instance G Int Bool = G11 Int | G12 Bool deriving (Eq)
newtype instance G () a = G21 a
data instance G [a] b where
G31 :: c -> G [Int] b
G32 :: G [a] Bool
</code></pre>
<p>I might as well rewrite it as</p>
<pre><code>type family G a b = g | g -> a b
type instance G Int Bool = G_Int_Bool
type instance G () a = G_Unit_a a
type instance G [a] b = G_lal_b a b
data G_Int_Bool = G11 Int | G12 Bool deriving (Eq)
newtype G_Unit_a a = G21 a
data G_lal_b a b where
G31 :: c -> G_lal_b [Int] b
G32 :: G_lal_b [a] Bool
</code></pre>
<p>It goes without saying that associated instances for data families correspond to associated instances with type families in the same way. Then is the only remaining difference that we have less things in the type-namespace?</p>
<p>As a followup, is there any benefit to having less things in the type-namespace? All I can think of is that this will become debugging hell for someone playing with this on <code>ghci</code> - the types of the constructors all seem to indicate that the constructors are all under one GADT...</p> | 39,715,512 | 3 | 4 | null | 2016-09-26 15:46:44.78 UTC | 10 | 2016-09-27 04:38:22.887 UTC | 2017-05-23 12:24:19.243 UTC | null | -1 | null | 3,072,788 | null | 1 | 21 | haskell|ghc|type-families | 2,232 | <pre><code>type family T a = r | r -> a
data family D a
</code></pre>
<p>An injective type family <code>T</code> satisfies the injectivity axiom</p>
<blockquote>
<p>if <code>T a ~ T b</code> then <code>a ~ b</code></p>
</blockquote>
<p>But a data family satisfies the much stronger generativity axiom</p>
<blockquote>
<p>if <code>D a ~ g b</code> then <code>D ~ g</code> and <code>a ~ b</code></p>
</blockquote>
<p>(If you like: Because the instances of <code>D</code> define new types that are different from any existing types.)</p>
<p>In fact <code>D</code> itself is a legitimate type in the type system, unlike a type family like <code>T</code>, which can only ever appear in a fully saturated application like <code>T a</code>. This means</p>
<ul>
<li><p><code>D</code> can be the argument to another type constructor, like <code>MaybeT D</code>. (<code>MaybeT T</code> is illegal.)</p></li>
<li><p>You can define instances for <code>D</code>, like <code>instance Functor D</code>. (You can't define instances for a type family <code>Functor T</code>, and it would be unusable anyway because instance selection for, e.g., <code>map :: Functor f => (a -> b) -> f a -> f b</code> relies on the fact that from the type <code>f a</code> you can determine both <code>f</code> and <code>a</code>; for this to work <code>f</code> cannot be allowed to vary over type families, even injective ones.)</p></li>
</ul> |
24,357,687 | How to include *.so library in Android Studio? | <p>I read many threads how to add a *.so library to Android Studio, but none of them works, especially when it comes to the point of text: This does not work with the newer xxx (Android Studio, gradle, ...)</p>
<p>Can we make a fresh start please. I got:</p>
<p>Android Studio 0.6.0</p>
<p>From Project Structure I see:</p>
<p>SDK Location:</p>
<pre><code>/usr/share/android-studio/data/sdk
/usr/lib/jvm/default-java
</code></pre>
<p>Project:</p>
<pre><code>Gradle version 1.10
Android Plugin Version 0.11.+
</code></pre>
<p>Modules/app:
Properties:</p>
<p>Compile Sdk Version 19
Build Tools Version 19.1.0</p>
<p>Dependencies:</p>
<pre><code>{dir=libs, include=[*.jar]} Compile
{dir=libs, include=[*.so]} Provided
m com.android.support: appcompat -v7:19.+ Compile
</code></pre>
<p>I got the *.so files pre-compiled and at the demo app they are working. I have to change the source code of the app, so I need to rebuild with the same *.so files.</p> | 24,360,361 | 9 | 2 | null | 2014-06-23 02:27:06.07 UTC | 54 | 2021-03-22 21:59:19.14 UTC | 2015-07-22 04:48:04.307 UTC | null | 1,213,296 | null | 1,516,854 | null | 1 | 151 | android|android-studio | 242,562 | <p><strong>Current Solution</strong></p>
<p>Create the folder <code>project/app/src/main/jniLibs</code>, and then put your <code>*.so</code> files within their abi folders in that location. E.g.,</p>
<pre><code>project/
├──libs/
| └── *.jar <-- if your library has jar files, they go here
├──src/
└── main/
├── AndroidManifest.xml
├── java/
└── jniLibs/
├── arm64-v8a/ <-- ARM 64bit
│ └── yourlib.so
├── armeabi-v7a/ <-- ARM 32bit
│ └── yourlib.so
└── x86/ <-- Intel 32bit
└── yourlib.so
</code></pre>
<p><strong>Deprecated solution</strong></p>
<p>Add both code snippets in your module gradle.build file as a dependency:</p>
<pre><code>compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
</code></pre>
<p>How to create this custom jar:</p>
<pre><code>task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
</code></pre>
<p>Same answer can also be found in related question: <a href="https://stackoverflow.com/questions/16683775/include-so-library-in-apk-in-android-studio?rq=1">Include .so library in apk in android studio</a></p> |
24,369,249 | Python with selenium: unable to locate element which really exist | <p>I've been trying fill input: </p>
<pre><code><input id="PASSFIELD1" class="logField" type="password" onkeyup="next(this, event);" maxlength="1" autocomplete="off" name="PASSFIELD1"></input>
</code></pre>
<p>To do this, I have to find this element. </p>
<p>I tried below things: </p>
<ol>
<li><p><code>pass1=driver.find_element_by_name("PASSFIELD1")</code> </p></li>
<li><p><code>pass1=driver.find_element_by_id("PASSFIELD1")</code> </p></li>
<li><p><code>pass1= driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/div/form/div[3]/table/tbody/tr[3]/td[2]/div/input[1]")</code> (path from firebug) </p></li>
<li><p>Even wait 100 seconds for it </p></li>
</ol>
<p><code>self.wait.until(EC.visibility_of_element_located((By.XPATH,"/html/body/div[4]/div/div/div[2]/div/form/div[3]/table/tbody/tr[3]/td[2]/div/input[1]")))
self.assertTrue(self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/div/form/div[3]/table/tbody/tr[3]/td[2]/div/input[1]"))</code> </p>
<p>I always get: </p>
<blockquote>
<p>selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: (...)</p>
</blockquote>
<p>Do you know what I am doing wrong?</p> | 24,371,665 | 2 | 4 | null | 2014-06-23 15:04:36.15 UTC | 15 | 2021-08-09 04:53:36.723 UTC | 2015-06-16 22:09:31.983 UTC | null | 771,848 | null | 3,767,975 | null | 1 | 33 | python|selenium|selenium-webdriver | 40,995 | <p>The problem is that your <code>input</code> tag is inside an <code>iframe</code>, you need to <a href="http://selenium-python.readthedocs.org/en/latest/navigating.html#moving-between-windows-and-frames">switch to</a> it first:</p>
<pre><code>frame = driver.find_element_by_xpath('//frame[@name="main"]')
driver.switch_to.frame(frame)
pass1 = driver.find_element_by_id("PASSFIELD1")
</code></pre> |
3,765,038 | Is there an equivalent to 'continue' in a Parallel.ForEach? | <p>I am porting some code to <code>Parallel.ForEach</code> and got an error with a <code>continue</code> I have in the code. Is there something equivalent I can use in a <code>Parallel.ForEach</code> functionally equivalent to <code>continue</code> in a <code>foreach</code> loop?</p>
<pre><code>Parallel.ForEach(items, parallelOptions, item =>
{
if (!isTrue)
continue;
});
</code></pre> | 3,765,078 | 2 | 0 | null | 2010-09-21 22:42:31.493 UTC | 19 | 2020-03-03 15:57:45.46 UTC | 2014-03-20 18:10:24.24 UTC | null | 375,375 | null | 394,178 | null | 1 | 299 | c#|foreach|parallel-processing | 74,800 | <pre><code>return;
</code></pre>
<p>(the body is just a function called for each item)</p> |
28,712,548 | Does the C standard guarantee buffers are not touched past their null terminator? | <p>In the various cases that a buffer is provided to the standard library's many string functions, is it guaranteed that the buffer will not be modified beyond the null terminator? For example:</p>
<pre><code>char buffer[17] = "abcdefghijklmnop";
sscanf("123", "%16s", buffer);
</code></pre>
<p>Is <code>buffer</code> now required to equal <code>"123\0efghijklmnop"</code>?</p>
<p>Another example:</p>
<pre><code>char buffer[10];
fgets(buffer, 10, fp);
</code></pre>
<p>If the read line is only 3 characters long, can one be certain that the 6th character is the same as before fgets was called?</p> | 28,716,991 | 7 | 15 | null | 2015-02-25 06:24:23.07 UTC | 2 | 2015-03-04 06:12:07.143 UTC | null | null | null | null | 2,209,194 | null | 1 | 43 | c|standards|c-standard-library | 3,537 | <p>Each individual byte in the buffer is an object. Unless some part of the function description of <code>sscanf</code> or <code>fgets</code> mentions modifying those bytes, or even implies their values may change e.g. by stating their values become unspecified, then the general rule applies: (emphasis mine)</p>
<blockquote>
<p><strong>6.2.4 Storage durations of objects</strong></p>
<p>2 [...] An object exists, has a constant address, <em><strong>and retains its last-stored value throughout its lifetime</strong></em>. [...]</p>
</blockquote>
<p>It's this same principle that guarantees that</p>
<pre><code>#include <stdio.h>
int a = 1;
int main() {
printf ("%d\n", a);
printf ("%d\n", a);
}
</code></pre>
<p>attempts to print 1 twice. Even though <code>a</code> is global, <code>printf</code> can access global variables, and the description of <code>printf</code> doesn't mention <em>not</em> modifying <code>a</code>.</p>
<p>Neither the description of <code>fgets</code> nor that of <code>sscanf</code> mentions modifying buffers past the bytes that actually were supposed to be written (except in the case of a read error), so those bytes don't get modified.</p> |
29,555,290 | What is the difference between res.end() and res.send()? | <p>I'm a beginner in <code>Express.js</code> and I'm confused by these two keywords: <code>res.end()</code> and <code>res.send()</code>.</p>
<p>Are they the same or different?</p> | 29,555,444 | 7 | 2 | null | 2015-04-10 07:01:28.23 UTC | 57 | 2022-07-14 10:43:59.03 UTC | 2018-07-24 14:56:25.177 UTC | null | 375,941 | null | 4,742,183 | null | 1 | 245 | node.js|express | 173,511 | <p><code>res.send()</code> will send the HTTP response. Its syntax is,</p>
<pre><code>res.send([body])
</code></pre>
<p>The body parameter can be a Buffer object, a String, an object, or an Array. For example:</p>
<pre><code>res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
</code></pre>
<p>See <a href="http://expressjs.com/en/4x/api.html#res.send" rel="noreferrer">this</a> for more info.</p>
<p><code>res.end()</code> will end the response process. This method actually comes from Node core, specifically the <code>response.end()</code> method of <code>http.ServerResponse</code>. It is used to quickly end the response without any data. For example:</p>
<pre><code>res.end();
res.status(404).end();
</code></pre>
<p>Read <a href="http://expressjs.com/en/4x/api.html#res.end" rel="noreferrer">this</a> for more info.</p> |
29,727,618 | Find Duplicate Elements In Array Using Swift | <p>How to find Duplicate Elements in Array? I have array of phone numbers so in the phone numbers i should start searching from the right side to the left side and find similar 6 integers. then i should print them out.</p> | 29,730,259 | 17 | 4 | null | 2015-04-19 08:32:03.85 UTC | 17 | 2022-08-31 15:41:12.82 UTC | 2015-04-19 10:20:21.803 UTC | null | 4,289,240 | null | 4,289,240 | null | 1 | 50 | arrays|swift|ios8|addressbook | 61,102 | <p>To find duplicates, you could build cross reference by phone number, then filter that down to duplicates only. For example, consider:</p>
<pre><code>let contacts = [
Contact(name: "Rob", phone: "555-1111"),
Contact(name: "Richard", phone: "555-2222"),
Contact(name: "Rachel", phone: "555-1111"),
Contact(name: "Loren", phone: "555-2222"),
Contact(name: "Mary", phone: "555-3333"),
Contact(name: "Susie", phone: "555-2222")
]
</code></pre>
<p>You can build the cross reference dictionary with:</p>
<pre><code>let crossReference = Dictionary(grouping: contacts, by: \.phone)
</code></pre>
<p>Then, to find the duplicates:</p>
<pre><code>let duplicates = crossReference
.filter { $1.count > 1 }
</code></pre>
<p>Clearly use whatever model types make sense for you, but the above uses the following <code>Contact</code> type:</p>
<pre><code>struct Contact {
let name: String
let phone: String
}
</code></pre>
<p>There are many, many ways to implement this, so I would not focus on the implementation details above, but rather focus on the concept: Build cross reference original array by some key (e.g. phone number) and then filter results down to just those keys with duplicate values.</p>
<hr />
<p>It sounds like you want to flatten this structure that reflects the duplicates, into a single array of contacts (I'm not sure why you'd want to do that, as you lose the structure identifying which are duplicates of each other), but if you want to do that, you can <code>flatMap</code> it:</p>
<pre><code>let flattenedDuplicates = crossReference
.filter { $1.count > 1 } // filter down to only those with multiple contacts
.flatMap { $0.1 } // flatten it down to just array of contacts that are duplicates of something else
</code></pre> |
16,145,187 | How to open a page in a new window or tab from code-behind | <p>So I have a webapplication where I select a value from a dropdownlist. When this value is selected, I want to load another page in a new window.</p>
<p>I tried this:</p>
<pre><code>ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('Default.aspx', '_blank');", true);
</code></pre>
<p>It does open the page, but not in a new window/tab. It opens it in the current opened page.</p>
<p>Alternatively I tried:</p>
<pre><code>ClientScript.RegisterStartupScript(this.GetType(), "OpenWin", "<script>openDashboardPage()</script>");
</code></pre>
<p>and</p>
<pre><code>HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>window.open('Default.aspx', '_new');</SCRIPT>");
</code></pre>
<p>They all behave in the same fashion. I just loads the page in the existing window. I tried it in both Firefox and Chrome, thinking it might be a browser thing, but they both behaved the same.</p>
<p>How do I open a new window?</p> | 16,398,156 | 5 | 3 | null | 2013-04-22 10:45:29.54 UTC | 2 | 2016-06-27 20:18:10.253 UTC | null | null | null | null | 2,114,784 | null | 1 | 13 | c#|asp.net | 105,263 | <p>Try this one</p>
<pre><code>string redirect = "<script>window.open('http://www.google.com');</script>";
Response.Write(redirect);
</code></pre> |
16,295,949 | Get all fields (even private and inherited) from class | <p>I am making university project.<br>
I need to get all fields from class. Even private and inherited. I tried to get all declared fields and then cast to super class and repeat.
Fragment of my code:</p>
<pre><code>private void listAllFields(Object obj) {
List<Field> fieldList = new ArrayList<Field>();
while (obj != null) {
fieldList.addAll(Arrays.asList(obj.getClass().getDeclaredFields()));
obj = obj.getClass().getSuperclass().cast(obj);
}
// rest of code
</code></pre>
<p>But it does not work. <code>tmpObj</code> after casting is still the same class (not superclass).<br>
I will appreciate any help how to fix casting problem, or how to retrieve these fields in different way. </p>
<p>Problem is not to gain access to fields, but to get names of fields!<br>
I manages it that way:</p>
<pre><code>private void listAllFields(Object obj) {
List<Field> fieldList = new ArrayList<Field>();
Class tmpClass = obj.getClass();
while (tmpClass != null) {
fieldList.addAll(Arrays.asList(tmpClass .getDeclaredFields()));
tmpClass = tmpClass .getSuperclass();
}
// rest of code
</code></pre> | 16,296,241 | 9 | 3 | null | 2013-04-30 08:58:30.703 UTC | 16 | 2021-07-30 07:49:10.55 UTC | 2019-02-16 04:15:27.67 UTC | null | 4,298,200 | null | 1,788,195 | null | 1 | 76 | java|reflection | 109,312 | <pre><code>obj = obj.getClass().getSuperclass().cast(obj);
</code></pre>
<p>This line does not do what you expect it to do. Casting an <code>Object</code> does not actually change it, it just tells the compiler to treat it as something else.</p>
<p>E.g. you can cast a <code>List</code> to a <code>Collection</code>, but it will still remain a <code>List</code>.</p>
<p>However, looping up through the super classes to access fields works fine without casting:</p>
<pre><code>Class<?> current = yourClass;
while(current.getSuperclass()!=null){ // we don't want to process Object.class
// do something with current's fields
current = current.getSuperclass();
}
</code></pre>
<p>BTW, if you have access to the Spring Framework, there is a handy method for looping through the fields of a class and all super classes:<br>
<a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/ReflectionUtils.html#doWithFields%28java.lang.Class,%20org.springframework.util.ReflectionUtils.FieldCallback%29" rel="noreferrer"><code>ReflectionUtils.doWithFields(baseClass, FieldCallback)</code></a><br>
(also see this previous answer of mine: <a href="https://stackoverflow.com/a/3567968/342852">Access to private inherited fields via reflection in Java</a>)</p> |
22,120,711 | Qt Creator, ptrace: Operation not permitted. What is the permanent solution? | <p>While debugging <code>C++</code> code in Qt creator I get the following error</p>
<pre><code>ptrace: Operation not permitted.
Could not attach to the process. Make sure no other debugger traces this process.
Check the settings of
/proc/sys/kernel/yama/ptrace_scope
For more details, see /etc/sysctl.d/10-ptrace.conf
</code></pre>
<p>Here a temporary solution is found: <a href="https://askubuntu.com/questions/244336/receiving-error-while-trying-to-debug-in-qtproject">Receiving error while trying to debug in QtProject</a></p>
<ul>
<li><p>temporary solution (won't survive a reboot):</p>
<p><code>echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope</code></p></li>
</ul>
<p>But it is difficult to run the same code in terminal every time when I start my PC to use Qt. </p>
<pre><code>What is the permanent solution for this?
</code></pre> | 27,065,399 | 3 | 3 | null | 2014-03-01 21:39:07.967 UTC | 22 | 2015-05-27 15:16:26.65 UTC | 2017-04-13 12:22:45.223 UTC | null | -1 | null | 2,337,276 | null | 1 | 57 | c++|qt|linux-kernel|qt5|linux-mint | 30,292 | <p>If running Ubuntu,</p>
<p>The recommended way to enable the needed ptrace kernel setting (hinted by qtcreator) is to edit /etc/sysctl.d/10-ptrace.conf</p>
<pre><code>sudo vim /etc/sysctl.d/10-ptrace.conf
</code></pre>
<p>Then change</p>
<pre><code>kernel.yama.ptrace_scope = 1
</code></pre>
<p>to</p>
<pre><code>kernel.yama.ptrace_scope = 0
</code></pre>
<p>Save,</p>
<p>then apply:</p>
<pre><code>$ sudo sysctl --system -a -p|grep yama
kernel.yama.ptrace_scope = 0
</code></pre>
<p>run</p>
<pre><code>man sysctl
</code></pre>
<p>for more info.</p> |
37,555,195 | Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV? | <p><a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="noreferrer">This link</a> has a tidy little example of how to use python's OpenCV library, <code>cv2</code> to stream data from a camera into your python shell. I'm looking to do some experiments and would like to use the following YouTube video feed: <code>https://www.youtube.com/watch?v=oCUqsPLvYBQ</code>. </p>
<p>I've tried adapting the example as follows: </p>
<pre><code>import numpy as np
import cv2
cap = cv2.VideoCapture('https://www.youtube.com/watch?v=oCUqsPLvYBQ')
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
</code></pre>
<p>Which produces the error: </p>
<pre><code>WARNING: Couldn't read movie file https://www.youtube.com/watch?v=oCUqsPLvYBQ
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /tmp/opencv20160107-29960-t5glvv/opencv-2.4.12/modules/highgui/src/window.cpp, line 261
</code></pre>
<p>Is there a simple fix that would allow me to stream this video feed into my python shell via <code>cv2</code>? Not absolutely committed to <code>cv2</code>, either, if there are other libraries out there that will accomplish the same purpose. </p> | 51,016,612 | 5 | 3 | null | 2016-05-31 20:37:18.247 UTC | 9 | 2021-04-14 05:18:00.773 UTC | null | null | null | null | 375,267 | null | 1 | 19 | python|opencv|video|youtube | 25,484 | <p>you need to have 2 things installed </p>
<ol>
<li>pafy (pip install pafy)</li>
<li>youtube_dl (sudo pip install --upgrade youtube_dl) </li>
</ol>
<p>after installing these two packages you can use the youtube url to play the streaming videos from youtube.
Please refer the code below</p>
<pre class="lang-py prettyprint-override"><code>url = 'https://youtu.be/W1yKqFZ34y4'
vPafy = pafy.new(url)
play = vPafy.getbest(preftype="webm")
#start the video
cap = cv2.VideoCapture(play.url)
while (True):
ret,frame = cap.read()
"""
your code here
"""
cv2.imshow('frame',frame)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
</code></pre> |
26,752,909 | Replace a object in a list of objects | <p>In C#, if I have a <code>List<T></code>, and I have an object of type <code>T</code>, how can I replace a specific item in the <code>List<T></code> with the object of type <code>T</code>?</p>
<p>Here is what I have tried:</p>
<pre><code>List<CustomListItem> customListItems = new List<CustomListItem>();
CustomListItem customListItem1 = new CustomListItem() { name = "Item 1", date = DateTime.MinValue};
CustomListItem customListItem2 = new CustomListItem() { name = "Item 2", date = DateTime.MinValue };
CustomListItem customListItem3 = new CustomListItem() { name = "Item 3", date = DateTime.MinValue };
customListItems.Add(customListItem1);
customListItems.Add(customListItem2);
customListItems.Add(customListItem3);
CustomListItem newCustomListItem = new CustomListItem() { name = "Item 4", date = DateTime.Now };
customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
customListItem2 = newCustomListItem;
</code></pre>
<p>In the above code, I want to replace the <code>customListItem2</code> with the <code>newCustomListItem</code>.</p>
<p>Do I have to remove the item in the list, and then insert the new item? Can I not do a simple assignment of <code>customListItem2 = newCustomListItem</code>?</p>
<p>What is the most efficient way of replacing an item in a list with another item?</p>
<p>Thanks in advance</p> | 26,752,977 | 5 | 2 | null | 2014-11-05 08:49:23.813 UTC | null | 2021-11-08 10:04:18.877 UTC | 2015-11-22 15:47:10.753 UTC | null | 3,970,411 | null | 3,736,648 | null | 1 | 52 | c#|.net|list|variable-assignment|generic-list | 85,579 | <p>You have to replace the item, not the value of <code>customListItem2</code>. Just replace following:</p>
<pre><code>customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
customListItem2 = newCustomListItem;
</code></pre>
<p>With this:</p>
<pre><code>customListItem2 = customListItems.Where(i=> i.name == "Item 2").First();
var index = customListItems.IndexOf(customListItem2);
if(index != -1)
customListItems[index] = newCustomListItem;
</code></pre>
<p><strong>Edit:</strong></p>
<p>As <a href="https://stackoverflow.com/questions/26752909/replace-a-object-in-a-list-of-objects/26752977?noredirect=1#comment63906297_26752977">Roman R.</a> stated in a comment, you can replace the <code>.Where(predicate).First()</code> by a simple <code>First(predicate)</code>:</p>
<pre><code>customListItem2 = customListItems.First(i=> i.name == "Item 2");
</code></pre> |
26,486,730 | In android app Toolbar.setTitle method has no effect – application name is shown as title | <p>I'm trying to create simple application using android-support-v7:21 library.<br><br>
Code snippets:
<br>
MainActivity.java</p>
<pre><code>public class MainActivity extends ActionBarActivity {
Toolbar mActionBarToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("My title");
setSupportActionBar(mActionBarToolbar);
}
</code></pre>
<p>activity_main.xml</p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_actionbar"
android:background="@null"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:fitsSystemWindows="true" />
</LinearLayout>
</code></pre>
<p>But instead of "My title" on Toolbar %application name% is shown.<br>
Seems like <code>setTitle</code> method has no effect.<br>
I would like to show "My title".<br></p>
<p><strong>UPD:</strong>
Before, <code>styles.xml</code> was:</p>
<pre><code><style name="AppTheme" parent="Theme.AppCompat">
<item name="windowActionBar">false</item>
</style>
</code></pre>
<p>So, I thought that actionbar is not used.
I add <code>NoActionBar</code> to style parent:</p>
<pre><code><style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<item name="windowActionBar">false</item>
</style>
</code></pre>
<p>But the problem is not resolved.</p> | 26,506,858 | 27 | 3 | null | 2014-10-21 12:27:53.063 UTC | 48 | 2021-05-14 03:58:19.69 UTC | 2019-01-13 21:57:34.563 UTC | null | 8,621,930 | null | 1,533,933 | null | 1 | 331 | android|toolbar|android-support-library | 256,255 | <p>Found the solution:<br></p>
<p>Instead of:</p>
<pre><code>mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("My title");
setSupportActionBar(mActionBarToolbar);
</code></pre>
<p>I used:</p>
<pre><code>mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My title");
</code></pre>
<p>And it works.</p> |
19,424,709 | R: gsub, pattern = vector and replacement = vector | <p>As the title states, I am trying to use gsub where I use a vector for the "pattern" and "replacement". Currently, I have a code that looks like this:</p>
<pre><code> names(x1) <- gsub("2110027599", "Inv1", names(x1)) #x1 is a data frame
names(x1) <- gsub("2110025622", "Inv2", names(x1))
names(x1) <- gsub("2110028045", "Inv3", names(x1))
names(x1) <- gsub("2110034716", "Inv4", names(x1))
names(x1) <- gsub("2110069349", "Inv5", names(x1))
names(x1) <- gsub("2110023264", "Inv6", names(x1))
</code></pre>
<p>What I hope to do is something like this:</p>
<pre><code> a <- c("2110027599","2110025622","2110028045","2110034716", "2110069349", "2110023264")
b <- c("Inv1","Inv2","Inv3","Inv4","Inv5","Inv6")
names(x1) <- gsub(a,b,names(x1))
</code></pre>
<p>I'm guessing there is an apply function somewhere that can do this, but I am not very sure which one to use!</p>
<p>EDIT: names(x1) looks like this (There are many more columns, but I'm leaving them out):</p>
<pre><code>> names(x1)
[1] "2110023264A.Ms.Amp" "2110023264A.Ms.Vol" "2110023264A.Ms.Watt" "2110023264A1.Ms.Amp"
[5] "2110023264A2.Ms.Amp" "2110023264A3.Ms.Amp" "2110023264A4.Ms.Amp" "2110023264A5.Ms.Amp"
[9] "2110023264B.Ms.Amp" "2110023264B.Ms.Vol" "2110023264B.Ms.Watt" "2110023264B1.Ms.Amp"
[13] "2110023264Error" "2110023264E-Total" "2110023264GridMs.Hz" "2110023264GridMs.PhV.phsA"
[17] "2110023264GridMs.PhV.phsB" "2110023264GridMs.PhV.phsC" "2110023264GridMs.TotPFPrc" "2110023264Inv.TmpLimStt"
[21] "2110023264InvCtl.Stt" "2110023264Mode" "2110023264Mt.TotOpTmh" "2110023264Mt.TotTmh"
[25] "2110023264Op.EvtCntUsr" "2110023264Op.EvtNo" "2110023264Op.GriSwStt" "2110023264Op.TmsRmg"
[29] "2110023264Pac" "2110023264PlntCtl.Stt" "2110023264Serial Number" "2110025622A.Ms.Amp"
[33] "2110025622A.Ms.Vol" "2110025622A.Ms.Watt" "2110025622A1.Ms.Amp" "2110025622A2.Ms.Amp"
[37] "2110025622A3.Ms.Amp" "2110025622A4.Ms.Amp" "2110025622A5.Ms.Amp" "2110025622B.Ms.Amp"
[41] "2110025622B.Ms.Vol" "2110025622B.Ms.Watt" "2110025622B1.Ms.Amp" "2110025622Error"
[45] "2110025622E-Total" "2110025622GridMs.Hz" "2110025622GridMs.PhV.phsA" "2110025622GridMs.PhV.phsB"
</code></pre>
<p>What I hope to get is this:</p>
<pre><code>> names(x1)
[1] "Inv6A.Ms.Amp" "Inv6A.Ms.Vol" "Inv6A.Ms.Watt" "Inv6A1.Ms.Amp" "Inv6A2.Ms.Amp"
[6] "Inv6A3.Ms.Amp" "Inv6A4.Ms.Amp" "Inv6A5.Ms.Amp" "Inv6B.Ms.Amp" "Inv6B.Ms.Vol"
[11] "Inv6B.Ms.Watt" "Inv6B1.Ms.Amp" "Inv6Error" "Inv6E-Total" "Inv6GridMs.Hz"
[16] "Inv6GridMs.PhV.phsA" "Inv6GridMs.PhV.phsB" "Inv6GridMs.PhV.phsC" "Inv6GridMs.TotPFPrc" "Inv6Inv.TmpLimStt"
[21] "Inv6InvCtl.Stt" "Inv6Mode" "Inv6Mt.TotOpTmh" "Inv6Mt.TotTmh" "Inv6Op.EvtCntUsr"
[26] "Inv6Op.EvtNo" "Inv6Op.GriSwStt" "Inv6Op.TmsRmg" "Inv6Pac" "Inv6PlntCtl.Stt"
[31] "Inv6Serial Number" "Inv2A.Ms.Amp" "Inv2A.Ms.Vol" "Inv2A.Ms.Watt" "Inv2A1.Ms.Amp"
[36] "Inv2A2.Ms.Amp" "Inv2A3.Ms.Amp" "Inv2A4.Ms.Amp" "Inv2A5.Ms.Amp" "Inv2B.Ms.Amp"
[41] "Inv2B.Ms.Vol" "Inv2B.Ms.Watt" "Inv2B1.Ms.Amp" "Inv2Error" "Inv2E-Total"
[46] "Inv2GridMs.Hz" "Inv2GridMs.PhV.phsA" "Inv2GridMs.PhV.phsB"
</code></pre> | 19,426,663 | 6 | 3 | null | 2013-10-17 10:52:08.943 UTC | 19 | 2020-12-09 21:26:49.047 UTC | 2013-10-17 16:38:42.06 UTC | null | 2,809,288 | null | 2,809,288 | null | 1 | 47 | r | 31,182 | <p>Lot's of solutions already, here are one more:</p>
<p><strong>The qdap package:</strong></p>
<pre><code>library(qdap)
names(x1) <- mgsub(a,b,names(x1))
</code></pre> |
45,173,454 | How can iOS detect bluetooth signal strength similar to Airpods? | <p>It seems that AirPods and iPhone can communicate on a very sensitive level. Moving AirPods physically close to the device (1 foot away) will trigger the iPhone to react.</p>
<p>Can the iPhone really detect bluetooth signals with such accuracy? I'm using bluetooth right now, but I can't seem to reach this level of signal sensitivity.</p> | 45,431,617 | 1 | 4 | null | 2017-07-18 17:28:10.173 UTC | 14 | 2018-08-08 12:36:39.673 UTC | null | null | null | null | 179,736 | null | 1 | 17 | ios|swift|bluetooth | 8,793 | <p>They used to have some additional measures to find out the distance. As noticed by <a href="https://stackoverflow.com/users/341750/hotpaw2">hotpaw2</a> in comments</p>
<hr>
<h2>Quick Answer - Swift 4.2</h2>
<pre><code>func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if let power = advertisementData[CBAdvertisementDataTxPowerLevelKey] as? Double{
print("Distance is ", pow(10, ((power - Double(truncating: RSSI))/20)))
}
}
</code></pre>
<hr>
<p><strong>TL:DR;</strong></p>
<h2>Factors Affecting RSSI</h2>
<p>RSSI readings are not very stable and highly depend on environment</p>
<p>It may also vary due to a number of factors, including both the power and sensitivity of the sensing / transmitting radios, as well as the environmental stuff (are you inside, outside? are there many people nearby? noisy wireless environment or not, and so on). </p>
<p>The problem, however, is that beacon signals are actually radio waves, and can be absorbed by metals, walls, water etc. Since they transmit radio signals in the commonly used 2.4GHz band, the signal strength received from a beacon varies widely because of interference. </p>
<p><strong>One of the mostly used formula to find out distance is</strong></p>
<blockquote>
<p>d = 10 ^ ((TxPower - RSSI) / 20)</p>
</blockquote>
<p>TxPower is typically known as transmit power</p>
<hr>
<h2>How to get TxPower From BLE advertisement Data</h2>
<p>The txPower value will be available in BLE advertisement data (available only if the broadcaster (peripheral) provides its Tx power level).</p>
<p>As per apple documentation the value of <a href="https://developer.apple.com/documentation/corebluetooth/cbadvertisementdatatxpowerlevelkey" rel="noreferrer">CBAdvertisementDataTxPowerLevelKey</a> in CBAdvertisementDataTx</p>
<p>Delegate method to access the raw advertisement data</p>
<pre><code>optional func centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber)
</code></pre>
<p><strong>Can be also accessed by using <a href="https://github.com/jessepollak/BlueCapKit#peripheral-advertisements" rel="noreferrer">BlueCap API</a></strong></p>
<p>To know more advantages of AirPlay than Classical Bluetooth </p>
<p><a href="https://www.cambridgeaudio.com/blog/airplay" rel="noreferrer">https://www.cambridgeaudio.com/blog/airplay</a></p>
<hr>
<h2>RSSI and Distance</h2>
<p>According to the image below from <a href="https://shinesolutions.com/2014/02/17/the-beacon-experiments-low-energy-bluetooth-devices-in-action/" rel="noreferrer">Link</a></p>
<p><a href="https://i.stack.imgur.com/MNp7Z.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MNp7Z.png" alt="enter image description here"></a></p>
<p>RSSI will go down if you cover the beacon (e.g., a person comes in between you and the beacon). That is, you're still in the same distance, but RSSI goes down—so where you to base the distance estimate on the RSSI, the distance would go up, without you moving an inch.</p>
<p>Many of the above explanations are taken from other sites. </p>
<p>I Hope it sum up to your need!</p> |
17,520,750 | List view item swipe left and swipe right? | <p>Can a List view item respond to swipe left and swipe right?</p>
<p>If so, how to apply android swipe left or right scrolling to open different intent? I want same like Call phone or message on contact view in android by default.</p>
<p>Thanks</p> | 17,521,473 | 2 | 2 | null | 2013-07-08 07:00:10.73 UTC | 18 | 2016-11-28 12:40:14.163 UTC | 2014-01-29 06:20:41.65 UTC | null | 608,639 | null | 1,481,766 | null | 1 | 29 | android|listview | 53,800 | <p>Try this:</p>
<pre><code>navigaList.setOnTouchListener(swipeDetector);
navigaList.setOnItemClickListener(listener);
OnItemClickListener listener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
if(swipeDetector.swipeDetected()) {
if(swipeDetector.getAction() == Action.RL) {
} else {
}
}
};
</code></pre>
<p><strong>SwipeDetector.java</strong></p>
<pre><code>public class SwipeDetector implements View.OnTouchListener {
public static enum Action {
LR, // Left to Right
RL, // Right to Left
TB, // Top to bottom
BT, // Bottom to Top
None // when no action was detected
}
private static final String logTag = "SwipeDetector";
private static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
private Action mSwipeDetected = Action.None;
public boolean swipeDetected() {
return mSwipeDetected != Action.None;
}
public Action getAction() {
return mSwipeDetected;
}
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
mSwipeDetected = Action.None;
return false; // allow other events like Click to be processed
}
case MotionEvent.ACTION_MOVE: {
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// horizontal swipe detection
if (Math.abs(deltaX) > MIN_DISTANCE) {
// left or right
if (deltaX < 0) {
Logger.show(Log.INFO,logTag, "Swipe Left to Right");
mSwipeDetected = Action.LR;
return true;
}
if (deltaX > 0) {
Logger.show(Log.INFO,logTag, "Swipe Right to Left");
mSwipeDetected = Action.RL;
return true;
}
} else
// vertical swipe detection
if (Math.abs(deltaY) > MIN_DISTANCE) {
// top or down
if (deltaY < 0) {
Logger.show(Log.INFO,logTag, "Swipe Top to Bottom");
mSwipeDetected = Action.TB;
return false;
}
if (deltaY > 0) {
Logger.show(Log.INFO,logTag, "Swipe Bottom to Top");
mSwipeDetected = Action.BT;
return false;
}
}
return true;
}
}
return false;
}
}
</code></pre> |
17,280,534 | Prettyprint to a file? | <p>I'm using this <a href="https://gist.github.com/hrldcpr/2012250/">gist's</a> tree, and now I'm trying to figure out how to prettyprint to a file. Any tips?</p> | 17,280,610 | 4 | 4 | null | 2013-06-24 16:36:38.073 UTC | 9 | 2022-01-30 22:08:25.047 UTC | null | null | null | null | 2,494,094 | null | 1 | 41 | python|hash|dictionary|tree|pretty-print | 37,868 | <p>What you need is Pretty Print <a href="http://docs.python.org/2/library/pprint.html"><code>pprint</code></a> module:</p>
<pre><code>from pprint import pprint
# Build the tree somehow
with open('output.txt', 'wt') as out:
pprint(myTree, stream=out)
</code></pre> |
30,694,453 | Blob createObjectURL download not working in Firefox (but works when debugging) | <p>I have an odd problem, the function below is one I created based on what i found on the net about creating a Blob in the client on the fly with some binary data in (passed as an array) and being able to download that. This works brilliantly in Chrome, but doesn't do anything in Firefox - UNLESS I debug and step through the code. Yes, oddly, if I create a break point inside the function and step through it, the a.click() will bring up the download window!</p>
<pre><code>function downloadFile(filename, data) {
var a = document.createElement('a');
a.style = "display: none";
var blob = new Blob(data, {type: "application/octet-stream"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
</code></pre>
<p>Can anyone help me? This was tested using Firefox 38.0.5.</p> | 30,708,820 | 3 | 3 | null | 2015-06-07 14:07:08.09 UTC | 15 | 2018-06-07 13:37:21.743 UTC | null | null | null | null | 435,637 | null | 1 | 61 | javascript|firefox|download|blob | 65,875 | <p>You're probably removing the resource too soon, try delaying it</p>
<pre><code> ...
a.click();
setTimeout(function(){
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 100);
}
</code></pre> |
26,031,932 | can't link with a main executable file | <p>Changed my deployment target to from 8.0 to 7.0.</p>
<p>Using Xcode 6 with latest iOS8 as base sdk. Getting this error when building for iOS7.1 device:</p>
<p>ld: can't link with a main executable file '/Users/Name/Library/Developer/Xcode/DerivedData/Clumsy_Bird-gotvuaeuyvrkzvfqpzsuxpmifimu/Build/Products/Debug-iphoneos/Clumsy Bird.app/Clumsy Bird' for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)</p>
<p><img src="https://i.stack.imgur.com/HGqOw.png" alt="enter image description here"></p>
<p>How to solve this?</p> | 26,663,991 | 4 | 2 | null | 2014-09-25 06:21:40.893 UTC | 9 | 2018-09-07 12:01:51.32 UTC | null | null | null | null | 1,872,384 | null | 1 | 25 | xcode6 | 15,286 | <ol>
<li>Click your project in Navigator.</li>
<li>Select your <strong>test</strong> target. Switch to <strong>general</strong> tab if not there.</li>
<li>Select your application name from <strong>Host Application</strong> dropdown.</li>
</ol>
<p><img src="https://i.stack.imgur.com/X1JZm.png" alt="enter image description here"></p> |
12,082,442 | Python:How to make the sum of the values of a while loop store into a variable? | <p>I'm just a beginner :P.
I'm doing a tutorial about while loops on Codeacademy "Click <a href="http://www.codecademy.com/courses/a-dash-of-python/1#!/exercises/1" rel="nofollow">here</a>!" ,
but I've gotten stuck on this part: Write a while loop which stores into "<code>theSum</code>" the sum of the first 10 positive integers (including 10).This is what it gives you to work with:</p>
<pre><code>theSum = 0
num = 1
while num <= 10:
print num
num = num + 1
</code></pre>
<p>It prints out the numbers 1 to 10 on seperate lines in the console. Can anyone explain to me how I can get it to store the sum of the values in the variable "<code>mySum</code>"? Anything I've tried so far hasn't worked for me. :(</p>
<p>EDIT:
Okay so I just tried this:</p>
<pre><code>theSum = 0
num = 1
while num <= 10:
num += 1
mySum = num
mySum = mySum + num
print mySum
</code></pre>
<p>This gives me 22, why is that? Am I in anyway close? (Thanks for all the replies but I'll try again tomorrow.)</p>
<p>EDIT: Okay, I got it! Thank you for the help. :)</p>
<pre><code>mySum = 0
num = 1
while num <= 10:
mySum += num
num += 1
print mySum
</code></pre> | 12,082,463 | 4 | 2 | null | 2012-08-22 22:47:40.887 UTC | null | 2018-03-11 23:24:17.213 UTC | 2012-08-23 11:54:31.6 UTC | null | 1,615,207 | null | 1,615,207 | null | 1 | 3 | python|loops|while-loop | 72,693 | <p>The code you have already shows almost everything needed.</p>
<p>The remaining problem is that while you are correctly generating the values to be added (<code>num</code>) inside your <code>while</code>-loop, you are <em>not</em> accumulating these values in your variable <code>theSum</code>.</p>
<p><em>I won't give you the missing code on purpose</em>, so that you can learn something from your question ... but you need to add the value of <code>num</code> to your variable <code>theSum</code> <em>inside</em> the loop. The code for doing this (it's really only <em>one</em> statement, i.e., one line of code) will be somewhat similar to how you are dealing with/updating the value of <code>num</code> inside your loop.</p>
<p>Does that help?</p> |
31,722,181 | Can an immutable type change its internal state? | <p>The question is simple. Can a type that can change its internal state without it being observable from the outside be considered <em>immutable</em>?</p>
<p>Simplified example:</p>
<pre><code>public struct Matrix
{
bool determinantEvaluated;
double determinant;
public double Determinant
{
get //asume thread-safe correctness in implementation of the getter
{
if (!determinantEvaluated)
{
determinant = getDeterminant(this);
determinantEvaluated = true;
}
return determinant;
}
}
}
</code></pre>
<p><em>UPDATE</em>: Clarified the thread-safeness issue, as it was causing distraction.</p> | 31,722,902 | 5 | 11 | null | 2015-07-30 11:09:57.863 UTC | 2 | 2015-09-06 13:17:22.163 UTC | 2015-07-30 11:24:27.79 UTC | null | 767,890 | null | 767,890 | null | 1 | 45 | c#|immutability | 2,301 | <p>Yes, immutable <em>can change</em> its state, providing that the changes are
<em>unseen</em> for other components of the software (usually caches). Quite
like quantum physics: an event should have an observer to be an event.</p>
<p>In your case a possible implementation is something like that:</p>
<pre><code> public class Matrix {
...
private Lazy<Double> m_Determinant = new Lazy<Double>(() => {
return ... //TODO: Put actual implementation here
});
public Double Determinant {
get {
return m_Determinant.Value;
}
}
}
</code></pre>
<p>Note, that <code>Lazy<Double> m_Determinant</code> <em>has</em> a changing state </p>
<pre><code>m_Determinant.IsValueCreated
</code></pre>
<p>which is, however, <em>unobservable</em>.</p> |
5,042,467 | CSS: display:inline-block and positioning:absolute | <p>Please consider the following code:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style type="text/css">
.section {
display: block;
width: 200px;
border: 1px dashed blue;
margin-bottom: 10px;
}
.element-left,
.element-right-a,
.element-right-b {
display: inline-block;
background-color: #ccc;
vertical-align: top;
}
.element-right-a,
.element-right-b {
max-width: 100px;
}
.element-right-b {
position: absolute;
left: 100px;
}
</style>
<title>test</title>
</head>
<body>
<div class="section">
<span class="element-left">some text</span>
<span class="element-right-a">some text</span>
</div>
<div class="section">
<span class="element-left">some text</span>
<span class="element-right-a">some more text to force line wrapping</span>
</div>
<div class="section">
<span class="element-left">some text</span>
<span class="element-right-b">some text</span>
</div>
<div class="section">
<span class="element-left">some text</span>
<span class="element-right-b">some more text to force line wrapping</span>
</div>
<div class="section">
<span class="element-left">some text</span>
<span class="element-right-b">some more text to force line wrapping</span>
</div>
</body>
</html>
</code></pre>
<p>The element with absolute positioning apparantly makes the containing box "forget" which height he needs.</p>
<p>I need the absolute positioning inside the "section" box, is there another solution for this?</p>
<p>thanks in advance,
geronimo</p>
<p><strong>edit</strong></p>
<p>Using tables is not really an option, I need some sort of "multi-level"/"nested" layout, where the second col is always on the same position:</p>
<pre>
| some text in first column | some text in 2nd column
| some indented text | 2nd column
| also indented | 2nd col
| even more indent | 2nd column with a lot of text that
| makes it wrap
| text | ...
| blah blah | ...
</pre>
<p>(of course whithout the "|"s)</p> | 5,042,666 | 3 | 1 | null | 2011-02-18 14:28:17.387 UTC | 13 | 2014-05-29 15:58:52.853 UTC | 2011-02-18 15:29:46.493 UTC | null | 623,280 | null | 623,280 | null | 1 | 38 | css|css-position | 107,340 | <p>When you use <code>position:absolute;</code>, the element is taken out of the normal page flow. Therefore it no longer affects the layout of its container element. So the container element does not take into account its height, so if there's nothing else to set the height, then the container will be zero height.</p>
<p>Additionally, setting <code>display:inline-block;</code> does not make any sense for an element that is <code>position:absolute;</code>. Again, this is because absolute positioning takes the element out of the page flow. This is at odds with <code>inline-block</code>, which only exists to affect how the element fits into the page flow. All elements that are <code>position:absolute;</code> are automatically treated as <code>display:block</code>, since that's the only logical display mode for absolute positioning.</p>
<p>If you <em>need</em> absolute positioning, then the only solution to your height problem is to set the height of the container box.</p>
<p>However, I suspect that you could do without the absolute positioning.</p>
<p>It looks like what you're trying to do is position the second <code><span></code> in each block to a fixed position in the block, so that they line up.</p>
<p>This is a classic CSS problem. In the "bad-old-days", web designers would have done it using a table, with fixed widths on the table cells. This obviously isn't the answer for today's web designers, but it is something that causes a lot of questions.</p>
<p>There are a number of ways to do it using CSS.</p>
<p>The easiest is to set both the <code><span></code> elements to <code>display:inline-block;</code>, and give them both a fixed width.</p>
<p>eg:</p>
<pre><code><div class='section'>
<span class="element-left">some text</span>
<span class="element-right">some text</span>
</div>
</code></pre>
<p>with the following CSS:</p>
<pre><code>.section span {display:inline-block;}
.element-left {width:200px;}
.element-right {width:150px;}
</code></pre>
<p>[EDIT]<em>after question has been updated</em></p>
<p>Here's how I would achieve what you're asking now:</p>
<pre><code><div class='section'>
<span class="element-left"><span class='indent-0'>some text</span></span>
<span class="element-right">some text</span>
</div>
<div class='section'>
<span class="element-left"><span class='indent-1'>some text</span></span>
<span class="element-right">some text</span>
</div>
<div class='section'>
<span class="element-left"><span class='indent-2'>some text</span></span>
<span class="element-right">some text</span>
</div>
</code></pre>
<p>with the following CSS:</p>
<pre><code>.section span {display:inline-block;}
.element-left {width:200px;}
.indent-1 {padding:10px;}
.indent-2 {padding:20px;}
.element-right {width:150px;}
</code></pre>
<p>A small amount of extra markup, but it does achieve the effect you want.</p> |
4,974,309 | Android SDK and Developer Guide Offline or PDF | <p>Where can I get PDF version of Android SDK docs and developer guide. Saw a posting that installed sdk has the html docs, mine does not. Is this a separate download. any eclipse update for this? Thanks</p> | 4,974,377 | 3 | 1 | null | 2011-02-11 21:33:53.35 UTC | 17 | 2015-01-20 09:58:17.413 UTC | 2011-02-12 04:06:13.07 UTC | null | 210,916 | null | 602,260 | null | 1 | 46 | android|pdf|documentation | 100,664 | <p>I think only HTML is available and you get it by installing the Documentation using the Android SDK tool:</p>
<p><img src="https://i.stack.imgur.com/TLbKI.png" alt="enter image description here"></p>
<p>(See the 4th item in the list).</p> |
18,495,874 | Failed to Create Cookie file RabbitMQ in Windows | <p>I am trying to run the following command </p>
<pre><code>rabbitmq-plugins.bat enable rabbitmq_management
</code></pre>
<p>and its giving me an error like this:</p>
<blockquote>
<p>11:36:55.464 [error] Failed to create cookie file 'h:/.erlang.cookie': enoent</p>
</blockquote>
<p>I am using windows 7, Erlang Version R16B01 and RabbitMQ-Server version 3.1.5</p>
<p>I am using my work PC and our Corporate policy sets the HOMEDRIVE to h: and HOMEPATH to /
and i dont think they will let me change this.</p>
<p>I can see the .erlang.cookie file under C:\Windows.</p>
<p>Could someone let me know of a workaround for this ?</p>
<p>Thanks in advance !</p> | 29,018,928 | 6 | 2 | null | 2013-08-28 18:46:03.397 UTC | 7 | 2022-03-01 03:41:51.82 UTC | 2019-08-30 06:35:19.677 UTC | null | 2,909,851 | null | 636,525 | null | 1 | 31 | erlang|rabbitmq | 27,167 | <p>Had the same H: problem. Set the home drive to some dir in the dos shell before executing the cli.</p>
<pre><code>set HOMEDRIVE=C:/conf/rabbitmq :: Or your favorite dir
rabbitmq-plugins.bat enable rabbitmq_management
</code></pre>
<p>Use a folder in C drive. The rabbitmq system will write the cookie file there.</p> |
18,374,103 | Exception Value:failed to find libmagic. Check your installation in windows 7 | <p>When I am trying to open django admin panel this error is showing:</p>
<pre><code>ImportError at /admin/
failed to find libmagic. Check your installation
Request Method: GET
Request URL: Django Version: 1.5.1
Exception Type: ImportError
Exception Value: failed to find libmagic. Check your installation
Exception Location: C:\Python27\lib\site-packages\magic.py in <module>, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['C:\\Users\\farhan\\Downloads\\dist\\Django-1.5.1\\django\\bin\\mysite',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time: Thu, 22 Aug 2013 13:19:01 +0600
</code></pre>
<p><a href="http://dpaste.com/1353012/" rel="noreferrer">Here is my traceback</a></p> | 18,377,915 | 7 | 3 | null | 2013-08-22 07:23:22.56 UTC | 6 | 2021-10-04 15:36:58.51 UTC | 2019-08-02 19:09:52.177 UTC | null | 1,896,134 | null | 1,104,240 | null | 1 | 31 | python|django|django-admin | 45,712 | <p>Your multiuploader form uses python-magic library possibly for filetype identification. However you probably do not have all the missing dependencies installed. Please install the missing dependencies.</p>
<p><a href="https://github.com/ahupp/python-magic#dependencies" rel="noreferrer">https://github.com/ahupp/python-magic#dependencies</a> </p> |
20,136,504 | How can set a default value constraint with Entity Framework 6 Code First? | <p>In a legacy app, most string properties can't be null and need to have a default value of string.empty.</p>
<p>I know it's possible to do this with migrations, but I'm looking for a way to do this using the fluent configuration interface:</p>
<pre><code> protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<string>().Configure(c =>
{
c.HasMaxLength(255);
if (!c.ClrPropertyInfo.IsDefined(typeof (NullableAttribute), false))
{
c.IsRequired();
// I want to set a default value (string.empty) here.
}
}
</code></pre>
<p>Is there any way to do this or I'm doomed to initialize all strings in the entity constructors?</p> | 29,108,905 | 6 | 3 | null | 2013-11-22 03:27:51.85 UTC | 9 | 2021-10-18 23:39:13.91 UTC | null | null | null | null | 1,038,611 | null | 1 | 39 | c#|.net|entity-framework|ef-code-first|entity-framework-6 | 74,617 | <p>Now the answer is <a href="https://stackoverflow.com/a/21712657/1341409">Yes</a>:</p>
<pre><code>AddColumn("[table name]",
"[column name]",
c => c.Boolean(nullable: false, defaultValue: false));
</code></pre> |
14,935,996 | How to use a filter in javascript instead of the Html | <p>I'm using AngularJS and it's great.
I can't find it in the Documentation - What is the equivalent in Javascript to this AngularJS expression: </p>
<pre><code><div>{{ (myList| filter:mySearch).length }}</div>
</code></pre>
<p>Thanks for the help.</p> | 14,936,581 | 3 | 2 | null | 2013-02-18 12:11:02.253 UTC | 7 | 2017-02-14 11:50:35.687 UTC | 2017-02-14 11:50:35.687 UTC | null | 146,309 | null | 1,092,238 | null | 1 | 52 | angularjs | 76,031 | <p>It's on Angular's <a href="http://docs.angularjs.org/api/ng.filter%3afilter">filter documentation</a>:</p>
<h2>In HTML Template Binding</h2>
<blockquote>
<p>{{ filter_expression | filter:expression }}</p>
</blockquote>
<h2>In JavaScript</h2>
<blockquote>
<p>$filter('filter')(array, expression)</p>
</blockquote>
<p>In your case, it would look something like <code>$filter('filter')(myList, mySearch)</code>.</p> |
15,289,250 | Using make with -j4 or -j8 | <p>I have 4 processors and am compiling a processor-hungry application. I read that using <code>make</code> with the <code>-j4</code> switch was recommended for OpenCV; should I instead use <code>-j8</code>? What is the advantage of making for multiple processors?</p> | 15,289,348 | 4 | 3 | null | 2013-03-08 07:58:04.193 UTC | 23 | 2022-05-31 15:37:27.673 UTC | 2021-07-24 04:14:10.77 UTC | null | 11,047,824 | user784435 | null | null | 1 | 65 | c|opencv|makefile | 91,082 | <p>As you say the <code>-j</code> flag tells <code>make</code> that it is allowed to spawn the provided amount of 'threads'. Ideally each thread is executed on its own core/CPU, so your multi-core/CPU environment is used to its fullest.</p>
<p><code>make</code> itself does not compile the source files. This is done by a compiler (gcc). The Makefile (input for <code>make</code>) contains a set of targets. Each target has a set of dependencies (on other targets) and rules how to build the target. <code>make</code> reads the Makefile(s) and manages all targets, dependencies, and build rules. Besides compiling source files you can use <code>make</code> to perform any task that can be described by shell commands.</p>
<p>If you set the allowed number of threads too high, it is not possible to schedule each thread on its own core. Additional scheduling (context) switches are required to let all threads execute. This additional resource usage obviously result in lower performance.</p>
<p>There are multiple rules-of-thumb, but I guess that setting to total amount to <code><number of cores> + 1</code> is the most common. The idea behind this is that all cores have their own thread and there is one additional managing thread that handles the targets and which is next to be built.</p> |
43,663,552 | Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify | <p>For some reason, the <code>jsonify</code> function is converting my <code>datetime.date</code> to what appears to be an HTTP date. How can I keep the date in <code>yyyy-mm-dd</code> format when using <code>jsonify</code>?</p>
<pre><code>test_date = datetime.date(2017, 4, 27)
print(test_date) # 2017-04-27
test_date_jsonify = jsonify(test_date)
print(test_date_jsonify.get_data(as_text=True)) # Thu, 27 Apr 2017 00:00:00 GMT
</code></pre>
<p>As suggested in the comments, using <code>jsonify(str(test_date))</code> returns the desired format. However, consider the following case:</p>
<pre><code>test_dict = {"name": "name1", "date":datetime.date(2017, 4, 27)}
print(test_dict) # {"name": "name1", "date":datetime.date(2017, 4, 27)}
test_dict_jsonify = jsonify(test_dict)
print(test_dict_jsonify.get_data(as_text=True)) # {"date": "Thu, 27 Apr 2017 00:00:00 GMT", "name": "name1"}
test_dict_jsonify = jsonify(str(test_dict))
print(test_dict_jsonify.get_data(as_text=True)) # "{"date": datetime.date(2017, 4, 27), "name": "name1"}"
</code></pre>
<p>In this case, the <code>str()</code> solution does not work.</p> | 43,663,918 | 3 | 5 | null | 2017-04-27 16:43:39.2 UTC | 6 | 2020-01-13 22:29:04.577 UTC | 2017-04-27 17:25:26.477 UTC | null | 400,617 | null | 6,358,210 | null | 1 | 32 | python|json|date|datetime|flask | 18,865 | <p>Following <a href="http://flask.pocoo.org/snippets/119/" rel="noreferrer">this snippet</a> you can do this:</p>
<pre><code>from flask.json import JSONEncoder
from datetime import date
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, date):
return obj.isoformat()
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
app = Flask(__name__)
app.json_encoder = CustomJSONEncoder
</code></pre>
<p>Route:</p>
<pre><code>import datetime as dt
@app.route('/', methods=['GET'])
def index():
now = dt.datetime.now()
return jsonify({'now': now})
</code></pre> |
45,207,104 | How to set jwt token expiry time to maximum in nodejs? | <p>I dont want my token to get expire and shold be valid forever.</p>
<pre><code>var token = jwt.sign({email_id:'[email protected]'}, "Stack", {
expiresIn: '24h' // expires in 24 hours
});
</code></pre>
<p>In above code i have given for 24 hours..
I do not want my token to get expire.
What shall be done for this?</p> | 45,209,610 | 5 | 8 | null | 2017-07-20 06:42:29.477 UTC | 15 | 2022-07-13 13:11:24.967 UTC | null | null | null | null | 7,207,508 | null | 1 | 60 | node.js|jwt | 205,779 | <p>The <code>exp</code> claim of a JWT is optional. If a token does not have it, it is considered that it does not expire</p>
<p>According to the documentation of <a href="https://www.npmjs.com/package/jsonwebtoken" rel="nofollow noreferrer">https://www.npmjs.com/package/jsonwebtoken</a> the <code>expiresIn</code> field does not have a default value either, so just omit it.</p>
<blockquote>
<p><strong>There are no default values for expiresIn,</strong> notBefore, audience, subject, issuer. These claims can also be provided in the payload directly with exp, nbf, aud, sub and iss respectively, but you can't include them in both places.</p>
</blockquote>
<pre><code>var token = jwt.sign({email_id:'[email protected]'}, "Stack", {});
</code></pre> |
7,787,317 | List of different types? | <pre><code>data Plane = Plane { point :: Point, normal :: Vector Double }
data Sphere = Sphere { center :: Point, radius :: Double }
class Shape s where
intersect :: s -> Ray -> Maybe Point
surfaceNormal :: s -> Point -> Vector Double
</code></pre>
<p>I have also made both <code>Plane</code> and <code>Sphere</code> instances of <code>Shape</code>.</p>
<p>I'm trying to store spheres and planes in the same list, but it doesn't work. I understand that it shouldn't work because <code>Sphere</code> and <code>Plane</code> are two different types, but they are both instances of <code>Shape</code>, so shouldn't it work? How would I store shapes and planes in a list?</p>
<pre><code>shapes :: (Shape t) => [t]
shapes = [ Sphere { center = Point [0, 0, 0], radius = 2.0 },
Plane { point = Point [1, 2, 1], normal = 3 |> [0.5, 0.6, 0.2] }
]
</code></pre> | 7,787,730 | 2 | 2 | null | 2011-10-16 21:04:55.07 UTC | 15 | 2017-02-28 20:31:48.73 UTC | null | null | null | null | 554,075 | null | 1 | 45 | haskell | 11,589 | <p>This problem represents a turning point between object-oriented and functional thinking. Sometimes even sophisticated Haskellers are still in this mental transition, and their designs often fall into the <a href="http://lukepalmer.wordpress.com/2010/01/24/haskell-antipattern-existential-typeclass/" rel="noreferrer">existential typeclass</a> pattern, mentioned in Thomas's answer. </p>
<p>A functional solution to this problem involves reifying the typeclass into a data type (usually once this is done, the need for the typeclass vanishes):</p>
<pre><code>data Shape = Shape {
intersect :: Ray -> Maybe Point,
surfaceNormal :: Point -> Vector Double
}
</code></pre>
<p>Now you can easily construct a list of <code>Shape</code>s, because it is a monomorphic type. Because Haskell does not support downcasting, no information is lost by removing the representational distinction between <code>Plane</code>s and <code>Sphere</code>s. The specific data types become functions that construct <code>Shape</code>s:</p>
<pre><code>plane :: Point -> Vector Double -> Shape
sphere :: Point -> Double -> Shape
</code></pre>
<p>If you cannot capture everything you need to know about a shape in the <code>Shape</code> data type, you can enumerate the cases with an algebraic data type, as Thomas suggested. But I would recommend against that if possible; instead, try to find the essential characteristics of a shape that you need rather than just listing off examples.</p> |
8,186,457 | Specify width in *characters* | <p>When using a <strong>fixed width font</strong>, I'd like to specify the width of an HTML element in <em>characters</em>.</p>
<p>The "em" unit is supposed to be the width of the M character, so I should be able to use it to specify a width. This is an example:</p>
<pre><code><html>
<head>
<style>
div {
font-family: Courier;
width: 10em;
}
</style>
</head>
<body>
<div>
1 3 5 7 9 1 3 5 7 9 1
</div>
</body>
</html>
</code></pre>
<p>The result is not what I wanted as the browser line breaks after column 15, not 10:</p>
<pre><code>1 3 5 7 9 1 3 5
7 9 1
</code></pre>
<p>(Result in Firefox and Chromium, both in Ubuntu.)</p>
<p><a href="https://secure.wikimedia.org/wikipedia/en/wiki/Em_%28typography%29" rel="noreferrer">Wikipedia's article</a> says that an "em" is not always the width of an M, so it definitely looks like the "em" unit can't be trusted for this.</p> | 8,204,354 | 2 | 6 | null | 2011-11-18 17:31:36.803 UTC | 18 | 2019-05-30 11:09:04.027 UTC | 2011-11-18 23:32:28.48 UTC | null | 2,711,383 | null | 2,711,383 | null | 1 | 137 | css|font-size | 98,108 | <p>1em is the height of an M, rather than the width. Same holds for ex, which is the height of an x. More generally speaking, these are the heights of uppercase and lowercase letters.</p>
<p>Width is a totally different issue....</p>
<p>Change your example above to </p>
<pre><code><div>
<span>1</span> 3 5 7 9 1 3 5 7 9 1
</div>
</code></pre>
<p>and you will notice width and height of the span are different. For a font-size of 20px on Chrome the span is 12x22 px, where 20px is the height of the font, and 2px are for line height.</p>
<p>Now since em and ex are of no use here, a possible strategy for a CSS-only solution would be to </p>
<ol>
<li>Create an element containing just a &nbsp;</li>
<li>Let it autosize itself</li>
<li>Place your div within and</li>
<li>Make it 10 times as large as the surrounding element.</li>
</ol>
<p>I however did not manage to code this up. I also doubt it really is possible.</p>
<p>The same logic could however be implemented in Javascript. I'm using ubiquitous jQuery here:</p>
<pre><code><html>
<head>
<style>
body { font-size: 20px; font-family: Monospace; }
</style>
<script
type="text/javascript"
src ="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
</head>
<body>
<div>1 3 5 7 9 1 3 5 7 9 1</div>
<script>
$('body').append('<div id="testwidth"><span>&nbsp;</span></div>');
var w = $('#testwidth span').width();
$('#testwidth').remove();
$('div').css('width', (w * 10 + 1) + 'px');
</script>
</body>
</html>
</code></pre>
<p>The +1 in (w * 10 + 1) is to handle rounding problems. </p> |
9,066,609 | Fastest possible grep | <p>I'd like to know if there is any tip to make <strong><code>grep</code></strong> as fast as possible. I have a rather large base of text files to search in the quickest possible way. I've made them all lowercase, so that I could get rid of <code>-i</code> option. This makes the search much faster.</p>
<p>Also, I've found out that <code>-F</code> and <code>-P</code> modes are quicker than the default one. I use the former when the search string is not a regular expression (just plain text), the latter if regex is involved.</p>
<p>Does anyone have any experience in speeding up <code>grep</code>? Maybe compile it from scratch with some particular flag (I'm on Linux CentOS), organize the files in a certain fashion or maybe make the search parallel in some way?</p> | 9,067,042 | 12 | 11 | null | 2012-01-30 15:50:43.37 UTC | 78 | 2018-02-27 10:10:29.287 UTC | 2017-02-17 23:54:40.983 UTC | null | 6,862,601 | null | 42,636 | null | 1 | 80 | bash|unix|grep | 89,970 | <p>Try with <a href="http://www.gnu.org/software/parallel/" rel="nofollow noreferrer">GNU parallel</a>, which includes <a href="https://www.gnu.org/software/parallel/man.html#EXAMPLE:-Parallel-grep" rel="nofollow noreferrer">an example of how to use it with <code>grep</code></a>:</p>
<blockquote>
<p><code>grep -r</code> greps recursively through directories. On multicore CPUs GNU
<code>parallel</code> can often speed this up.</p>
<pre><code>find . -type f | parallel -k -j150% -n 1000 -m grep -H -n STRING {}
</code></pre>
<p>This will run 1.5 job per core, and give 1000 arguments to <code>grep</code>.</p>
</blockquote>
<p>For big files, it can split it the input in several chunks with the <code>--pipe</code> and <code>--block</code> arguments:</p>
<pre><code> parallel --pipe --block 2M grep foo < bigfile
</code></pre>
<p>You could also run it on several different machines through SSH (ssh-agent needed to avoid passwords):</p>
<pre><code>parallel --pipe --sshlogin server.example.com,server2.example.net grep foo < bigfile
</code></pre> |
4,901,128 | Obtaining the array Class of a component type | <p>If I have an instance of <code>Class</code>, is there a way of obtaining a <code>Class</code> instance for its array type? What I'm essentially asking for is the equivalent of a method <code>getArrayType</code> which is the inverse of the <code>getComponentType()</code> method, such that:</p>
<pre><code>array.getClass().getComponentType().getArrayType() == array.getClass()
</code></pre> | 4,901,192 | 5 | 0 | null | 2011-02-04 17:39:07.95 UTC | 5 | 2022-01-16 22:53:12.543 UTC | null | null | null | null | 272,176 | null | 1 | 49 | java|arrays | 19,890 | <p>One thing that comes to mind is:</p>
<pre><code>java.lang.reflect.Array.newInstance(componentType, 0).getClass();
</code></pre>
<p>But it creates an unnecessary instance.</p>
<p>Btw, this appears to work:</p>
<pre><code>Class clazz = Class.forName("[L" + componentType.getName() + ";");
</code></pre>
<p>Here is test. It prints <code>true</code>:</p>
<pre><code>Integer[] ar = new Integer[1];
Class componentType = ar.getClass().getComponentType();
Class clazz = Class.forName("[L" + componentType.getName() + ";");
System.out.println(clazz == ar.getClass());
</code></pre>
<p><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getName%28%29" rel="noreferrer">The documentation of <code>Class#getName()</code></a> defines strictly the format of array class names:</p>
<blockquote>
<p>If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting.</p>
</blockquote>
<p>The <code>Class.forName(..)</code> approach won't directly work for primitives though - for them you'd have to create a mapping between the name (<code>int</code>) and the array shorthand - (<code>I</code>)</p> |
5,330,895 | CSS for "fill parent width?" | <p>I have an item on the DOM that I'd simply like to have fill its parent's width, regardless of what that is:</p>
<pre><code><div width="800">
<div class="filler"></div>
</div>
</code></pre>
<p>How can I specify in CSS that the <code>filler</code> class match the width of its parent?</p>
<pre><code>.filler {
?
}
</code></pre> | 5,330,915 | 6 | 2 | null | 2011-03-16 19:46:36.92 UTC | 2 | 2021-05-18 07:36:22.877 UTC | 2021-05-18 07:33:52.867 UTC | null | 1,684,875 | null | 128,967 | null | 1 | 53 | css | 127,768 | <p>Have you tried: <code>width: 100%;</code> ?</p> |
5,207,613 | How to output ${expression} in Freemarker without it being interpreted? | <p>I'm trying to use Freemarker in conjunction with jQuery Templates.</p>
<p>Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. <code>${person.name}</code> . </p>
<p>So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).</p>
<p>I've tried various combinations of escaping the <code>${</code> sequence to pass it through Freemarker to no avail - <code>\${</code>, <code>\$\{</code>, <code>$\{</code>, etc. </p>
<p>Inserting a freemarker comment in between the dollar and the curly (e.g. <code>$<#-- -->{expression}</code>) DOES work - but I'm looking for a more concise and elegant solution.</p>
<p>Is there a simpler way to get a Freemarker template to output the character sequence <code>${</code>?</p> | 5,207,658 | 8 | 0 | null | 2011-03-05 23:47:36.4 UTC | 8 | 2020-01-16 22:02:30.723 UTC | null | null | null | null | 120,103 | null | 1 | 36 | el|freemarker|jquery-templates | 35,016 | <p>This should print ${person.name}:</p>
<pre><code>${r"${person.name}"}
</code></pre>
<p>From the <a href="https://freemarker.apache.org/docs/dgui_template_exp.html#dgui_template_exp_direct_string" rel="noreferrer">freemarker docs</a></p>
<blockquote>
<p>A special kind of string literals is the raw string literals. In raw string literals, backslash and ${ have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an r directly before the opening quotation mark or apostrophe-quote</p>
</blockquote> |
4,884,681 | How to use "cd" command using Java runtime? | <p>I've created a standalone java application in which I'm trying to change the directory using the "cd" command in Ubuntu 10.04 terminal. I've used the following code.</p>
<pre><code>String[] command = new String[]{"cd",path};
Process child = Runtime.getRuntime().exec(command, null);
</code></pre>
<p>But the above code gives the following error </p>
<pre><code>Exception in thread "main" java.io.IOException: Cannot run program "cd": java.io.IOException: error=2, No such file or directory
</code></pre>
<p>Can anyone please tell me how to implement it? </p> | 4,884,715 | 8 | 1 | null | 2011-02-03 10:02:02.413 UTC | 9 | 2021-06-28 15:32:45.17 UTC | 2013-07-10 20:12:15.323 UTC | null | 40,342 | null | 451,951 | null | 1 | 56 | java|terminal|runtime|runtime.exec|cd | 99,756 | <p>There is no executable called <code>cd</code>, because it <strong>can't</strong> be implemented in a separate process.</p>
<p>The problem is that each process has its own current working directory and implementing <code>cd</code> as a separate process would only ever change <strong>that</strong> processes current working directory.</p>
<p>In a Java program you <strong>can't</strong> change your current working directory and you shouldn't need to. Simply use absolute file paths.</p>
<p>The one case where the current working directory matters is executing an external process (using <code>ProcessBuilder</code> or <code>Runtime.exec()</code>). In those cases you can specify the working directory to use for the newly started process explicitly (<a href="http://download.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html#directory(java.io.File)" rel="noreferrer"><code>ProcessBuilder.directory()</code></a> and the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String,%20java.lang.String%5B%5D,%20java.io.File)" rel="noreferrer">three-argument <code>Runtime.exec()</code></a> respectively).</p>
<p>Note: the current working directory can be read from the <a href="http://download.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties()" rel="noreferrer">system property</a> <code>user.dir</code>. You might feel tempted to <em>set</em> that system property. Note that doing so will lead to <a href="https://stackoverflow.com/questions/2275362/java-file-exists-inconsistencies-when-setting-user-dir">very bad inconsistencies</a>, because <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4117557" rel="noreferrer">it's not <em>meant</em> to be writable</a>.</p> |
5,010,042 | MySQL: Get column name or alias from query | <p>I'm not asking for the <code>SHOW COLUMNS</code> command.</p>
<p>I want to create an application that works similarly to heidisql, where you can specify an SQL query and when executed, returns a result set with rows and columns representing your query result. The column names in the result set should match your selected columns as defined in your SQL query.</p>
<p>In my Python program (using <code>MySQLdb</code>) my query returns only the row and column results, but not the column names. In the following example the column names would be <code>ext</code>, <code>totalsize</code>, and <code>filecount</code>. The SQL would eventually be external from the program. </p>
<p>The only way I can figure to make this work, is to write my own SQL parser logic to extract the selected column names.</p>
<p>Is there an easy way to get the column names for the provided SQL?
Next I'll need to know how many columns does the query return?</p>
<pre><code># Python
import MySQLdb
#===================================================================
# connect to mysql
#===================================================================
try:
db = MySQLdb.connect(host="myhost", user="myuser", passwd="mypass",db="mydb")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
#===================================================================
# query select from table
#===================================================================
cursor = db.cursor ()
cursor.execute ("""\
select ext,
sum(size) as totalsize,
count(*) as filecount
from fileindex
group by ext
order by totalsize desc;
""")
while (1):
row = cursor.fetchone ()
if row == None:
break
print "%s %s %s\n" % (row[0], row[1], row[2])
cursor.close()
db.close()
</code></pre> | 5,058,950 | 12 | 1 | null | 2011-02-15 22:01:17.607 UTC | 42 | 2022-03-19 04:16:47.863 UTC | 2016-11-01 22:53:38.987 UTC | null | 2,178,980 | null | 259,538 | null | 1 | 102 | python|mysql|mysql-python | 176,217 | <p>cursor.description will give you a tuple of tuples where [0] for each is the column header.</p>
<pre><code>num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]
</code></pre> |
12,079,332 | creating simple cookies in asp.net c# | <p>My application needs to store cookies. When a user logs on I want to make sure that if the cookie does not exist create it and store value, but if it does modify it.</p>
<pre><code>if(cookieExist)
{
cookiename = "value";
}
else
{
create a new cookie
then store the value;
}
</code></pre>
<p>Thanks for any help</p> | 12,079,406 | 1 | 2 | null | 2012-08-22 18:36:04.747 UTC | 6 | 2016-12-06 08:48:05.337 UTC | 2012-08-22 18:39:38.34 UTC | null | 826,659 | null | 516,883 | null | 1 | 8 | c#|asp.net | 48,380 | <p>You have to use <code>Request.Cookies</code> to get cookie value and <code>Response.Cookies</code> to add cookies</p>
<pre><code> string cookievalue ;
if ( Request.Cookies["cookie"] != null )
{
cookievalue = Request.Cookies["cookie"].ToString();
}
else
{
Response.Cookies["cookie"].Value = "cookie value";
Response.Cookies["cookie"].Expires = DateTime.Now.AddMinutes(1); // add expiry time
}
</code></pre> |
12,306,330 | pass kinit a custom krb5.conf file | <p>I'm using kinit to log into a server that my sys admin didn't anticipate us using. It seems that the default location for the config file is <code>/etc/krb5.conf</code>, but I don't have root access so I can't edit this file to add a new server. How can I pass kinit a custom config file? </p> | 12,308,187 | 3 | 0 | null | 2012-09-06 18:35:54.157 UTC | 7 | 2021-12-23 09:45:19.927 UTC | null | null | null | null | 915,501 | null | 1 | 25 | kerberos | 41,598 | <p>OK, solved the problem: the default config file location can be overridden by setting the <a href="http://web.mit.edu/kerberos/krb5-current/doc/user/user_config/kerberos.html#kerberos-7" rel="noreferrer"><code>KRB5_CONFIG</code> environment variable</a></p> |
12,528,644 | Count duplicates records in Mysql table? | <p>I have table with, folowing structure. </p>
<p>tbl </p>
<pre><code>id name
1 AAA
2 BBB
3 BBB
4 BBB
5 AAA
6 CCC
select count(name) c from tbl
group by name having c >1
</code></pre>
<p>The query returning this result:</p>
<pre><code>AAA(2) duplicate
BBB(3) duplicate
CCC(1) not duplicate
</code></pre>
<p>The names who are duplicates as AAA and BBB. The final result, who I want is count of this duplicate records.</p>
<p>Result should be like this:
Total duplicate products (<strong>2</strong>)</p> | 12,528,717 | 7 | 3 | null | 2012-09-21 10:19:36.807 UTC | 8 | 2022-02-16 11:21:29.993 UTC | null | null | null | null | 1,107,629 | null | 1 | 27 | mysql|duplicates | 66,962 | <p>The approach is to have a nested query that has one line per duplicate, and an outer query returning just the count of the results of the inner query.</p>
<pre><code>SELECT count(*) AS duplicate_count
FROM (
SELECT name FROM tbl
GROUP BY name HAVING COUNT(name) > 1
) AS t
</code></pre> |
12,295,352 | How to change the font color / Text Color of the UIBarButtonItem on navigation bar | <p>I add a bar button to the navigation bar programitically as follows</p>
<pre><code>UIBarButtonItem *cancel = [[UIBarButtonItem alloc] initWithTitle:@"CANCEL" style:UIBarButtonItemStyleBordered target:self action:@selector(goToPreviousView)];
self.navigationItem.leftBarButtonItem = cancel;
</code></pre>
<p>Now I want to display <strong>Text "CANCEL" in RED Color</strong>.</p>
<p>I mean that I need to change the <strong>text on the bar button items</strong>, but not the tint color of the button.</p>
<p>How to do that?</p> | 12,295,444 | 12 | 2 | null | 2012-09-06 07:51:55.193 UTC | 5 | 2020-10-21 10:24:26.067 UTC | 2015-06-01 07:44:47.01 UTC | null | 2,476,755 | null | 1,645,721 | null | 1 | 31 | iphone|objective-c|ios|xcode|ipad | 38,219 | <p>Another method is :-</p>
<pre><code>UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
[button setTitle:@"Delete" forState:UIControlStateNormal];
button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
[button.layer setCornerRadius:4.0f];
[button.layer setMasksToBounds:YES];
[button.layer setBorderWidth:1.0f];
[button.layer setBorderColor: [[UIColor grayColor] CGColor]];
button.frame=CGRectMake(0.0, 100.0, 60.0, 30.0);
[button addTarget:self action:@selector(batchDelete) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem* deleteItem = [[UIBarButtonItem alloc] initWithCustomView:button];
</code></pre> |
12,559,208 | How to remove comma from number which comes dynamically in .tpl file | <p>i want to remove comma from a number (e.g change 1,125 to 1125 ) in a .tpl file.
The value comes dynamically like <code>${variableMap[key]}</code></p> | 12,559,256 | 7 | 0 | null | 2012-09-24 05:18:48.177 UTC | 8 | 2022-09-14 08:15:08.45 UTC | 2012-09-24 15:05:34.663 UTC | null | 250,259 | null | 808,409 | null | 1 | 35 | javascript|jquery|gwt | 104,936 | <pre><code>var a='1,125';
a=a.replace(/\,/g,''); // 1125, but a string, so convert it to number
a=parseInt(a,10);
</code></pre>
<p>Hope it helps.</p> |
12,566,228 | Candidate template ignored because template argument could not be inferred | <p>What is wrong with the following piece of code?</p>
<pre><code>#include <iostream>
template<typename K>
struct A {
struct X { K p; };
struct Y { K q; };
};
template<typename K>
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
std::cout << "A" << std::endl;
}
int main() {
A<float>::X x;
A<float>::Y y;
foo(x, y);
}
</code></pre>
<p>clang gives the following error message:</p>
<pre><code>17:2: error: no matching function for call to 'foo'
foo(x, y);
^~~
10:6: note: candidate template ignored: couldn't infer template argument 'K'
void foo(const typename A<K>::X& x, const typename A<K>::Y& y) {
^
1 error generated.
</code></pre> | 12,566,268 | 3 | 0 | null | 2012-09-24 13:37:30.963 UTC | 4 | 2020-01-02 10:50:52.063 UTC | null | null | null | null | 316,448 | null | 1 | 38 | c++|templates | 29,745 | <p>The argument <code>K</code> in <code>const typename A<K>::X</code> is <em>not deducible</em>. Basically, everything left of a <code>::</code> is not deducible (if <code>::</code> separates a nested-name).</p>
<p>It's trivial to see why it makes no sense to ask for deduction by running through this thought experiment:</p>
<pre><code>struct A { typedef int type; }
struct B { typedef int type; }
template <typename T> void foo(typename T::type);
foo(5); // is T == A or T == B ??
</code></pre>
<p>There's no one-to-one mapping from types to nested types: Given any type (such as <code>int</code>), there could be many ambient types of which it is a nested type, or there needn't be any.</p> |
12,458,522 | Bootstrap dropdown not working | <p>I can't make bootstrap dropdown to work.
Here is my html for nav:</p>
<pre><code><ul class='nav'>
<li class='active'>Home</li>
<li class='dropdown'>
<a class="dropdown-toggle" data-toggle="dropdown" href='#'>Personal asset loans</a>
<ul class="dropdown-menu" role="menu">
<li><a href="#">asds</a></li>
<li class="divider"></li>
</ul>
</li>
<li>Payday loans</li>
<li>About</li>
<li>Contact</li>
</ul>
</code></pre>
<p>And here are the scripts:</p>
<pre><code><script type="text/javascript" src="js/bootstrap/bootstrap-dropdown.js"></script>
<script>
$(document).ready(function(){
$('.dropdown-toggle').dropdown()
});
</script>
</code></pre>
<p>What am I doing wrong? Thanks for your answers!</p> | 12,458,825 | 30 | 8 | null | 2012-09-17 11:46:11.07 UTC | 21 | 2022-08-25 06:33:58.57 UTC | 2015-06-01 11:26:41.84 UTC | null | 1,770,831 | null | 855,705 | null | 1 | 111 | html|drop-down-menu|twitter-bootstrap | 450,524 | <p>Working demo: <a href="http://codebins.com/bin/4ldqp73" rel="noreferrer">http://codebins.com/bin/4ldqp73</a></p>
<p>try this </p>
<pre><code><ul class='nav'>
<li class='active'>Home</li>
<li>
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Personal asset loans</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
<li><a href="#">asds</a></li>
<li class="divider"></li>
</ul>
</div>
</li>
<li>Payday loans</li>
<li>About</li>
<li>Contact</li>
</ul>
</code></pre> |
19,237,419 | Sorting 2D Array C++ | <p>Is it possible to sort a 2D Array using qsort or std::sort in C++ such that the elements are in increasing order when read from left to right in each row or from top to bottom in each column?</p>
<p>For example,</p>
<pre><code>13, 14, 15, 16
1, 4, 3, 2
7, 5, 7, 6
9, 10, 11, 12
</code></pre>
<p>Becomes:</p>
<pre><code>{ 1, 2, 3, 4 }
{ 5, 6, 7, 8 }
{ 9, 10, 11, 12 }
{ 13, 14, 15, 16 }
</code></pre>
<p>I know you can do it by creating two comparison functions and then first sorting each row then comparing the first elements of each row to establish the columns, but is there a way to do it in one function itself?</p> | 19,237,620 | 5 | 7 | null | 2013-10-08 01:06:35.8 UTC | 3 | 2015-05-07 17:47:38 UTC | 2013-10-08 01:12:10.013 UTC | null | 528,724 | null | 2,612,743 | null | 1 | 4 | c++|sorting | 39,496 | <p>Yes. C++ STL library is built with separation of <em>algorithms</em> and <em>containers</em>. What links them together is <em>iterators</em>. Raw pointer is <em>iterator</em>, therefore it is possible to initialize vector with raw pointers and then sort that vector as usual.</p>
<pre><code>std::vector<int> v(arr2d, arr2d + N); // create a vector based on pointers
// This assumes array is contiguous range
// in memory, N=number of elemnts in arr2d
// using default comparison (operator <):
std::sort (v.begin(), v.end());
// cout by 4 elements in a row
</code></pre> |
24,350,763 | How can C# allow virtual generic methods where C++ can't allow virtual template methods? | <p>C++ does not support virtual template methods. The reason is that this would alter the <code>vtable</code> whenever a new instantiation of such a method is made (it has to be added to the <code>vtable</code>).</p>
<p>Java in contrast does allow virtual generic methods. Here, it is also clear how this can be implemented: Java generics are erased at runtime, so a generic method is a usual method at runtime, so no alterations of the <code>vtable</code> necessary.</p>
<p>But now to C#. C# does have reified generics. With reified generics and especially when using value types as type parameters, there have to be different versions of a generic method. But then we have the same problem as C++ has: We would need to alter the vtable whenever a new instantiation of a generic method was made.</p>
<p>I am not too deep into the inner workings of C#, so my intuition could simply be totally wrong. So can someone with more in-depth knowledge about C#/.NET tell me how they are able to implement generic virtual methods in C#?</p>
<p>Here's code to show what I mean:</p>
<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]
static void Test_GenericVCall()
{
var b = GetA();
b.M<string>();
b.M<int>();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static A GetA()
{
return new B();
}
class A
{
public virtual void M<T>()
{
}
}
class B : A
{
public override void M<T>()
{
base.M<T>();
Console.WriteLine(typeof(T).Name);
}
}
</code></pre>
<p>How does the CLR dispatch to the correct JITed code when calling <code>M</code> in the function <code>Test_GenericVCall</code>?</p> | 24,351,699 | 5 | 9 | null | 2014-06-22 11:24:51.143 UTC | 5 | 2014-06-23 09:15:35.953 UTC | 2014-06-23 09:15:35.953 UTC | null | 1,018,140 | null | 1,408,611 | null | 1 | 32 | c#|c++|templates|generics|generic-method | 3,679 | <p>Running this code and analyzing the IL and generated ASM allows us to see what is going on:</p>
<pre><code>internal class Program
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Test()
{
var b = GetA();
b.GenericVirtual<string>();
b.GenericVirtual<int>();
b.GenericVirtual<StringBuilder>();
b.GenericVirtual<int>();
b.GenericVirtual<StringBuilder>();
b.GenericVirtual<string>();
b.NormalVirtual();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static A GetA()
{
return new B();
}
private class A
{
public virtual void GenericVirtual<T>()
{
}
public virtual void NormalVirtual()
{
}
}
private class B : A
{
public override void GenericVirtual<T>()
{
base.GenericVirtual<T>();
Console.WriteLine("Generic virtual: {0}", typeof(T).Name);
}
public override void NormalVirtual()
{
base.NormalVirtual();
Console.WriteLine("Normal virtual");
}
}
public static void Main(string[] args)
{
Test();
Console.ReadLine();
Test();
}
}
</code></pre>
<p>I breakpointed Program.Test with WinDbg:</p>
<blockquote>
<p>.loadby sos clr; !bpmd CSharpNewTest CSharpNewTest.Program.Test</p>
</blockquote>
<p>I then used <a href="http://www.stevestechspot.com/SOSEXV40NowAvailable.aspx">Sosex.dll</a>'s great <code>!muf</code> command to show me interleaved source, IL and ASM:</p>
<pre><code>0:000> !muf
CSharpNewTest.Program.Test(): void
b:A
002e0080 55 push ebp
002e0081 8bec mov ebp,esp
002e0083 56 push esi
var b = GetA();
IL_0000: call CSharpNewTest.Program::GetA()
IL_0005: stloc.0 (b)
>>>>>>>>002e0084 ff15c0371800 call dword ptr ds:[1837C0h]
002e008a 8bf0 mov esi,eax
b.GenericVirtual<string>();
IL_0006: ldloc.0 (b)
IL_0007: callvirt A::GenericVirtuallong
002e008c 6800391800 push 183900h
002e0091 8bce mov ecx,esi
002e0093 ba50381800 mov edx,183850h
002e0098 e877e49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e009d 8bce mov ecx,esi
002e009f ffd0 call eax
b.GenericVirtual<int>();
IL_000c: ldloc.0 (b)
IL_000d: callvirt A::GenericVirtuallong
002e00a1 6830391800 push 183930h
002e00a6 8bce mov ecx,esi
002e00a8 ba50381800 mov edx,183850h
002e00ad e862e49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e00b2 8bce mov ecx,esi
002e00b4 ffd0 call eax
b.GenericVirtual<StringBuilder>();
IL_0012: ldloc.0 (b)
IL_0013: callvirt A::GenericVirtuallong
002e00b6 6870391800 push 183970h
002e00bb 8bce mov ecx,esi
002e00bd ba50381800 mov edx,183850h
002e00c2 e84de49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e00c7 8bce mov ecx,esi
002e00c9 ffd0 call eax
b.GenericVirtual<int>();
IL_0018: ldloc.0 (b)
IL_0019: callvirt A::GenericVirtuallong
002e00cb 6830391800 push 183930h
002e00d0 8bce mov ecx,esi
002e00d2 ba50381800 mov edx,183850h
002e00d7 e838e49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e00dc 8bce mov ecx,esi
002e00de ffd0 call eax
b.GenericVirtual<StringBuilder>();
IL_001e: ldloc.0 (b)
IL_001f: callvirt A::GenericVirtuallong
002e00e0 6870391800 push 183970h
002e00e5 8bce mov ecx,esi
002e00e7 ba50381800 mov edx,183850h
002e00ec e823e49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e00f1 8bce mov ecx,esi
002e00f3 ffd0 call eax
b.GenericVirtual<string>();
IL_0024: ldloc.0 (b)
IL_0025: callvirt A::GenericVirtuallong
002e00f5 6800391800 push 183900h
002e00fa 8bce mov ecx,esi
002e00fc ba50381800 mov edx,183850h
002e0101 e80ee49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e0106 8bce mov ecx,esi
002e0108 ffd0 call eax
b.NormalVirtual();
IL_002a: ldloc.0 (b)
002e010a 8bce mov ecx,esi
002e010c 8b01 mov eax,dword ptr [ecx]
002e010e 8b4028 mov eax,dword ptr [eax+28h]
IL_002b: callvirt A::NormalVirtual()
002e0111 ff5014 call dword ptr [eax+14h]
}
IL_0030: ret
</code></pre>
<p>Of interest is the normal virtual call, which can be compared to the generic virtual calls:</p>
<pre><code>b.NormalVirtual();
IL_002a: ldloc.0 (b)
002e010a 8bce mov ecx,esi
002e010c 8b01 mov eax,dword ptr [ecx]
002e010e 8b4028 mov eax,dword ptr [eax+28h]
IL_002b: callvirt A::NormalVirtual()
002e0111 ff5014 call dword ptr [eax+14h]
</code></pre>
<p>Looks very standard. Let's take a look at the generic calls:</p>
<pre><code>b.GenericVirtual<string>();
IL_0024: ldloc.0 (b)
IL_0025: callvirt A::GenericVirtuallong
002e00f5 6800391800 push 183900h
002e00fa 8bce mov ecx,esi
002e00fc ba50381800 mov edx,183850h
002e0101 e80ee49b71 call clr!JIT_VirtualFunctionPointer (71c9e514)
002e0106 8bce mov ecx,esi
002e0108 ffd0 call eax
</code></pre>
<p>Ok, so the generic virtual calls are handled by loading our object <code>b</code> (which is in <code>esi</code>, being moved into <code>ecx</code>), and then calling into <code>clr!JIT_VirtualFunctionPointer</code>. Two constants are also pushed: <code>183850</code> in <code>edx</code>. We can conclude that this is probably the handle for the function <code>A.GenericVirtual<T></code>, as it does not change for any of the 6 call sites.
The other constant, <code>183900</code>, looks to be the type handle for the generic argument.
Indeed, <a href="http://www.microsoft.com/en-us/download/details.aspx?id=4917">SSCLI</a> confirms the suspicions:</p>
<p><code>HCIMPL3(CORINFO_MethodPtr, JIT_VirtualFunctionPointer, Object * objectUNSAFE,
CORINFO_CLASS_HANDLE classHnd,
CORINFO_METHOD_HANDLE methodHnd)</code></p>
<p>So, the lookup is basically delegated to <code>JIT_VirtualFunctionPointer</code>, which must prepare an address that can be called. Supposedly it will either JIT it and return a pointer to the JIT'ted code, or make a trampoline which, when called the first time, will JIT the function.</p>
<pre><code>0:000> uf clr!JIT_VirtualFunctionPointer
clr!JIT_VirtualFunctionPointer:
71c9e514 55 push ebp
71c9e515 8bec mov ebp,esp
71c9e517 83e4f8 and esp,0FFFFFFF8h
71c9e51a 83ec0c sub esp,0Ch
71c9e51d 53 push ebx
71c9e51e 56 push esi
71c9e51f 8bf2 mov esi,edx
71c9e521 8bd1 mov edx,ecx
71c9e523 57 push edi
71c9e524 89542414 mov dword ptr [esp+14h],edx
71c9e528 8b7d08 mov edi,dword ptr [ebp+8]
71c9e52b 85d2 test edx,edx
71c9e52d 745c je clr!JIT_VirtualFunctionPointer+0x70 (71c9e58b)
clr!JIT_VirtualFunctionPointer+0x1b:
71c9e52f 8b12 mov edx,dword ptr [edx]
71c9e531 89542410 mov dword ptr [esp+10h],edx
71c9e535 8bce mov ecx,esi
71c9e537 c1c105 rol ecx,5
71c9e53a 8bdf mov ebx,edi
71c9e53c 03ca add ecx,edx
71c9e53e c1cb05 ror ebx,5
71c9e541 03d9 add ebx,ecx
71c9e543 a180832872 mov eax,dword ptr [clr!g_pJitGenericHandleCache (72288380)]
71c9e548 8b4810 mov ecx,dword ptr [eax+10h]
71c9e54b 33d2 xor edx,edx
71c9e54d 8bc3 mov eax,ebx
71c9e54f f77104 div eax,dword ptr [ecx+4]
71c9e552 8b01 mov eax,dword ptr [ecx]
71c9e554 8b0490 mov eax,dword ptr [eax+edx*4]
71c9e557 85c0 test eax,eax
71c9e559 7430 je clr!JIT_VirtualFunctionPointer+0x70 (71c9e58b)
clr!JIT_VirtualFunctionPointer+0x47:
71c9e55b 8b4c2410 mov ecx,dword ptr [esp+10h]
clr!JIT_VirtualFunctionPointer+0x50:
71c9e55f 395804 cmp dword ptr [eax+4],ebx
71c9e562 7521 jne clr!JIT_VirtualFunctionPointer+0x6a (71c9e585)
clr!JIT_VirtualFunctionPointer+0x55:
71c9e564 39480c cmp dword ptr [eax+0Ch],ecx
71c9e567 751c jne clr!JIT_VirtualFunctionPointer+0x6a (71c9e585)
clr!JIT_VirtualFunctionPointer+0x5a:
71c9e569 397010 cmp dword ptr [eax+10h],esi
71c9e56c 7517 jne clr!JIT_VirtualFunctionPointer+0x6a (71c9e585)
clr!JIT_VirtualFunctionPointer+0x5f:
71c9e56e 397814 cmp dword ptr [eax+14h],edi
71c9e571 7512 jne clr!JIT_VirtualFunctionPointer+0x6a (71c9e585)
clr!JIT_VirtualFunctionPointer+0x64:
71c9e573 f6401801 test byte ptr [eax+18h],1
71c9e577 740c je clr!JIT_VirtualFunctionPointer+0x6a (71c9e585)
clr!JIT_VirtualFunctionPointer+0x85:
71c9e579 8b4008 mov eax,dword ptr [eax+8]
71c9e57c 5f pop edi
71c9e57d 5e pop esi
71c9e57e 5b pop ebx
71c9e57f 8be5 mov esp,ebp
71c9e581 5d pop ebp
71c9e582 c20400 ret 4
clr!JIT_VirtualFunctionPointer+0x6a:
71c9e585 8b00 mov eax,dword ptr [eax]
71c9e587 85c0 test eax,eax
71c9e589 75d4 jne clr!JIT_VirtualFunctionPointer+0x50 (71c9e55f)
clr!JIT_VirtualFunctionPointer+0x70:
71c9e58b 8b4c2414 mov ecx,dword ptr [esp+14h]
71c9e58f 57 push edi
71c9e590 8bd6 mov edx,esi
71c9e592 e8c4800400 call clr!JIT_VirtualFunctionPointer_Framed (71ce665b)
71c9e597 5f pop edi
71c9e598 5e pop esi
71c9e599 5b pop ebx
71c9e59a 8be5 mov esp,ebp
71c9e59c 5d pop ebp
71c9e59d c20400 ret 4
</code></pre>
<p>The implementation can be viewed in SSCLI, and it looks like it is still applicable:</p>
<pre><code>HCIMPL3(CORINFO_MethodPtr, JIT_VirtualFunctionPointer, Object * objectUNSAFE,
CORINFO_CLASS_HANDLE classHnd,
CORINFO_METHOD_HANDLE methodHnd)
{
CONTRACTL {
SO_TOLERANT;
THROWS;
DISABLED(GC_TRIGGERS); // currently disabled because of FORBIDGC in HCIMPL
} CONTRACTL_END;
OBJECTREF objRef = ObjectToOBJECTREF(objectUNSAFE);
if (objRef != NULL && g_pJitGenericHandleCache)
{
JitGenericHandleCacheKey key(objRef->GetMethodTable(), classHnd, methodHnd);
HashDatum res;
if (g_pJitGenericHandleCache->GetValueSpeculative(&key,&res))
return (CORINFO_GENERIC_HANDLE)res;
}
// Tailcall to the slow helper
ENDFORBIDGC();
return HCCALL3(JIT_VirtualFunctionPointer_Framed, OBJECTREFToObject(objRef), classHnd, methodHnd);
}
HCIMPLEND
</code></pre>
<p>So basically it checks a cache to see if we have seen this type/class combination before, and otherwise sends it off to <code>JIT_VirtualFunctionPointer_Framed</code> which calls into <code>MethodDesc::GetMultiCallableAddrOfVirtualizedCode</code> to get an address of it. The <code>MethodDesc</code> call is passed the object reference and generic type handle so it can look up what virtual function to dispatch to, and what version of the virtual function (ie. with what generic parameter).</p>
<p>All of this can be viewed in SSCLI if you want to go more in depth - it seems this has not changed with the 4.0 version of the CLR.</p>
<p>In short, the CLR does what you would expect; generate different call sites which carry information of the type that the virtual, generic function is called with. This is then passed to the CLR to do the dispatch. The complexity is that the CLR has to both keep track of the generic virtual function and the versions of it that it has JIT'ted.</p> |
3,548,345 | How do I close a UISearchDisplayController programmatically? | <p>I want to close my UISearchDisplayController when the user clicks the "Search" button since I'm loading new data from the web. How do I close the controller programatically? I already have the proper method called, but don't know how to do it.</p>
<p>I thought that the below would work, but I'm wrong.</p>
<pre><code>- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[self.searchDisplayController finalize];
}
</code></pre> | 3,548,945 | 3 | 0 | null | 2010-08-23 14:10:43.57 UTC | 5 | 2017-04-04 12:16:59.507 UTC | 2017-04-04 12:16:59.507 UTC | null | 1,033,581 | null | 345,282 | null | 1 | 30 | iphone|ios4|uisearchdisplaycontroller | 7,329 | <pre><code>[self.searchDisplayController setActive:NO animated:YES];
</code></pre>
<p>Enjoy.</p> |
22,856,931 | Converting java date to Sql timestamp | <p>I am trying to insert <code>java.util.Date</code> after converting it to java.sql.Timestamp and I am using the following snippet:</p>
<pre><code>java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
</code></pre>
<p>But this is giving me <code>sq</code> as <code>2014-04-04 13:30:17.533</code></p>
<p>Is there any way to get the output without milliseconds?</p> | 22,857,114 | 5 | 11 | null | 2014-04-04 08:01:42.747 UTC | 9 | 2019-01-03 09:58:53.277 UTC | 2014-04-04 08:25:34.43 UTC | null | 1,518,078 | null | 1,518,078 | null | 1 | 52 | java|sql|datetime|sqldatetime | 179,472 | <p>You can cut off the milliseconds using a <code>Calendar</code>:</p>
<pre><code>java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));
</code></pre>
<p>Output:</p>
<pre><code>2014-04-04 10:10:17.78
2014-04-04 10:10:17.0
</code></pre> |
11,059,910 | Skipping elements in a List Python | <p>I'm new to programming and I'm trying to do the codingbat.com problems to start. I came across this problem:</p>
<p>Given an array calculate the sum except when there is a 13 in the array. If there is a 13 in the array, skip the 13 and the number immediately following it. For example [1,2,13,5,1] should yield 4 (since the 13 and the 5s are skipped).</p>
<p>This is what I have so far. My problem is that I don't know what to do when there are multiple 13s...And I would like to learn coding efficiently. Can you guys help? (I'm using python 3.2) Thanks!</p>
<pre><code>def pos(nums):
for i in nums:
if i == 13:
return nums.index(13)
return False
def sum13(lis):
if pos(lis)!= False:
return sum(lis[:pos(lis)])+sum(lis[pos(lis)+1:])
else:
return sum(lis)
</code></pre> | 11,059,977 | 7 | 5 | null | 2012-06-16 00:58:17.56 UTC | 1 | 2017-07-29 10:43:11.757 UTC | 2012-06-16 01:13:03.98 UTC | null | 1,219,006 | null | 1,455,043 | null | 1 | 11 | python | 78,122 | <p>One tricky thing to notice is something like this: [1, 13, 13, 2, 3]</p>
<p>You need to skip <code>2</code> too</p>
<pre><code>def getSum(l):
sum = 0
skip = False
for i in l:
if i == 13:
skip = True
continue
if skip:
skip = False
continue
sum += i
return sum
</code></pre>
<p><strong>Explanation</strong>:</p>
<p>You go through the items in the list one by one</p>
<p>Each time you </p>
<ul>
<li>First check if it's 13, if it is, then you mark <code>skip</code> as <code>True</code>, so that you can also skip next item.</li>
<li>Second, you check if <code>skip</code> is <code>True</code>, if it is, which means it's a item right after 13, so you need to skip this one too, and you also need to set <code>skip</code> back to <code>False</code> so that you don't skip next item.</li>
<li>Finally, if it's not either case above, you add the value up to <code>sum</code></li>
</ul> |
11,022,675 | Rotate histogram in R or overlay a density in a barplot | <p>I would like to rotate a histogram in R, plotted by hist(). The question is not new, and in several forums I have found that it is not possible. However, all these answers date back to 2010 or even later.</p>
<p>Has anyone found a solution meanwhile?</p>
<p>One way to get around the problem is to plot the histogram via barplot() that offers the option "horiz=TRUE". The plot works fine but I fail to overlay a density in the barplots. The problem probably lies in the x-axis since in the vertical plot, the density is centered in the first bin, while in the horizontal plot the density curve is messed up.</p>
<p>Any help is very much appreciated!</p>
<p>Thanks,</p>
<p>Niels</p>
<p>Code:</p>
<pre><code>require(MASS)
Sigma <- matrix(c(2.25, 0.8, 0.8, 1), 2, 2)
mvnorm <- mvrnorm(1000, c(0,0), Sigma)
scatterHist.Norm <- function(x,y) {
zones <- matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
layout(zones, widths=c(2/3,1/3), heights=c(1/3,2/3))
xrange <- range(x) ; yrange <- range(y)
par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="", cex=0.5)
xhist <- hist(x, plot=FALSE, breaks=seq(from=min(x), to=max(x), length.out=20))
yhist <- hist(y, plot=FALSE, breaks=seq(from=min(y), to=max(y), length.out=20))
top <- max(c(xhist$counts, yhist$counts))
par(mar=c(0,3,1,1))
plot(xhist, axes=FALSE, ylim=c(0,top), main="", col="grey")
x.xfit <- seq(min(x),max(x),length.out=40)
x.yfit <- dnorm(x.xfit,mean=mean(x),sd=sd(x))
x.yfit <- x.yfit*diff(xhist$mids[1:2])*length(x)
lines(x.xfit, x.yfit, col="red")
par(mar=c(0,3,1,1))
plot(yhist, axes=FALSE, ylim=c(0,top), main="", col="grey", horiz=TRUE)
y.xfit <- seq(min(x),max(x),length.out=40)
y.yfit <- dnorm(y.xfit,mean=mean(x),sd=sd(x))
y.yfit <- y.yfit*diff(yhist$mids[1:2])*length(x)
lines(y.xfit, y.yfit, col="red")
}
scatterHist.Norm(mvnorm[,1], mvnorm[,2])
scatterBar.Norm <- function(x,y) {
zones <- matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
layout(zones, widths=c(2/3,1/3), heights=c(1/3,2/3))
xrange <- range(x) ; yrange <- range(y)
par(mar=c(3,3,1,1))
plot(x, y, xlim=xrange, ylim=yrange, xlab="", ylab="", cex=0.5)
xhist <- hist(x, plot=FALSE, breaks=seq(from=min(x), to=max(x), length.out=20))
yhist <- hist(y, plot=FALSE, breaks=seq(from=min(y), to=max(y), length.out=20))
top <- max(c(xhist$counts, yhist$counts))
par(mar=c(0,3,1,1))
barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0)
x.xfit <- seq(min(x),max(x),length.out=40)
x.yfit <- dnorm(x.xfit,mean=mean(x),sd=sd(x))
x.yfit <- x.yfit*diff(xhist$mids[1:2])*length(x)
lines(x.xfit, x.yfit, col="red")
par(mar=c(3,0,1,1))
barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE)
y.xfit <- seq(min(x),max(x),length.out=40)
y.yfit <- dnorm(y.xfit,mean=mean(x),sd=sd(x))
y.yfit <- y.yfit*diff(yhist$mids[1:2])*length(x)
lines(y.xfit, y.yfit, col="red")
}
scatterBar.Norm(mvnorm[,1], mvnorm[,2])
</code></pre>
#
<p>Source of scatter plot with marginal histograms (click first link after "adapted from..."):</p>
<p><a href="http://r.789695.n4.nabble.com/newbie-scatterplot-with-marginal-histograms-done-and-axes-labels-td872589.html">http://r.789695.n4.nabble.com/newbie-scatterplot-with-marginal-histograms-done-and-axes-labels-td872589.html</a></p>
<p>Source of density in a scatter plot:</p>
<p><a href="http://www.statmethods.net/graphs/density.html">http://www.statmethods.net/graphs/density.html</a></p> | 11,114,617 | 5 | 0 | null | 2012-06-13 20:16:39.807 UTC | 11 | 2015-04-22 17:39:15.433 UTC | null | null | null | null | 1,454,600 | null | 1 | 12 | r | 16,665 | <pre><code>scatterBarNorm <- function(x, dcol="blue", lhist=20, num.dnorm=5*lhist, ...){
## check input
stopifnot(ncol(x)==2)
## set up layout and graphical parameters
layMat <- matrix(c(2,0,1,3), ncol=2, byrow=TRUE)
layout(layMat, widths=c(5/7, 2/7), heights=c(2/7, 5/7))
ospc <- 0.5 # outer space
pext <- 4 # par extension down and to the left
bspc <- 1 # space between scatter plot and bar plots
par. <- par(mar=c(pext, pext, bspc, bspc),
oma=rep(ospc, 4)) # plot parameters
## scatter plot
plot(x, xlim=range(x[,1]), ylim=range(x[,2]), ...)
## 3) determine barplot and height parameter
## histogram (for barplot-ting the density)
xhist <- hist(x[,1], plot=FALSE, breaks=seq(from=min(x[,1]), to=max(x[,1]),
length.out=lhist))
yhist <- hist(x[,2], plot=FALSE, breaks=seq(from=min(x[,2]), to=max(x[,2]),
length.out=lhist)) # note: this uses probability=TRUE
## determine the plot range and all the things needed for the barplots and lines
xx <- seq(min(x[,1]), max(x[,1]), length.out=num.dnorm) # evaluation points for the overlaid density
xy <- dnorm(xx, mean=mean(x[,1]), sd=sd(x[,1])) # density points
yx <- seq(min(x[,2]), max(x[,2]), length.out=num.dnorm)
yy <- dnorm(yx, mean=mean(x[,2]), sd=sd(x[,2]))
## barplot and line for x (top)
par(mar=c(0, pext, 0, 0))
barplot(xhist$density, axes=FALSE, ylim=c(0, max(xhist$density, xy)),
space=0) # barplot
lines(seq(from=0, to=lhist-1, length.out=num.dnorm), xy, col=dcol) # line
## barplot and line for y (right)
par(mar=c(pext, 0, 0, 0))
barplot(yhist$density, axes=FALSE, xlim=c(0, max(yhist$density, yy)),
space=0, horiz=TRUE) # barplot
lines(yy, seq(from=0, to=lhist-1, length.out=num.dnorm), col=dcol) # line
## restore parameters
par(par.)
}
require(mvtnorm)
X <- rmvnorm(1000, c(0,0), matrix(c(1, 0.8, 0.8, 1), 2, 2))
scatterBarNorm(X, xlab=expression(italic(X[1])), ylab=expression(italic(X[2])))
</code></pre>
<p><img src="https://i.stack.imgur.com/cnkHP.png" alt="enter image description here"></p> |
11,022,934 | Getting "java.net.ProtocolException: Server redirected too many times" Error | <p>I'm making a simple URL request with code like this:</p>
<pre><code>URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
</code></pre>
<p>But on that last line, I'm getting the "redirected too many times error". If my "webpage" var is, say, google.com then it works fine, but when I try to use my servlet's URL then it fails. It seems I can adjust the number of times it follows the redirects (default is 20) with this:</p>
<pre><code>System.setProperty("http.maxRedirects", "100");
</code></pre>
<p>But when I crank it up to, say, 100 it definitely takes longer to throw the error so I know it is trying. However, the URL to my servlet works fine in (any) browser and using the "persist" option in firebug it seems to only be redirecting once.</p>
<p>A bit more info on my servlet ... it is running in tomcat and fronted by apache using 'mod-proxy-ajp'. Also of note, it is using form authentication so any URL you enter should redirect you to the login page. As I said, this works correctly in all browsers, but for some reason the redirect isn't working with the URLConnection in Java 6.</p>
<p>Thanks for reading ... ideas?</p> | 11,036,882 | 4 | 5 | null | 2012-06-13 20:38:29.693 UTC | 7 | 2019-08-29 12:07:47.313 UTC | null | null | null | null | 499,689 | null | 1 | 39 | java|url|servlets|redirect|urlconnection | 81,928 | <p>It's apparently redirecting in an infinite loop because you don't maintain the user session. The session is usually backed by a cookie. You need to create a <code>CookieManager</code> before you use <code>URLConnection</code>.</p>
<pre><code>// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests">Using java.net.URLConnection to fire and handle HTTP requests</a></li>
</ul> |
12,822,301 | Resetting form in VBA | <p>I have a VBA form with a variety of selection options including drop downs, text fields, checkboxes and radios. </p>
<p>I just wanted to know about the best way to clear all these fields with a button press. A friend of mine has tried to help by emailing me the code below but unfortunately it doesn't work, I have checked the variable names. </p>
<p>Any advice on how I can improve it? </p>
<p>Thanks in advance.</p>
<pre><code>Private Sub btnReset_Click()
Unload Me
UserForm.Show
End Sub
</code></pre>
<p>Here is the other code for the userform.</p>
<pre><code>Dim DeptCode 'Holds department code
Private Sub UserForm_Initialize()
Dim c_deptCode As Range
Dim c_deptName As Range
Dim deptCodes As Variant
Dim deptNames As Variant
Dim ws_dept As Worksheet
Set ws_dept = Worksheets("lookupDept")
' Assign each range to an array containing the values
deptCodes = Choose(1, ws_dept.Range("deptCode"))
deptNames = Choose(1, ws_dept.Range("deptName"))
For i = 1 To ws_dept.Range("deptCode").Rows.Count
' Create the combined name (code + space + name)
CombinedName = deptCodes(i, 1) & " - " & deptNames(i, 1)
cbo_deptCode.AddItem CombinedName
Next i
End Sub
</code></pre> | 12,824,465 | 5 | 0 | null | 2012-10-10 14:53:07.537 UTC | 1 | 2018-02-13 19:43:11.06 UTC | 2012-10-10 15:12:38.267 UTC | null | 1,316,573 | null | 436,493 | null | 1 | 8 | vba | 97,682 | <p>I think when it hits the Unload Me line, code execution stops and that's why it's not working for you. Here's a generic event procedure to reset all (most) of the controls on the form.</p>
<pre><code>Private Sub cmdReset_Click()
Dim ctl As MSForms.Control
For Each ctl In Me.Controls
Select Case TypeName(ctl)
Case "TextBox"
ctl.Text = ""
Case "CheckBox", "OptionButton", "ToggleButton"
ctl.Value = False
Case "ComboBox", "ListBox"
ctl.ListIndex = -1
End Select
Next ctl
End Sub
</code></pre>
<p>It doesn't repopulate the ComboBoxes and ListBoxes, just clears the selection, which is what I assume you want.</p> |
13,127,177 | If my interface must return Task what is the best way to have a no-operation implementation? | <p>In the code below, due to the interface, the class <code>LazyBar</code> must return a task from its method (and for argument's sake can't be changed). If <code>LazyBar</code>s implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?</p>
<p>I have gone with <code>Task.Delay(0)</code> below, however I would like to know if this has any performance side-effects if the function is called a <em>lot</em> (for argument's sake, say hundreds of times a second):</p>
<ul>
<li>Does this syntactic sugar un-wind to something big?</li>
<li>Does it start clogging up my application's thread pool?</li>
<li>Is the compiler cleaver enough to deal with <code>Delay(0)</code> differently?</li>
<li>Would <code>return Task.Run(() => { });</code> be any different?</li>
</ul>
<p>Is there a better way?</p>
<pre><code>using System.Threading.Tasks;
namespace MyAsyncTest
{
internal interface IFooFace
{
Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
}
/// <summary>
/// An implementation, that unlike most cases, will not have a long-running
/// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
/// </summary>
internal class LazyBar : IFooFace
{
#region IFooFace Members
public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
{
// First, do something really quick
var x = 1;
// Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
// Is it a real no-op, or if I call this a lot, will it adversely affect the
// underlying thread-pool? Better way?
return Task.Delay(0);
// Any different?
// return Task.Run(() => { });
// If my task returned something, I would do:
// return Task.FromResult<int>(12345);
}
#endregion
}
internal class Program
{
private static void Main(string[] args)
{
Test();
}
private static async void Test()
{
IFooFace foo = FactoryCreate();
await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
return;
}
private static IFooFace FactoryCreate()
{
return new LazyBar();
}
}
}
</code></pre> | 13,127,229 | 9 | 2 | null | 2012-10-29 18:01:21.5 UTC | 61 | 2022-05-05 22:31:33.253 UTC | 2022-05-05 22:31:33.253 UTC | null | 426,273 | null | 426,273 | null | 1 | 535 | c#|.net|task-parallel-library|async-await|threadpool | 235,729 | <p>Today, I would recommend using <a href="https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.completedtask.aspx" rel="noreferrer">Task.CompletedTask</a> to accomplish this.</p>
<hr />
<p>Pre .net 4.6:</p>
<p>Using <code>Task.FromResult(0)</code> or <code>Task.FromResult<object>(null)</code> will incur less overhead than creating a <code>Task</code> with a no-op expression. When creating a <code>Task</code> with a result pre-determined, there is no scheduling overhead involved.</p> |
12,703,535 | Scala sbt console - code changes not reflected in sbt console | <p>I use scala sbt console to test my methods. (commands : <strong>sbt</strong> then <strong>console</strong>) But the code changes done in eclipse or other external editor, are not getting reflected in the sbt console. </p>
<p>Every time, I have to quit the console (using Crt + D) and again start it using <strong>console</strong> command to see the changes. </p>
<p>Any one facing this problem?
Is there any ways to reload the code from console? </p>
<p>I am using Ubuntu 64-Bit, </p> | 12,703,977 | 2 | 0 | null | 2012-10-03 07:11:54.343 UTC | 10 | 2015-08-01 01:04:01.553 UTC | null | null | null | null | 980,449 | null | 1 | 43 | scala|sbt | 12,736 | <p>Not without using something like JRebel, mostly because class definitions could break in such a way as to make instances already loaded unusable. The only suggestion I have is to run the console with <strong>~console</strong> so that if changes have been made they will be recompiled and the console re-entered.</p>
<p>Also if you're regularly running a set of commands the initialCommands sbt setting configures commands to be run immediately after starting the console.</p> |
16,773,642 | Pull git submodules after cloning project from GitHub | <p>I have a project that has specified submodules in it. Everything works well on the dev machine. I have commited <code>.gitmodules</code> file and pulled on the production. However it does not pulled submodules.</p>
<p>If I go into submodule directories and call <code>git pull</code>, nothing happens.</p>
<p>What is the proper way to pull those submodules in the new project ?</p> | 16,773,779 | 4 | 0 | null | 2013-05-27 12:52:05.387 UTC | 37 | 2022-04-29 09:50:49.897 UTC | null | null | null | null | 223,386 | null | 1 | 194 | git|git-submodules | 97,871 | <p>From the root of the repo just run:</p>
<pre><code>git submodule update --init
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.