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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,208,361 | Why does my view move when I set its frame after changing its anchorPoint? | <p>I made two instances of <code>UILabel</code> and added them to my <code>ViewController</code>'s view.
And then I changed the <code>anchorPoint</code> of each from 0.5 to 1.0 (x and y).</p>
<p>Next, I reset the frame of <code>uiLabel2</code> to its frame I created it with: (100,100,100,20).</p>
<p>When I run the app, <code>uiLabel1</code> and <code>uiLabel2</code> show at different positions. Why?</p>
<pre><code>UILabel *uiLabel1 = [[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)] autorelease];
uiLabel1.text = @"UILabel1";
uiLabel1.layer.anchorPoint = CGPointMake(1, 1);
UILabel *uiLabel2 = [[[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 20)] autorelease];
uiLabel2.text = @"UILabel2";
uiLabel2.layer.anchorPoint = CGPointMake(1, 1);
uiLabel2.frame = CGRectMake(100, 100, 100, 20);
[self.view addSubview:uiLabel1];
[self.view addSubview:uiLabel2];
</code></pre>
<p><img src="https://i.stack.imgur.com/1kwSD.png" alt="enter image description here"></p> | 12,208,587 | 2 | 0 | null | 2012-08-31 03:04:52.663 UTC | 9 | 2016-02-23 22:01:38.133 UTC | 2012-08-31 03:45:45.523 UTC | null | 77,567 | null | 868,754 | null | 1 | 10 | objective-c|ios|uikit | 5,985 | <p>A <code>CALayer</code> has four properties that determine where it appears in its superlayer:</p>
<ul>
<li><code>position</code> (which is the same as the view's <code>center</code> property)</li>
<li><code>bounds</code> (actually only the <code>size</code> part of <code>bounds</code>)</li>
<li><code>anchorPoint</code></li>
<li><code>transform</code></li>
</ul>
<p>You will notice that <code>frame</code> is <strong>not</strong> one of those properties. The <code>frame</code> property is actually derived from those properties. When you set the <code>frame</code> property, the layer actually changes its <code>center</code> and <code>bounds.size</code> based on the frame you provide and the layer's existing <code>anchorPoint</code>.</p>
<p>You create the first layer (by creating the first <code>UILabel</code>, which is a subclass of <code>UIView</code>, and every <code>UIView</code> has a layer), giving it a frame of 100,100,100,20. The layer has a default anchor point of 0.5,0.5. So it computes its bounds as 0,0,100,20 and its position as 150,110. It looks like this:</p>
<p><img src="https://i.stack.imgur.com/E3KSK.png" alt="anchor at center"></p>
<p>Then you change its anchor point to 1,1. Since you don't change the layer's position or bounds directly, and you don't change them indirectly by setting its frame, the layer moves so that its new anchor point is at its (unchanged) position in its superlayer:</p>
<p><img src="https://i.stack.imgur.com/4izAN.png" alt="anchor at corner"></p>
<p>If you ask for the layer's (or view's) frame now, you will get 50,90,100,20.</p>
<p>When you create the second layer (for the second <code>UILabel</code>), after changing its anchor point, you set its frame. So the layer computes a new position and bounds based on the frame you provide and its existing anchor point:</p>
<p><img src="https://i.stack.imgur.com/V4Hjh.png" alt="anchor at corner with reset frame"></p>
<p>If you ask the layer (or view) for its frame now, you will get the frame you set, 100,100,100,20. But if you ask for its position (or the view's center), you will get 200,120.</p> |
12,389,158 | Check if R is running in RStudio | <p>I am looking for a way to test if R is being run from RStudio. For some reason I could find the answer on google yesterday but not today, but I think it had to do with testing if a certain system variable was set.</p> | 12,390,013 | 10 | 0 | null | 2012-09-12 13:20:32.18 UTC | 6 | 2022-05-11 17:19:31.58 UTC | null | null | null | null | 567,015 | null | 1 | 40 | r|rstudio | 25,305 | <p>There is no "running inside RStudio". RStudio is merely an IDE layer that wraps around R; at the end of the day it just launches the normal R executable you need to have on your $PATH anyway to operate RStudio.</p>
<p>As a proxy, and as R Studio You could test available.packages() for the 'manipulate' package though, or as a shorter version see if RStudio added itself to the <code>.libPaths()</code> content:</p>
<pre><code>R> any(grepl("RStudio", .libPaths()))
[1] TRUE
R>
R>
</code></pre>
<p><em>Edit in May 2020 or eight years later</em> The question does come up, and one can query a variety of things from within. Here is an example from the terminal of RStudio:</p>
<pre><code>$ env | grep -i rstudio | sort
GIO_LAUNCHED_DESKTOP_FILE=/usr/share/applications/rstudio.desktop
PATH=[...redacted...]
RMARKDOWN_MATHJAX_PATH=/usr/lib/rstudio/resources/mathjax-27
RS_RPOSTBACK_PATH=/usr/lib/rstudio/bin/rpostback
RSTUDIO=1
RSTUDIO_CONSOLE_COLOR=256
RSTUDIO_CONSOLE_WIDTH=111
RSTUDIO_PANDOC=/usr/lib/rstudio/bin/pandoc
RSTUDIO_PROGRAM_MODE=desktop
RSTUDIO_PROJ_NAME=chshli
RSTUDIO_SESSION_ID=9C62D3D4
RSTUDIO_SESSION_PORT=13494
RSTUDIO_TERM=2BD6BB88
RSTUDIO_USER_IDENTITY=edd
RSTUDIO_WINUTILS=bin/winutils
$
</code></pre>
<p>Similarly, from within the R session:</p>
<pre><code>R> se <- Sys.getenv()
R> se[grepl("rstudio",se,ignore.case=TRUE)]
GIO_LAUNCHED_DESKTOP_FILE /usr/share/applications/rstudio.desktop
PATH [...also redacted...]
RMARKDOWN_MATHJAX_PATH /usr/lib/rstudio/resources/mathjax-27
RS_RPOSTBACK_PATH /usr/lib/rstudio/bin/rpostback
RSTUDIO_PANDOC /usr/lib/rstudio/bin/pandoc
R>
</code></pre>
<p><em>Edit in Aug 2021 or nine years later</em> As all the answers listed here in the different answer may still be too much for people, you can also install package <code>rstudioapi</code> from CRAN and then ask it via <code>rstudioapi::isAvailable()</code> which comes back <code>TRUE</code> for me inside RStudio and <code>FALSE</code> in ESS / standard R.</p> |
12,166,476 | android canvas drawText set font size from width? | <p>I want to draw text on <code>canvas</code> of certain width using <code>.drawtext</code></p>
<p>For example, the width of the text should always be <code>400px</code> no matter what the input text is. </p>
<p>If input text is longer it will decrease the font size, if input text is shorter it will increase the font size accordingly.</p> | 21,895,626 | 3 | 0 | null | 2012-08-28 19:46:49.64 UTC | 29 | 2018-05-07 14:32:38.207 UTC | 2014-01-29 06:01:12.207 UTC | null | 881,229 | null | 1,037,988 | null | 1 | 63 | java|android|android-canvas | 80,213 | <p>Here's a much more efficient method:</p>
<pre><code>/**
* Sets the text size for a Paint object so a given string of text will be a
* given width.
*
* @param paint
* the Paint to set the text size for
* @param desiredWidth
* the desired width
* @param text
* the text that should be that width
*/
private static void setTextSizeForWidth(Paint paint, float desiredWidth,
String text) {
// Pick a reasonably large value for the test. Larger values produce
// more accurate results, but may cause problems with hardware
// acceleration. But there are workarounds for that, too; refer to
// http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
final float testTextSize = 48f;
// Get the bounds of the text, using our testTextSize.
paint.setTextSize(testTextSize);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
// Calculate the desired size as a proportion of our testTextSize.
float desiredTextSize = testTextSize * desiredWidth / bounds.width();
// Set the paint for that size.
paint.setTextSize(desiredTextSize);
}
</code></pre>
<p>Then, all you need to do is <code>setTextSizeForWidth(paint, 400, str);</code> (400 being the example width in the question).</p>
<p>For even greater efficiency, you can make the <code>Rect</code> a static class member, saving it from being instantiated each time. However, this may introduce concurrency issues, and would arguably hinder code clarity.</p> |
3,219,672 | Memory efficient image resize in Android | <p>I am trying to reduce the size of images retrieved form the camera (so ~5-8 mega pixels) down to one a a few smaller sizes (the largest being 1024x768). I Tried the following code but I consistently get an <code>OutOfMemoryError</code>.</p>
<pre><code>Bitmap image = BitmapFactory.decodeStream(this.image, null, opt);
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
// Constrain to given size but keep aspect ratio
float scaleFactor = Math.min(((float) width) / imgWidth, ((float) height) / imgHeight);
Matrix scale = new Matrix();
scale.postScale(scaleFactor, scaleFactor);
final Bitmap scaledImage = Bitmap.createBitmap(image, 0, 0, imgWidth, imgHeight, scale, false);
image.recycle();
</code></pre>
<p>It looks like the OOM happens during the <code>createBitmap</code>. Is there a more memory efficient way to do this? Perhaps something that doesn't require me to load the entire original into memory?</p> | 3,220,794 | 3 | 0 | null | 2010-07-10 15:00:36.497 UTC | 14 | 2015-04-20 23:26:44.557 UTC | null | null | null | null | 111,644 | null | 1 | 14 | android|bitmap|image-manipulation | 42,714 | <p>When you decode the bitmap with the BitmapFactory, pass in a BitmapFactory.Options object and specify inSampleSize. This is the best way to save memory when decoding an image.</p>
<p>Here's a sample code <a href="https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966">Strange out of memory issue while loading an image to a Bitmap object</a></p> |
3,250,503 | PHPUnit, mocked interfaces, and instanceof | <p>Sometimes in my code, I'll check to see if a particular object implements an interface:</p>
<pre><code>if ($instance instanceof Interface) {};
</code></pre>
<p>However, creating mocks of said interface in PHPUnit, I can't seem to pass that test.</p>
<pre><code> // class name is Mock_Interface_431469d7, does not pass above check
$instance = $this->getMock('Interface');
</code></pre>
<p>I understand that having a class named Interface is different from a class implementing Interface, but I'm not sure how to get deal with this.</p>
<p>Am I forced to mock a concrete class that implements Interface? Wouldn't that defeat the purpose of using an interface for portability?</p>
<p>Thanks</p> | 3,254,990 | 3 | 0 | null | 2010-07-14 21:01:40.103 UTC | 4 | 2020-01-24 12:04:21.953 UTC | null | null | null | null | 4,636 | null | 1 | 39 | php|unit-testing|mocking|phpunit | 30,519 | <p>This works for me:</p>
<pre><code>$mock = $this->getMock('TestInterface');
$this->assertTrue($mock instanceof TestInterface);
</code></pre>
<p>Maybe it's a typo or maybe $instance isn't what you think it is?</p> |
22,931,032 | Vim: word vs WORD | <p>I'm learning Vim and can't wrap my head around the difference between <code>word</code> and <code>WORD</code>.</p>
<p>I got the following from the Vim manual.</p>
<blockquote>
<p>A word consists of a sequence of letters, digits and underscores, or a
sequence of other non-blank characters, separated with white space
(spaces, tabs, ). This can be changed with the 'iskeyword'
option. An empty line is also considered to be a word.</p>
<p>A WORD consists of a sequence of non-blank characters, separated with
white space. An empty line is also considered to be a WORD.</p>
</blockquote>
<p>I feel <code>word</code> and <code>WORD</code> are just the same thing. They are both a sequence of non-blank chars separated with white spaces. An empty line can be considered as both <code>word</code> and <code>WORD</code>.</p>
<p>Question:<br>
What's the difference between them?<br>
And why/when would someone use <code>WORD</code> over <code>word</code>?</p>
<p>I've already done Google and SO search, but their search-engine interpret <code>WORD</code> as just <code>word</code> so it's like I'm searching for <code>Vim word vs word</code> and of course won't find anything useful.</p> | 22,931,259 | 6 | 5 | null | 2014-04-08 08:01:33.78 UTC | 32 | 2020-11-10 16:15:49.013 UTC | null | null | null | null | 1,780,148 | null | 1 | 94 | vim | 16,086 | <ul>
<li>A WORD is always delimited by <em>whitespace</em>.</li>
<li>A word is delimited by <em>non-keyword</em> characters, which are configurable. Whitespace characters aren't keywords, and usually other characters (like <code>()[],-</code>) aren't, neither. Therefore, a word usually is smaller than a WORD; the word-navigation is more fine-grained.</li>
</ul>
<h3>Example</h3>
<pre><code>This "stuff" is not-so difficult!
wwww wwwww ww www ww wwwwwwwww " (key)words, delimiters are non-keywords: "-! and whitespace
WWWW WWWWWWW WW WWWWWW WWWWWWWWWW " WORDS, delimiters are whitespace only
</code></pre> |
11,093,654 | How to identify square or rectangle with variable lengths and width by using javacv? | <p>I'm developing project using java to identify components using opencv package but I'm new to javacv and I just want to know how to identify rectangles in a particular source image please can some experience person give some basic guide line to archive this task. I try to use template matching on here but it can identify exact size rectangle only. But In my case I need to identify variable length rectangle ?</p>
<pre><code>import java.util.Arrays;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
public class TestingTemplate {
public static void main(String[] args) {
//Original Image
IplImage src = cvLoadImage("src\\lena.jpg",0);
//Template Image
IplImage tmp = cvLoadImage("src\\those_eyes.jpg",0);
//The Correlation Image Result
IplImage result = cvCreateImage(cvSize(src.width()-tmp.width()+1, src.height()-tmp.height()+1), IPL_DEPTH_32F, 1);
//Init our new Image
cvZero(result);
cvMatchTemplate(src, tmp, result, CV_TM_CCORR_NORMED);
double[] min_val = new double[2];
double[] max_val = new double[2];
//Where are located our max and min correlation points
CvPoint minLoc = new CvPoint();
CvPoint maxLoc = new CvPoint();
cvMinMaxLoc(result, min_val, max_val, minLoc, maxLoc, null); //the las null it's for
optional mask mat()
System.out.println(Arrays.toString(min_val)); //Min Score
System.out.println(Arrays.toString(max_val)); //Max Score
CvPoint point = new CvPoint();
point.x(maxLoc.x()+tmp.width());
point.y(maxLoc.y()+tmp.height());
cvRectangle(src, maxLoc, point, CvScalar.WHITE, 2, 8, 0); //Draw the rectangule result in original img.
cvShowImage("Lena Image", src);
cvWaitKey(0);
//Release
cvReleaseImage(src);
cvReleaseImage(tmp);
cvReleaseImage(result);
}
}
</code></pre>
<p>Please can some one help to accomplish this </p> | 11,104,079 | 1 | 3 | null | 2012-06-19 02:33:26.963 UTC | 9 | 2013-05-20 14:50:10.533 UTC | 2012-06-19 12:21:52.697 UTC | null | 817,452 | user1465195 | null | null | 1 | 9 | java|image-processing|opencv|javacv | 14,439 | <p>(So it is fixed as square.)</p>
<p>For square detection, OpenCV comes with some samples for this. Codes are in C++, C, Python. Hope you can port this to JavaCV.</p>
<p><a href="https://github.com/Itseez/opencv/blob/master/samples/cpp/squares.cpp" rel="noreferrer">C++ code</a> , <a href="https://github.com/Itseez/opencv/blob/master/samples/python2/squares.py" rel="noreferrer">Python Code</a>.</p>
<p>I will just illustrate how it works:</p>
<p>1 - First you <strong>split the image</strong> to R,G,B planes. </p>
<p>2 - Then for each plane perform <strong>edge detection</strong>, and in addition to that, <strong>threshold</strong> for different values like 50, 100, .... etc. </p>
<p>3 - And in all these binary images, <strong>find contours</strong> ( remember it is processing a lot of images, so may be a little bit slow, if you don't want, you can remove some threshold values).</p>
<p>4 - After finding contours, remove some small unwanted noises by <strong>filtering according to area</strong>. </p>
<p>5 - Then, <strong>approximate the contour</strong>. (<a href="http://opencvpython.blogspot.in/2012/06/contours-2-brotherhood.html" rel="noreferrer">More about contour approximation</a>). </p>
<p>6 - For a rectangle, it will give you the four corners. For others, corresponding corners will be given.</p>
<p>So filter these contours with respect to number of elements in approximated contour that should be four, which is same as number of corners. <strong>First property of rectangle.</strong> </p>
<p>7 - Next, there may be some shapes with four corners but not rectangles. So we take <strong>second property of rectangles, ie all inner angles are 90</strong>. So we find the angle at all the corners using the relation below :</p>
<p><img src="https://i.stack.imgur.com/gxUXv.png" alt="enter image description here"></p>
<p>And if cos (theta) < 0.1, ie theta > 84 degree, that is a rectangle.</p>
<p>8 - Then what about the square? <strong>Use its property, that all the sides are equal.</strong></p>
<p>You can find the distance between two points by the relation as shown above. Check if they all are equal, then that rectangle is a square.</p>
<p>This is how the code works.</p>
<p>Below is the output I got applying above mentioned code on an image :</p>
<p><img src="https://i.stack.imgur.com/flaby.png" alt="enter image description here"></p>
<p><strong>EDIT :</strong></p>
<p>It has been asked how to remove the rectangle detected at the border. It is because, opencv finds white objects in black background, so is border. Just inverting the image using cv2.bitwise_not() function will solve the problem. we get the result as below:</p>
<p><img src="https://i.stack.imgur.com/bi6xZ.png" alt="enter image description here"></p>
<p>You can find more information about contour here : <a href="http://opencvpython.blogspot.com/2012/06/hi-this-article-is-tutorial-which-try.html" rel="noreferrer">Contours - 1 : Getting Started</a></p> |
11,219,931 | How to force div element to keep its contents inside container | <p>I am making a css menu. For this I am using a <code>ul</code>. When I make <code>li</code> float left then all <code>li</code>'s gets outside of the ul. I mean the height of <code>ul</code> become zero. How can I make <code>li</code> display inside <code>ul</code> after giving float left. </p>
<p>One way to do is to make a <code>div</code> tag with some common class and add clear: both to it in css but I do not want this.</p>
<p>How can I solve this?</p> | 11,220,010 | 4 | 0 | null | 2012-06-27 05:28:25.433 UTC | 2 | 2019-08-24 13:27:25.15 UTC | 2019-08-24 13:27:25.15 UTC | null | 1,640,892 | null | 1,136,062 | null | 1 | 19 | html|css | 86,616 | <p>Just add <code>overflow: auto;</code> to the <code><ul></code>. That will make it so that the text doesn't leak outside of the UL.</p>
<p>See: <a href="http://jsfiddle.net/6cKAG/">http://jsfiddle.net/6cKAG/</a></p>
<hr>
<p>However, depending on what you're doing, it might be easier to just make the <code><li></code> <code>display: inline;</code>. It totally depends on what you're doing!</p>
<p>See: <a href="http://jsfiddle.net/k7Wqx/">http://jsfiddle.net/k7Wqx/</a></p> |
11,081,504 | How can you return everything after last slash(/) in a Ruby string | <p>I have a string would like everything after the last <code>/</code> to be returned. </p>
<p>E.g. for <code>https://www.example.org/hackerbob</code>, it should return <code>"hackerbob"</code>.</p> | 11,081,827 | 7 | 3 | null | 2012-06-18 11:05:35.317 UTC | 3 | 2015-01-15 22:42:53.037 UTC | 2015-01-15 22:42:53.037 UTC | null | 21,115 | null | 788,652 | null | 1 | 38 | ruby-on-rails|ruby|regex | 24,648 | <p>I don't think a regex is a good idea, seeing how simple the task is:</p>
<pre><code>irb(main):001:0> s = 'https://www.facebook.com/hackerbob'
=> "https://www.facebook.com/hackerbob"
irb(main):002:0> s.split('/')[-1]
=> "hackerbob"
</code></pre>
<p>Of course you could also do it using regex, but it's a lot less readable:</p>
<pre><code>irb(main):003:0> s[/([^\/]+)$/]
=> "hackerbob"
</code></pre> |
11,420,263 | Is it possible to read infinity or NaN values using input streams? | <p>I have some input to be read by a input filestream (for example):</p>
<p><code>-365.269511 -0.356123 -Inf 0.000000</code></p>
<p>When I use <code>std::ifstream mystream;</code> to read from the file to some </p>
<p><code>double d1 = -1, d2 = -1, d3 = -1, d4 = -1;</code> </p>
<p>(assume <code>mystream</code> has already been opened and the file is valid), </p>
<p><code>mystream >> d1 >> d2 >> d3 >> d4;</code></p>
<p><code>mystream</code> is in the fail state. I would expect </p>
<p><code>std::cout << d1 << " " << d2 << " " << d3 << " " << d4 << std::endl;</code> </p>
<p>to output </p>
<p><code>-365.269511 -0.356123 -1 -1</code>. I would want it to output <code>-365.269511 -0.356123 -Inf 0</code> instead.</p>
<p>This set of data was output using C++ streams. Why can't I do the reverse process (read in my output)? How can I get the functionality I seek?</p>
<p>From MooingDuck:</p>
<pre><code>#include <iostream>
#include <limits>
using namespace std;
int main()
{
double myd = std::numeric_limits<double>::infinity();
cout << myd << '\n';
cin >> myd;
cout << cin.good() << ":" << myd << endl;
return 0;
}
</code></pre>
<p>Input: <code>inf</code></p>
<p>Output: </p>
<pre><code>inf
0:inf
</code></pre>
<p>See also: <a href="http://ideone.com/jVvei">http://ideone.com/jVvei</a></p>
<p>Also related to this problem is <code>NaN</code> parsing, even though I do not give examples for it.</p>
<p>I added to the accepted answer a complete solution on ideone. It also includes paring for "Inf" and "nan", some possible variations to those keywords that may come from other programs, such as MatLab.</p> | 11,421,585 | 6 | 8 | null | 2012-07-10 19:12:22.703 UTC | 4 | 2020-04-05 09:57:56.527 UTC | 2012-07-16 15:59:03.79 UTC | null | 868,546 | null | 868,546 | null | 1 | 49 | c++|numeric-limits | 11,879 | <p><strong>Edit:</strong> To avoid the use of a wrapper structure around a double, I enclose an <code>istream</code> within a wrapper class instead.</p>
<p>Unfortunately, I am unable to figure out how to avoid the ambiguity created by adding another input method for <code>double</code>. For the implementation below, I created a wrapper structure around an <code>istream</code>, and the wrapper class implements the input method. The input method determines negativity, then tries to extract a double. If that fails, it starts a parse.</p>
<p><strong>Edit:</strong> Thanks to sehe for getting me to check for error conditions better.</p>
<pre><code>struct double_istream {
std::istream &in;
double_istream (std::istream &i) : in(i) {}
double_istream & parse_on_fail (double &x, bool neg);
double_istream & operator >> (double &x) {
bool neg = false;
char c;
if (!in.good()) return *this;
while (isspace(c = in.peek())) in.get();
if (c == '-') { neg = true; }
in >> x;
if (! in.fail()) return *this;
return parse_on_fail(x, neg);
}
};
</code></pre>
<p>The parsing routine was a little trickier to implement than I first thought it would be, but I wanted to avoid trying to <code>putback</code> an entire string.</p>
<pre><code>double_istream &
double_istream::parse_on_fail (double &x, bool neg) {
const char *exp[] = { "", "inf", "NaN" };
const char *e = exp[0];
int l = 0;
char inf[4];
char *c = inf;
if (neg) *c++ = '-';
in.clear();
if (!(in >> *c).good()) return *this;
switch (*c) {
case 'i': e = exp[l=1]; break;
case 'N': e = exp[l=2]; break;
}
while (*c == *e) {
if ((e-exp[l]) == 2) break;
++e; if (!(in >> *++c).good()) break;
}
if (in.good() && *c == *e) {
switch (l) {
case 1: x = std::numeric_limits<double>::infinity(); break;
case 2: x = std::numeric_limits<double>::quiet_NaN(); break;
}
if (neg) x = -x;
return *this;
} else if (!in.good()) {
if (!in.fail()) return *this;
in.clear(); --c;
}
do { in.putback(*c); } while (c-- != inf);
in.setstate(std::ios_base::failbit);
return *this;
}
</code></pre>
<p>One difference in behavior this routine will have over the the default <code>double</code> input is that the <code>-</code> character is not consumed if the input was, for example <code>"-inp"</code>. On failure, <code>"-inp"</code> will still be in the stream for <code>double_istream</code>, but for a regular <code>istream</code> only <code>"inp"</code> will be left in the the stream.</p>
<pre><code>std::istringstream iss("1.0 -NaN inf -inf NaN 1.2");
double_istream in(iss);
double u, v, w, x, y, z;
in >> u >> v >> w >> x >> y >> z;
std::cout << u << " " << v << " " << w << " "
<< x << " " << y << " " << z << std::endl;
</code></pre>
<p>The output of the above snippet on my system is:</p>
<pre><code>1 nan inf -inf nan 1.2
</code></pre>
<p><strong>Edit:</strong> Adding a "iomanip" like helper class. A <code>double_imanip</code> object will act like a toggle when it appears more than once in the <code>>></code> chain.</p>
<pre><code>struct double_imanip {
mutable std::istream *in;
const double_imanip & operator >> (double &x) const {
double_istream(*in) >> x;
return *this;
}
std::istream & operator >> (const double_imanip &) const {
return *in;
}
};
const double_imanip &
operator >> (std::istream &in, const double_imanip &dm) {
dm.in = &in;
return dm;
}
</code></pre>
<p>And then the following code to try it out:</p>
<pre><code>std::istringstream iss("1.0 -NaN inf -inf NaN 1.2 inf");
double u, v, w, x, y, z, fail_double;
std::string fail_string;
iss >> double_imanip()
>> u >> v >> w >> x >> y >> z
>> double_imanip()
>> fail_double;
std::cout << u << " " << v << " " << w << " "
<< x << " " << y << " " << z << std::endl;
if (iss.fail()) {
iss.clear();
iss >> fail_string;
std::cout << fail_string << std::endl;
} else {
std::cout << "TEST FAILED" << std::endl;
}
</code></pre>
<p>The output of the above is:</p>
<pre><code>1 nan inf -inf nan 1.2
inf
</code></pre>
<p><strong>Edit from Drise:</strong> I made a few edits to accept variations such as Inf and nan that wasn't originally included. I also made it into a compiled demonstration, which can be viewed at <a href="http://ideone.com/qIFVo" rel="nofollow">http://ideone.com/qIFVo</a>.</p> |
10,957,238 | "Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC? | <p>This is how my connection is set:<br>
<code>Connection conn = DriverManager.getConnection(url + dbName + "?useUnicode=true&characterEncoding=utf-8", userName, password);</code></p>
<p>And I'm getting the following error when tyring to add a row to a table:<br>
<code>Incorrect string value: '\xF0\x90\x8D\x83\xF0\x90...' for column 'content' at row 1</code></p>
<p>I'm inserting thousands of records, and I always get this error when the text contains \xF0 (i.e. the the incorrect string value always starts with \xF0).</p>
<p>The column's collation is utf8_general_ci.</p>
<p>What could be the problem?</p> | 10,959,780 | 21 | 4 | null | 2012-06-08 23:46:11.96 UTC | 95 | 2022-09-16 03:38:45.057 UTC | 2012-08-07 07:03:45.96 UTC | null | 96,656 | null | 618,355 | null | 1 | 305 | mysql|jdbc|utf-8|utf8mb4 | 498,224 | <p>MySQL's <code>utf8</code> permits only the Unicode characters that can be represented with 3 bytes in UTF-8. Here you have a character that needs 4 bytes: \xF0\x90\x8D\x83 (<a href="http://www.fileformat.info/info/unicode/char/10343/index.htm" rel="noreferrer">U+10343 GOTHIC LETTER SAUIL</a>).</p>
<p>If you have MySQL 5.5 or later you can change the column encoding from <code>utf8</code> to <a href="http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html" rel="noreferrer"><code>utf8mb4</code></a>. This encoding allows storage of characters that occupy 4 bytes in UTF-8.</p>
<p>You may also have to set the server property <code>character_set_server</code> to <code>utf8mb4</code> in the MySQL configuration file. It seems that <a href="http://dev.mysql.com/doc/connector-j/en/connector-j-reference-charsets.html" rel="noreferrer">Connector/J defaults to 3-byte Unicode otherwise</a>:</p>
<blockquote>
<p>For example, to use 4-byte UTF-8 character sets with Connector/J, configure the MySQL server with <code>character_set_server=utf8mb4</code>, and leave <code>characterEncoding</code> out of the Connector/J connection string. Connector/J will then autodetect the UTF-8 setting. </p>
</blockquote> |
12,842,729 | Finding type parameters via reflection in Scala 2.10? | <p>Using type tags, I'm able to <em>see</em> the parameters of some type:</p>
<pre><code>scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = List[Int]
</code></pre>
<p>But I just can't quite figure out how to programmatically get that "Int" out of there, in a general way. </p>
<p>(I've been wandering around in REPL for an hour now, trying permutations on Type, to see what I can obtain from it... I get a lot of things which indicate this is a "List", but good luck on finding that "Int"! And I don't really want to resort to parsing the toString() output...)</p>
<p>Daniel Sobral has an excellent (as usual) quick overview <a href="http://dcsobral.blogspot.fr/2012/07/json-serialization-with-reflection-in.html">here</a>, in which he gets tantalizingly close to what I'm looking for, but (apparently) only if you happen to know, for that particular class, some specific method whose type can be interrogated:</p>
<pre><code>scala> res0.member(newTermName("head"))
res1: reflect.runtime.universe.Symbol = method head
scala> res1.typeSignatureIn(res0)
res2: reflect.runtime.universe.Type = => Int
</code></pre>
<p>But I'm hoping for something more general, which doesn't involve rooting around in the list of declared methods and hoping that one of them will capture (and thus divulge) the tag's current type information somewhere.</p>
<p>If Scala can so easily <em>print</em> "List[Int]", why on earth is it so hard to discover that "Int" part of that -- without resorting to string pattern matching? Or am I just missing something really, really obvious?</p>
<pre><code>scala> res0.typeSymbol.asInstanceOf[ClassSymbol].typeParams
res12: List[reflect.runtime.universe.Symbol] = List(type A)
scala> res12.head.typeSignatureIn(res0)
res13: reflect.runtime.universe.Type =
</code></pre>
<p>Grr...</p> | 12,843,766 | 2 | 1 | null | 2012-10-11 15:06:07.887 UTC | 10 | 2017-11-18 16:41:54.41 UTC | 2012-10-11 15:38:46.49 UTC | null | 1,465,199 | null | 1,465,199 | null | 1 | 22 | scala|reflection|scala-2.10 | 5,400 | <p>Sadly, I don't think that there's a method that will give you the parameters, but you can get hold of them this way:</p>
<pre><code>Welcome to Scala version 2.10.0-20121007-145615-65a321c63e (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_35).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = scala.List[Int]
scala> res0 match { case TypeRef(_, _, args) => args }
res1: List[reflect.runtime.universe.Type] = List(Int)
scala> res1.head
res2: reflect.runtime.universe.Type = Int
</code></pre>
<p><strong>Edit</strong>
Here's a slightly nicer way to achieve the same thing (following a <a href="https://groups.google.com/d/msg/scala-internals/56KRF98Mdjo/IOZ_kHTw79cJ">discussion on scala-internals</a>):</p>
<pre><code>scala> res0.asInstanceOf[TypeRefApi].args
res1: List[reflect.runtime.universe.Type] = List(Int)
</code></pre> |
13,102,918 | Cast string as array | <p>How, in Javascript, can I cast a string as an array in the same way that PHP (array) does.</p>
<pre><code>//PHP
$array = (array)"string"
</code></pre>
<p>Basically I have a variable that can be an array or a string and, if a string, I want to make it an array using an inline command.</p> | 13,102,952 | 12 | 3 | null | 2012-10-27 18:25:02.517 UTC | 2 | 2022-04-28 14:17:51.013 UTC | null | null | null | null | 856,498 | null | 1 | 22 | javascript | 57,167 | <p>JavaScript is a prototyping language and does not have a type casting system.</p>
<p>One solution would be to check if your variable is a string and convert it into an array. For example :</p>
<pre><code>if (typeof someVariable === 'string') someVariable = [someVariable];
</code></pre>
<p>In PHP, if you do a check on a <strong>string</strong>, like (ex: <code>$array = 'string';</code>) :</p>
<pre><code>$array = (array) $array; // ex: "string" becomes array("string")
</code></pre>
<p>The JavaScript equivalent will be</p>
<pre><code>arr = typeof arr === 'string' ? [arr] : arr;
</code></pre>
<p>If your variable <code>arr</code> is not necessarily a string, you may use <code>instanceof</code> (<em>edit: or <code>Array.isArray</code></em>) :</p>
<pre><code>arr = arr instanceof Array ? arr : [arr];
arr = Array.isArray(arr) ? arr : [arr];
</code></pre> |
13,035,736 | Django load block for css | <p>I have a few pages. For every page I need load unique css.
For all static files I use <a href="https://docs.djangoproject.com/en/dev/howto/static-files/#with-a-template-tag" rel="noreferrer">this</a>. In the head of index.html I have:</p>
<pre><code>{% block css %}
{% endblock %}
</code></pre>
<p>But, for example, in contact.html I use:</p>
<pre><code>{% extends "index.html" %}
{% block css %}
<link rel="stylesheet" href="{% static "css/contact.css" %}" type="text/css" />
{% endblock %}
</code></pre>
<p>And its print error:
<strong>Invalid block tag: 'static', expected 'endblock'</strong>. How to fix it?</p> | 13,036,010 | 3 | 0 | null | 2012-10-23 17:09:34.093 UTC | 5 | 2019-01-20 07:40:53.54 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,751,039 | null | 1 | 49 | css|django|static | 21,875 | <p>You need to use <code>{% load static %}</code> first.</p> |
13,088,826 | Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found using Visual Studio 2012 | <p>When I click on the home-icon of Team Explorer, I get the following error:</p>
<blockquote>
<p>Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found instead of all the options.</p>
</blockquote>
<p>I have this error since I reinstalled the Visual Studio 2012 Ultimate trial and installed the Visual Studio 2012 Premium edition. Repair and reinstall didn't work out.</p> | 21,728,708 | 10 | 0 | null | 2012-10-26 14:27:55.643 UTC | 12 | 2018-06-13 13:43:42.123 UTC | 2017-12-29 19:36:29.983 UTC | null | 63,550 | null | 1,387,830 | null | 1 | 61 | visual-studio | 24,870 | <p>To fix this, run this from the Visual Studio command prompt as administrator:</p>
<pre><code>devenv /setup
</code></pre>
<p>It will not mess up your environment, and you can just continue to use Visual Studio afterwards was my experience.</p> |
37,414,304 | Typescript complains Property does not exist on type 'JSX.IntrinsicElements' when using React.createClass? | <p>I am using typescript to write redux application.</p>
<pre><code>var item = React.createClass({
render: function() {
return (<div>hello world</div>)
}
});
export default class ItemList extends Component<any, any> {
render() {
return (<item />)
}
}
</code></pre>
<p>Then typescript complains this:</p>
<pre><code>Property 'item' does not exist on type 'JSX.IntrinsicElements'.
</code></pre> | 37,414,418 | 8 | 6 | null | 2016-05-24 12:56:05.377 UTC | 13 | 2022-09-04 00:13:22.497 UTC | null | null | null | null | 2,849,157 | null | 1 | 99 | reactjs|typescript|redux | 159,389 | <p>Your component must start with a capital letter <code>I</code> instead of small letter <code>i</code> otherwise TypeScript would yell. Changing <code>item</code> to <code>Item</code> should fix it:</p>
<pre><code>var Item = React.createClass({
render: function() {
return (<div>hello world</div>)
}
});
export default class ItemList extends Component<any, any> {
render() {
return (<Item />)
}
}
</code></pre> |
16,785,369 | How to include other files to the output directory in C# upon build? | <p>I have some library files needed for my application to work.<br />
My application has a setup and deployment included.</p>
<p>I already know that in order for a library file to be added to the output directory of the application when installing, I just have to reference those libraries inside the .NET IDE before building... the only problem is that these libraries can't be referenced... So I need to be able to copy these libraries to the installation directory of my application... At the moment, I am copying these libraries manually...</p>
<p><strong>Addendum</strong></p>
<p>I also did try to add these library files as an <em><strong>Existing Item</strong></em> to my project and marked each library files' <em><strong>Copy to Output Directory</strong></em> to <em><strong>Copy if newer</strong></em> on their properties but still not getting the solution I want.</p>
<p><strong>Update 1</strong></p>
<p>Thanks for you help guys it helped me solve my problem, I managed to make the solutions you posted work except for one... @Matthew Watson's post.. I even managed to find a solution too so I wanted to share it with you also.</p>
<p>Heres what I did:</p>
<ol>
<li>I opened the setup and deployment project in my application.</li>
<li>Under the Application Folder Tree, on it's right side, I right clicked..</li>
<li>then clicked Add..</li>
<li>then clicked File</li>
<li>and then browsed for the files I wanted to add to the installation directory</li>
<li>and click open.</li>
</ol>
<p>But out of curiosity...I am still trying to make what @Matthew Watson posted work...Hope you can help me with this one guys. Thanks in advance</p>
<p><strong>Update 2</strong></p>
<p>I forgot to update this post yesterday, I already manage to make Matthew Watson's solution worked yesterday. Thank you again for all your help guys.</p> | 16,785,426 | 2 | 11 | null | 2013-05-28 06:37:30.127 UTC | 8 | 2020-09-30 16:26:30.607 UTC | 2020-09-30 16:26:30.607 UTC | null | 8,166,701 | null | 2,273,524 | null | 1 | 58 | c#|.net|installation | 112,124 | <p>You can add files to your project and select their properties: <code>"Build Action"</code> as <code>"Content"</code> and <code>"Copy to output directory"</code> as <code>"Copy Always"</code> or <code>Copy if Newer</code> (the latter is preferable because otherwise the project rebuilds fully every time you build it).</p>
<p>Then those files will be copied to your output folder.</p>
<p>This is better than using a post build step because Visual Studio will know that the files are part of the project. (That affects things like ClickOnce applications which need to know what files to add to the clickonce data.)</p>
<p>You will also be more easily able to see which files are in the project because they will be listed with the source code files rather than hidden in a post-build step. And also Source Control can be used with them more easily.</p>
<p>Once you have added "Content" files to your project, you will be able to add them to a Visual Studio 2010 Setup and Deployment project as follows:</p>
<p>Go into your Setup project and add to your <code>"Application Folder"</code> output the Project Output called <code>"Content Files"</code>. If you right-click the Content Files after adding them you can select "outputs" and see what it's going to copy.</p>
<p>Note that Setup and Deployment projects are NOT supported in Visual Studio 2012.</p> |
16,800,711 | Passing function as a parameter in java | <p>I'm getting familiar with Android framework and Java and wanted to create a general "NetworkHelper" class which would handle most of the networking code enabling me to just call web-pages from it.</p>
<p>I followed this article from the developer.android.com to create my networking class: <a href="http://developer.android.com/training/basics/network-ops/connecting.html" rel="noreferrer">http://developer.android.com/training/basics/network-ops/connecting.html</a></p>
<p>Code:</p>
<pre><code>package com.example.androidapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
/**
* @author tuomas
* This class provides basic helper functions and features for network communication.
*/
public class NetworkHelper
{
private Context mContext;
public NetworkHelper(Context mContext)
{
//get context
this.mContext = mContext;
}
/**
* Checks if the network connection is available.
*/
public boolean checkConnection()
{
//checks if the network connection exists and works as should be
ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
//network connection works
Log.v("log", "Network connection works");
return true;
}
else
{
//network connection won't work
Log.v("log", "Network connection won't work");
return false;
}
}
public void downloadUrl(String stringUrl)
{
new DownloadWebpageTask().execute(stringUrl);
}
//actual code to handle download
private class DownloadWebpageTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls)
{
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException
{
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d("log", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException
{
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
//textView.setText(result);
Log.v("log", result);
}
}
</code></pre>
<p>}</p>
<p>In my activity class I use the class this way:</p>
<pre><code>connHelper = new NetworkHelper(this);
</code></pre>
<p>...</p>
<pre><code>if (connHelper.checkConnection())
{
//connection ok, download the webpage from provided url
connHelper.downloadUrl(stringUrl);
}
</code></pre>
<p>Problem I'm having is that I should somehow make a callback back to the activity and it should be definable in "downloadUrl()" function. For example when download finishes, public void "handleWebpage(String data)" function in activity is called with loaded string as its parameter.</p>
<p>I did some googling and found that I should somehow use interfaces to achieve this functionality. After reviewing few similar stackoverflow questions/answers I didn't get it working and I'm not sure if I understood interfaces properly: <a href="https://stackoverflow.com/questions/12616796/how-do-i-pass-method-as-a-parameter-in-java">How do I pass method as a parameter in Java?</a> To be honest using the anonymous classes is new for me and I'm not really sure where or how I should apply the example code snippets in the mentioned thread.</p>
<p>So my question is how I could pass the callback function to my network class and call it after download finishes? Where the interface declaration goes, implements keyword and so on?
Please note that I'm beginner with Java (have other programming background though) so I'd appreciate a throughout explanation :) Thank you!</p> | 16,800,770 | 7 | 0 | null | 2013-05-28 20:16:08.967 UTC | 23 | 2022-07-04 03:43:26.77 UTC | 2017-05-23 12:17:54.33 UTC | null | -1 | null | 969,294 | null | 1 | 75 | java|android|function|interface|parameters | 97,565 | <p>Use a callback interface or an abstract class with abstract callback methods.</p>
<p>Callback interface example:</p>
<pre><code>public class SampleActivity extends Activity {
//define callback interface
interface MyCallbackInterface {
void onDownloadFinished(String result);
}
//your method slightly modified to take callback into account
public void downloadUrl(String stringUrl, MyCallbackInterface callback) {
new DownloadWebpageTask(callback).execute(stringUrl);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//example to modified downloadUrl method
downloadUrl("http://google.com", new MyCallbackInterface() {
@Override
public void onDownloadFinished(String result) {
// Do something when download finished
}
});
}
//your async task class
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
final MyCallbackInterface callback;
DownloadWebpageTask(MyCallbackInterface callback) {
this.callback = callback;
}
@Override
protected void onPostExecute(String result) {
callback.onDownloadFinished(result);
}
//except for this leave your code for this class untouched...
}
}
</code></pre>
<p>The second option is even more concise. You do not even have to define an abstract method for "onDownloaded event" as <code>onPostExecute</code> does exactly what is needed. Simply extend your <code>DownloadWebpageTask</code> with an anonymous inline class inside your <code>downloadUrl</code> method.</p>
<pre><code> //your method slightly modified to take callback into account
public void downloadUrl(String stringUrl, final MyCallbackInterface callback) {
new DownloadWebpageTask() {
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
callback.onDownloadFinished(result);
}
}.execute(stringUrl);
}
//...
</code></pre> |
4,780,152 | extract coefficients from glm in R | <p>I have performed a logistic regression with the following result:</p>
<pre><code>ssi.logit.single.age["coefficients"]
# $coefficients
# (Intercept) age
# -3.425062382 0.009916508
</code></pre>
<p>I need to pick up the coefficient for <code>age</code>, and currently I use the following code:</p>
<pre><code>ssi.logit.single.age["coefficients"][[1]][2]
</code></pre>
<p>It works, but I don't like the cryptic code here, can I use the name of the coefficient (i.e. <code>(Intercept)</code> or <code>age</code>)</p> | 4,780,948 | 2 | 0 | null | 2011-01-24 08:57:35.463 UTC | 5 | 2016-03-12 21:21:39.903 UTC | 2016-03-12 21:21:39.903 UTC | null | 3,576,984 | null | 373,908 | null | 1 | 17 | list|r | 45,768 | <p>There is an extraction function called <code>coef</code> to get coefficients from models:</p>
<pre><code>coef(ssi.logit.single.age)["age"]
</code></pre> |
4,652,248 | jquery how to set input focus on control | <p>Hey I am very new to jquery using asp.net, and I was wondering how to set focus on a textbox using jquery.</p>
<p>I have my script in my HeaderContent but it is not working, no focus on load. And yes I know this can be done on the server side as well, but I am just trying to get better and more familiar with jquery. Thanks.</p>
<pre><code><script type="text/javascript">
$(document).ready(function () {
$("#MainContent_LoginUser_UserName").focus();
});
</script>
</code></pre> | 4,652,266 | 2 | 0 | null | 2011-01-10 22:30:00.937 UTC | 3 | 2016-09-05 21:18:54.793 UTC | 2016-09-05 21:18:54.793 UTC | null | 292,502 | null | 516,883 | null | 1 | 23 | jquery|asp.net|input | 72,493 | <p>Your code is correct. If it is failing, chances are <code>$("#MainContent_LoginUser_UserName")</code> is not the correct selector value or perhaps jQuery is not correctly loaded.</p>
<p>If you are using jQuery alongside standard ASP.NET JavaScript, then the '$' will not be mapped to jQuery, but instead to ASP.NET's JavaScript framework. You may need to substitute <code>$("#foo")</code> for <code>jQuery("#foo")</code>.</p> |
4,839,532 | Recompiling the RTL - if possible, then how? | <p>I have this craving to do some experiments with modifying the underbelly of the Delphi run time library (RTL), <code>system.pas</code> and the likes... It is possible or not?</p>
<p>I'm very fond of challenges like "yes, but you'll have to provide custom .obj files for some assembler wizardry because they were never distributed with the official Delphi source". Fine with me, I just want to know.</p>
<p>I want to do this experiment with Delphi 7, but inside information on any other version is fine. It is one of the perks of being with a company that worked with Delphi since the Stone Age.</p>
<p>(I always figured this to be one of those RTFM questions, with the answer being a resounding "NO!", but for some reason google won't confirm it.)</p> | 4,842,026 | 2 | 0 | null | 2011-01-29 21:23:45.493 UTC | 10 | 2014-03-06 14:42:20.64 UTC | 2014-03-06 14:42:20.64 UTC | null | 578,411 | null | 16,725 | null | 1 | 23 | delphi | 6,074 | <p>You can recompile the RTL like any other unit.</p>
<p>For System.pas you must use the command line compiler.</p>
<p>For instance, here is a working batch file content (there is some not well documented command line switches):</p>
<pre><code>del *.dcu /s
"c:\program files\borland\delphi7\bin\dcc32.exe" -O+ -Q -M -Y -Z -$D+ System.pas
</code></pre>
<p>This will recompile System.pas and SysInit.pas (both lowest level RTL files).</p>
<p>But in order to use your recreated dcu files, you'll have to put the folder containing the updated dcu files into the first position of your IDE: for instance, in Delphi 7 it's Option / Environment Options / Library, then put your folder FIRST in both "Libary path" and "Browsing path" field.</p>
<p>And it's perhaps worth deleting the original .dcu files in your Delphi installation directory.</p>
<p>But be sure you won't change the "interface" part of the unit, or you'll have troubles with compiling with other not modified units of the RTL (or third-party components). You can change the "implementation" part, apply fixes or rewrite some part for speed or such, but don't change the "interface" part to avoid any linking error.</p>
<p>Always make a backup of the original .pas and .dcu files which you are changing. And it's a good idea to make some automated compilation test, so that you could be sure that your modifications of the RTL won't add any regression.</p>
<p>We made such a RTL recompilation for our <a href="http://blog.synopse.info/category/Open-Source-Projects/Enhanced-Delphi-Run-Time" rel="noreferrer">Enhanced Run Time Library</a> for better speed of low-level RTL functions (mostly System.pas and SysUtils.pas). Designed for Delphi 7 and 2007. For more recent Delphi version, you still can use the same principle.</p> |
4,271,717 | How can I define a C function in one file, then call it from another? | <p>If I define a function in file <code>func1.c</code>, and I want to call it from file <code>call.c</code>. How can I accomplish this task?</p> | 4,271,733 | 2 | 0 | null | 2010-11-24 21:28:50.223 UTC | 5 | 2020-07-13 07:25:41.063 UTC | 2020-07-13 07:25:41.063 UTC | null | 12,825,713 | null | 510,333 | null | 1 | 29 | c|file|function|call | 51,097 | <p>You would put a declaration for the function in the file <code>func1.h</code>, and add <code>#include "func1.h"</code> in <code>call.c</code>. Then you would compile or link <code>func1.c</code> and <code>call.c</code> together (details depend on which C system).</p> |
4,146,813 | How to stop chrome from caching | <p>I need to force the browser to reload the previous page from the server when the user presses the back button.</p>
<p>I've added the following to my response headers:</p>
<pre><code>Cache-Control: no-cache, must-revalidate
Expires: -1
</code></pre>
<p>This seems to work for most browsers but not for Google Chrome that insists on returning the cached results.</p>
<p>So does anyone know how I force the browser to get the page from the server when the user presses the back button?</p>
<p>Thank you.</p> | 4,146,870 | 2 | 2 | null | 2010-11-10 16:48:40.987 UTC | 10 | 2012-11-13 04:44:53.707 UTC | 2012-06-16 18:30:49.11 UTC | null | 210,916 | null | 24,804 | null | 1 | 41 | html|google-chrome|reload|meta-tags | 28,670 | <p>as per <a href="http://code.google.com/p/chromium/issues/detail?id=28035" rel="noreferrer">this bug report</a> in chromium repo, users find that using no-store instead of no-cache will fix it in chrome.</p> |
4,425,571 | What's the difference between x:Key and x:Name in WPF? | <p>What's the difference between <code>x:Key</code> and <code>x:Name</code> in WPF?</p>
<p>I am not sure what the true difference is.</p> | 4,425,632 | 2 | 0 | null | 2010-12-13 03:23:28.807 UTC | 7 | 2015-10-08 13:40:01.023 UTC | 2015-10-08 13:40:01.023 UTC | null | 267,702 | null | 59,035 | null | 1 | 59 | wpf | 21,341 | <p>Although they are used for similar purposes, they are not interchangeable. x:Key is used for items that are being added as values to a dictionary, most often for styles and other resources that are being added to a ResourceDictionary. When setting the x:Key attribute, there is actually no corresponding property on the object or even an attached dependency property being set. It is simply used by the XAML processor to know what key to use when calling Dictionary.Add.</p>
<p>x:Name is a bit more complicated. It's used to apply an associated name to an object (typically an object derived from FrameworkElement) within the scope of some parent element. This scope is called a "namescope" and the easiest way to think of it is to imagine a UserControl that contains a <code><TextBox x:Name="foo" /></code>.</p>
<p>You could then put multiple instances of the UserControl onto a Window without the name "foo" colliding because each UserControl has its own namescope.</p>
<p>It's worth noting too that FrameworkElement defines a dependency property called Name that is equivalent to setting x:Name.</p>
<p>The other difference is that the XAML designer creates members in the code-behind for elements that have an x:Name. This is not true of objects added to a dictionary using x:Key.</p>
<p>You can find more information about these in the remarks section of the MSDN documentation for <a href="http://msdn.microsoft.com/en-us/library/ms752290.aspx" rel="noreferrer">the x:Name directive</a>.</p> |
41,494,358 | Spyder Python "object arrays are currently not supported" | <p>I have a problem in Anaconda Spyder (Python).</p>
<p>Object type array can not be seen under Windows 10 in the <strong>variable explorer</strong>. If I click on <em>X or Y</em>, I see an error:</p>
<blockquote>
<p>object arrays are currently not supported. </p>
</blockquote>
<p>I have Win 10 Home 64bit (i7-4710HQ) and Python 3.5.2 | Anaconda 4.2.0 (64-bit) [MSC v.1900 64 bit (AMD64)]</p>
<p><img src="https://i.stack.imgur.com/uApwt.jpg" alt="Screenshot"></p> | 46,408,782 | 18 | 8 | null | 2017-01-05 20:43:43.377 UTC | 6 | 2021-05-16 09:40:20.413 UTC | 2019-03-15 21:12:19.107 UTC | null | 3,100,515 | null | 7,381,227 | null | 1 | 35 | python|anaconda|spyder | 65,170 | <p>(<em>Spyder developer here</em>) Support for object arrays will be added in Spyder <strong>4</strong>, to be released in 2019.</p> |
9,750,097 | How can a button get the focus? | <p>There are quite a few posts touching this topic. I thought I should ask this simple question hoping to clarify this.</p>
<p>I am unable to achieve setting the focus on a button. I know I probably miss something fundamental. Here is the simple layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:focusable="true" />
</LinearLayout>
</code></pre>
<p>The following is the simple code in onCreate():</p>
<pre><code> Button button = (Button)findViewById(R.id.button1);
button.setFocusable(true);
button.requestFocus();
button.setText("Debug"); //Just to show the code here has been executed
</code></pre>
<p>It simply does not work (i.e. the button does not get the focus).</p>
<p>Any correction of my error or misunderstanding will be greatly appreciated.</p> | 9,750,125 | 1 | 0 | null | 2012-03-17 12:46:37.433 UTC | 2 | 2018-07-17 15:38:04.063 UTC | null | null | null | null | 355,456 | null | 1 | 17 | android|button | 39,662 | <p>update your code:</p>
<pre><code> Button button = (Button)findViewById(R.id.button1);
button.setFocusable(true);
button.setFocusableInTouchMode(true);///add this line
button.requestFocus();
button.setText("Debug");
</code></pre> |
44,080,248 | Pandas: Join dataframe with condition | <p>So I have this dataframe (as below), I am trying to join itself by copying it into another df. The join condition as below;
Join condition:</p>
<ol>
<li>Same PERSONID and Badge_ID</li>
<li>But different SITE_ID1 </li>
<li>Timedelta between the two rows should be less than 48 hrs.</li>
</ol>
<p>Expecting</p>
<pre><code>PERSONID Badge_ID Reader_ID1_x SITE_ID1_x EVENT_TS1_x Reader_ID1_y SITE_ID1_x EVENT_TS1_y
2553-AMAGID 4229 141 99 2/1/2016 3:26 145 97 2/1/2016 3:29
2553-AMAGID 4229 248 99 2/1/2016 3:26 145 97 2/1/2016 3:29
2553-AMAGID 4229 145 97 2/1/2016 3:29 251 99 2/1/2016 3:29
2553-AMAGID 4229 145 97 2/1/2016 3:29 291 99 2/1/2016 3:29
</code></pre>
<p>Here is what I tired,
Make a copy of df and then filter each df with this condition like below and then join them back again. But the below condition doesn't work :(
I tried this filters in SQL before reading into df but that's too slow for 600k+ rows, event with indexes.</p>
<pre><code>df1 = df1[(df1['Badge_ID']==df2['Badge_ID']) and (df1['SITE_ID1']!=df2['SITE_ID1']) and ((df1['EVENT_TS1']-df2['EVENT_TS1'])<=datetime.timedelta(hours=event_time_diff))]
PERSONID Badge_ID Reader_ID1 SITE_ID1 EVENT_TS1
2553-AMAGID 4229 141 99 2/1/2016 3:26:10 AM
2553-AMAGID 4229 248 99 2/1/2016 3:26:10 AM
2553-AMAGID 4229 145 97 2/1/2016 3:29:56 AM
2553-AMAGID 4229 251 99 2/1/2016 3:29:56 AM
2553-AMAGID 4229 291 99 2/1/2016 3:29:56 AM
2557-AMAGID 4219 144 99 2/1/2016 2:36:30 AM
2557-AMAGID 4219 144 99 2/1/2016 2:40:00 AM
2557-AMAGID 4219 250 99 2/1/2016 2:40:00 AM
2557-AMAGID 4219 290 99 2/1/2016 2:40:00 AM
2557-AMAGID 4219 144 97 2/1/2016 4:02:06 AM
2557-AMAGID 4219 250 99 2/1/2016 4:02:06 AM
2557-AMAGID 4219 290 99 2/1/2016 4:02:06 AM
2557-AMAGID 4219 250 97 2/2/2016 1:36:30 AM
2557-AMAGID 4219 290 99 2/3/2016 2:38:30 AM
2559-AMAGID 4227 141 99 2/1/2016 4:33:24 AM
2559-AMAGID 4227 248 99 2/1/2016 4:33:24 AM
2560-AMAGID 4226 141 99 2/1/2016 4:10:56 AM
2560-AMAGID 4226 248 99 2/1/2016 4:10:56 AM
2560-AMAGID 4226 145 99 2/1/2016 4:33:52 AM
2560-AMAGID 4226 251 99 2/1/2016 4:33:52 AM
2560-AMAGID 4226 291 99 2/1/2016 4:33:52 AM
2570-AMAGID 4261 141 99 2/1/2016 4:27:02 AM
2570-AMAGID 4261 248 99 2/1/2016 4:27:02 AM
2986-AMAGID 4658 145 99 2/1/2016 3:14:54 AM
2986-AMAGID 4658 251 99 2/1/2016 3:14:54 AM
2986-AMAGID 4658 291 99 2/1/2016 3:14:54 AM
2986-AMAGID 4658 144 99 2/1/2016 3:26:30 AM
2986-AMAGID 4658 250 99 2/1/2016 3:26:30 AM
2986-AMAGID 4658 290 99 2/1/2016 3:26:30 AM
4133-AMAGID 6263 142 99 2/1/2016 2:44:08 AM
4133-AMAGID 6263 249 99 2/1/2016 2:44:08 AM
4133-AMAGID 6263 141 34 2/1/2016 2:44:20 AM
4133-AMAGID 6263 248 34 2/1/2016 2:44:20 AM
4414-AMAGID 6684 145 99 2/1/2016 3:08:06 AM
4414-AMAGID 6684 251 99 2/1/2016 3:08:06 AM
4414-AMAGID 6684 291 99 2/1/2016 3:08:06 AM
4414-AMAGID 6684 145 22 2/1/2016 3:19:12 AM
4414-AMAGID 6684 251 22 2/1/2016 3:19:12 AM
4414-AMAGID 6684 291 22 2/1/2016 3:19:12 AM
4414-AMAGID 6684 145 99 2/1/2016 4:14:28 AM
4414-AMAGID 6684 251 99 2/1/2016 4:14:28 AM
4414-AMAGID 6684 291 99 2/1/2016 4:14:28 AM
4484-AMAGID 6837 142 99 2/1/2016 2:51:14 AM
4484-AMAGID 6837 249 99 2/1/2016 2:51:14 AM
4484-AMAGID 6837 141 99 2/1/2016 2:51:26 AM
4484-AMAGID 6837 248 99 2/1/2016 2:51:26 AM
4484-AMAGID 6837 141 99 2/1/2016 3:05:12 AM
4484-AMAGID 6837 248 99 2/1/2016 3:05:12 AM
4484-AMAGID 6837 141 99 2/1/2016 3:08:58 AM
4484-AMAGID 6837 248 99 2/1/2016 3:08:58 AM
</code></pre> | 44,082,653 | 1 | 8 | null | 2017-05-19 23:20:38.51 UTC | 2 | 2017-05-20 06:25:58.933 UTC | 2017-05-20 00:12:40.967 UTC | null | 7,087,214 | null | 7,087,214 | null | 1 | 8 | python|pandas|join|dataframe|conditional-statements | 39,563 | <p>Try the following:</p>
<pre><code># Transform data in first dataframe
df1 = pd.DataFrame(data)
# Save the data in another datframe
df2 = pd.DataFrame(data)
# Rename column names of second dataframe
df2.rename(index=str, columns={'Reader_ID1': 'Reader_ID1_x', 'SITE_ID1': 'SITE_ID1_x', 'EVENT_TS1': 'EVENT_TS1_x'}, inplace=True)
# Merge the dataframes into another dataframe based on PERSONID and Badge_ID
df3 = pd.merge(df1, df2, how='outer', on=['PERSONID', 'Badge_ID'])
# Use df.loc() to fetch the data you want
df3.loc[(df3.Reader_ID1 < df3.Reader_ID1_x) & (df3.SITE_ID1 != df3.SITE_ID1_x) & (pd.to_datetime(df3['EVENT_TS1']) - pd.to_datetime(df3['EVENT_TS1_x'])<=datetime.timedelta(hours=event_time_diff))]
</code></pre> |
9,915,543 | GIT list of new/modified/deleted files | <p>Is there a way to get the list of all new/deleted/modified directories/files in local/remote repository w.r.t each other in GIT ?</p> | 10,733,765 | 11 | 3 | null | 2012-03-28 20:58:04.283 UTC | 8 | 2022-07-21 07:08:45.143 UTC | null | null | null | null | 472,485 | null | 1 | 59 | git|file|list|diff | 70,278 | <p>The best way to list these file is using git status --porcelain</p>
<p>For example:
To remove previously deleted files:</p>
<pre><code>git status --porcelain | awk 'match($1, "D"){print $2}' | xargs git rm
</code></pre> |
11,924,249 | Finding prime factors | <pre><code>#include <iostream>
using namespace std;
void whosprime(long long x)
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{
for(int z = 2; z <= x; z++)
{
if((i != z) && (i%z == 0))
{
imPrime = false;
break;
}
}
if(imPrime && x%i == 0)
cout << i << endl;
imPrime = true;
}
}
int main()
{
long long r = 600851475143LL;
whosprime(r);
}
</code></pre>
<p>I'm trying to find the prime factors of the number 600851475143 specified by <a href="https://projecteuler.net/problem=3" rel="nofollow">Problem 3</a> on Project Euler (it asks for the highest prime factor, but I want to find all of them). However, when I try to run this program I don't get any results. Does it have to do with how long my program is taking for such a large number, or even with the number itself?</p>
<p>Also, what are some more efficient methods to solve this problem, and do you have any tips as to how can I steer towards these more elegant solutions as I'm working a problem out?</p>
<p>As always, thank you!</p> | 11,924,315 | 12 | 7 | null | 2012-08-12 17:28:03.523 UTC | 8 | 2018-12-06 15:06:48.583 UTC | 2015-02-03 13:34:13.783 UTC | null | 849,891 | null | 1,218,732 | null | 1 | 7 | c++|primes|prime-factoring|factorization | 44,153 | <p>Your algorithm is wrong; you don't need <em>i</em>. Here's pseudocode for integer factorization by trial division:</p>
<pre><code>define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
</code></pre>
<p>I'll leave it to you to translate to C++ with the appropriate integer datatypes.</p>
<p>Edit: Fixed comparison (thanks, Harold) and added discussion for Bob John:</p>
<p>The easiest way to understand this is by an example. Consider the factorization of n = 13195. Initially z = 2, but dividing 13195 by 2 leaves a remainder of 1, so the else clause sets z = 3 and we loop. Now n is not divisible by 3, or by 4, but when z = 5 the remainder when dividing 13195 by 5 is zero, so output 5 and divide 13195 by 5 so n = 2639 and z = 5 is unchanged. Now the new n = 2639 is not divisible by 5 or 6, but is divisible by 7, so output 7 and set n = 2639 / 7 = 377. Now we continue with z = 7, and that leaves a remainder, as does division by 8, and 9, and 10, and 11, and 12, but 377 / 13 = 29 with no remainder, so output 13 and set n = 29. At this point z = 13, and z * z = 169, which is larger than 29, so 29 is prime and is the final factor of 13195, so output 29. The complete factorization is 5 * 7 * 13 * 29 = 13195.</p>
<p>There are better algorithms for factoring integers using trial division, and even more powerful algorithms for factoring integers that use techniques other than trial division, but the algorithm shown above will get you started, and is sufficient for Project Euler #3. When you're ready for more, look <a href="http://programmingpraxis.com/contents/themes/#Prime%20Numbers" rel="noreferrer">here</a>.</p> |
11,911,011 | Android: Set ImageView layout_height programmatically | <p>I have an ImageView in my main.xml file:</p>
<pre><code><ImageView
android:id="@+id/pageImage"
android:layout_width="270dp"
android:layout_height="45dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="25dp"
android:layout_marginTop="15dp"
android:scaleType="fitXY"
android:src="@drawable/pageimage" />
</code></pre>
<p>What I only need to do is to set the the <code>layout_height</code> programmatically to another value.</p>
<p>Additionally, I need to set the value in <strong>dp</strong>. So it is currently 45dp, I'd like to change it to another value in my main activity.</p>
<p>I tried to figure out how to do this using LayoutParams, but I couldn't succeed.</p>
<p>Thanks.</p> | 11,911,123 | 2 | 0 | null | 2012-08-11 01:02:30.303 UTC | 10 | 2012-08-11 02:01:01.287 UTC | 2012-08-11 02:01:01.287 UTC | null | 1,565,635 | null | 1,234,718 | null | 1 | 21 | android|android-imageview | 44,015 | <p>I think you want something like this:</p>
<pre><code>ImageView imgView = (ImageView) findViewById(R.id.pageImage);
imgView.getLayoutParams().height = 200;
</code></pre>
<p>So first we get the ImageView from the XML. Then getLayoutParams() gets you exactly the params you may edit then. You can set them directly there. The same for the width etc. </p>
<p>About the unit (sp,dp...) I found something here. Hope this helps:</p>
<p><a href="http://androidactivity.wordpress.com/2011/10/04/use-dip-sp-metrics-programmatically/" rel="noreferrer">Use DIP, SP metrics programmatically</a></p>
<p>There they mention, that all units are pixels. In the example he sets the <em>minimum width</em> of 20sp like this:</p>
<pre><code>TextView tv0 = new TextView(this);
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
tv0.setMinimumWidth(px);
</code></pre>
<p>P.S. Here is the complete code I use. Hopefully this is what you want:</p>
<pre><code>package com.example.testproject2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imgView = (ImageView) findViewById(R.id.pageImage);
imgView.getLayoutParams().height = 500;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
</code></pre> |
11,599,461 | C++11 lambda capture by value captures at declaration point | <p>The code below prints 0, but I expect to see a 1. My conclusion is that lambda functions are not invoked by actually passing captured parameters to the functions, which is more intuitive. Am I right or am I missing something?</p>
<pre><code>#include <iostream>
int main(int argc, char **argv){
int value = 0;
auto incr_value = [&value]() { value++; };
auto print_value = [ value]() { std::cout << value << std::endl; };
incr_value();
print_value();
return 0;
}
</code></pre> | 11,599,581 | 3 | 0 | null | 2012-07-22 10:22:46.993 UTC | 7 | 2012-07-22 21:44:53.01 UTC | null | null | null | null | 390,913 | null | 1 | 32 | c++|lambda|c++11 | 15,505 | <p>Lambda functions <strong>are</strong> invoked by actually passing captured parameters to the function.</p>
<p><code>value</code> is equal to 0 at the point where the lambda is defined (and <code>value</code> is captured). Since you are capturing by value, it doesn't matter what you do to <code>value</code> after the capture.</p>
<p>If you had captured <code>value</code> by reference, then you would see a 1 printed because even though the point of capture is still the same (the lambda definition) you would be printing the current value of the captured object and not a copy of it created when it was captured.</p> |
11,665,628 | Read data from CSV file and transform from string to correct data-type, including a list-of-integer column | <p>When I read data back in from a CSV file, every cell is interpreted as a string.</p>
<ul>
<li>How can I automatically convert the data I read in into the correct type?</li>
<li>Or better: How can I tell the csv reader the correct data-type of each column?</li>
</ul>
<p>(I wrote a 2-dimensional list, where each column is of a different type (bool, str, int, list of integer), out to a CSV file.)</p>
<p>Sample data (in CSV file):</p>
<pre class="lang-none prettyprint-override"><code>IsActive,Type,Price,States
True,Cellphone,34,"[1, 2]"
,FlatTv,3.5,[2]
False,Screen,100.23,"[5, 1]"
True,Notebook, 50,[1]
</code></pre> | 32,397,436 | 9 | 9 | null | 2012-07-26 08:49:12.533 UTC | 11 | 2022-03-29 18:32:53.77 UTC | 2019-09-29 01:43:05.35 UTC | null | 202,229 | null | 1,528,248 | null | 1 | 35 | python|csv|python-2.5 | 75,316 | <p>As the <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="noreferrer">docs explain</a>, the CSV reader doesn't perform automatic data conversion. You have the QUOTE_NONNUMERIC format option, but that would only convert all non-quoted fields into floats. This is a very similar behaviour to other csv readers.</p>
<p>I don't believe Python's csv module would be of any help for this case at all. As others have already pointed out, <code>literal_eval()</code> is a far better choice.</p>
<p>The following does work and converts:</p>
<ul>
<li>strings </li>
<li>int</li>
<li>floats</li>
<li>lists</li>
<li>dictionaries</li>
</ul>
<p>You may also use it for booleans and NoneType, although these have to be formatted accordingly for <code>literal_eval()</code> to pass. LibreOffice Calc displays booleans in capital letters, when in Python booleans are Capitalized. Also, you would have to replace empty strings with <code>None</code> (without quotes)</p>
<p>I'm writing an importer for mongodb that does all this. The following is part of the code I've written so far.</p>
<p>[NOTE: My csv uses tab as field delimiter. You may want to add some exception handling too]</p>
<pre><code>def getFieldnames(csvFile):
"""
Read the first row and store values in a tuple
"""
with open(csvFile) as csvfile:
firstRow = csvfile.readlines(1)
fieldnames = tuple(firstRow[0].strip('\n').split("\t"))
return fieldnames
def writeCursor(csvFile, fieldnames):
"""
Convert csv rows into an array of dictionaries
All data types are automatically checked and converted
"""
cursor = [] # Placeholder for the dictionaries/documents
with open(csvFile) as csvFile:
for row in islice(csvFile, 1, None):
values = list(row.strip('\n').split("\t"))
for i, value in enumerate(values):
nValue = ast.literal_eval(value)
values[i] = nValue
cursor.append(dict(zip(fieldnames, values)))
return cursor
</code></pre> |
11,839,655 | Is it possible to adjust a font's vertical scaling using CSS? | <p>I am using an embedded font for the top navigational elements on a site
<code>Helvetica65</code> and at <code>16px</code> it is the perfect WIDTH but I need it to be
about <code>90%</code> of it's current height.</p>
<p>In Photoshop, the solution is simple - adjust the vertical scaling.</p>
<p>Is there a way to do essentially the same thing using CSS? And if so, how
well is it supported?</p>
<p>Here is a <a href="http://jsfiddle.net/Jd5Y7/">jsFiddle</a> of the basic nav coding. </p> | 16,447,826 | 1 | 2 | null | 2012-08-07 05:16:42.517 UTC | 10 | 2017-05-12 20:44:18.917 UTC | 2012-08-07 05:37:20.257 UTC | null | 1,182,982 | null | 1,255,168 | null | 1 | 63 | css|fonts|scaling|embedded-fonts | 57,901 | <p><code>transform</code> property can be used to scale text:</p>
<pre><code>.menu li a {
color: #ffffff;
text-transform: uppercase;
text-decoration: none;
font-family: "HelveticaNeue-Medium", sans-serif;
font-size: 14px;
display: inline-block;
transform: scale(1, 1.5);
-webkit-transform: scale(1, 1.5); /* Safari and Chrome */
-moz-transform: scale(1, 1.5); /* Firefox */
-ms-transform: scale(1, 1.5); /* IE 9+ */
-o-transform: scale(1, 1.5); /* Opera */
}
</code></pre> |
19,854,072 | How to draw a route between two markers in Google Maps API? | <p>I have a requirement where, onclick, I have to draw a route in between two markers when I select. I have successfully uploaded a KML file on Google MAPS API, so the markers are clearly visible on Google MAPS API.</p>
<p>When I select a two markers onclick, there should be a route drawn between the selected markers. I was able to draw a static route between the two points but the line which was getting drawn was not following the route. Please guide.
Also please find the code which I have tried. Thanks in advance.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Transit layer</title>
<style>
html,body,#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js"></script>
<script> function initialize()
{
var myLatlng = new google.maps.LatLng(0, -180);
var mapOptions =
{
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var transitLayer = new google.maps.TransitLayer();
transitLayer.setMap(map);
var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml.parse('kmload.kml');
var geoXml1 = new geoXML3.parser({map: map, singleInfoWindow: true});
geoXml1.parse('lines.kml');
var coordinates = [
new google.maps.LatLng(18.9800, 73.1000),
new google.maps.LatLng(19.0361, 73.0617)];
google.maps.event.addListener(map, "click", function (e)
{
var trainpath = new google.maps.Polyline({
path: coordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
trainpath.setMap(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
</code></pre> | 19,886,552 | 2 | 4 | null | 2013-11-08 07:55:35.81 UTC | 6 | 2016-11-04 05:57:41.74 UTC | 2014-07-21 15:13:09.55 UTC | null | 707,700 | null | 1,309,392 | null | 1 | 13 | javascript|html|google-maps|google-maps-api-3|kml | 52,047 | <p><a href="http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_directions_linktoB.html" rel="nofollow noreferrer">example</a></p>
<p>add a custom "createMarker" function to geoxml3 which adds a function to the marker's click listener to trigger the directions service.</p>
<pre><code>// global variables
var directions = {};
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
// geoxml3 configuration
var geoXml = new geoXML3.parser({
map: map,
createMarker: createMarker,
singleInfoWindow: true
});
// handle the directions service
function processMarkerClick(latLng) {
if (!directions.start) {
directions.start = latLng;
}
else if (!directions.end) {
directions.end = latLng;
directionsService.route({
origin:directions.start,
destination: directions.end,
travelMode: google.maps.TravelMode.DRIVING
},
function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
directionsDisplay.setMap(map);
}
else {
alert("Directions Request failed:" +status);
}
directions.start = null;
directions.end = null;
});
}
}
// custom createMarker function to add hook for the directions service
// (modified from the version in the geoxml3 source)
var createMarker = function (placemark, doc) {
// create a Marker to the map from a placemark KML object
// Load basic marker properties
var markerOptions = geoXML3.combineOptions(geoXml.options.markerOptions, {
map: geoXml.options.map,
position: new google.maps.LatLng(placemark.Point.coordinates[0].lat, placemark.Point.coordinates[0].lng),
title: placemark.name,
zIndex: Math.round(placemark.Point.coordinates[0].lat * -100000)<<5,
icon: placemark.style.icon,
shadow: placemark.style.shadow
});
// Create the marker on the map
var marker = new google.maps.Marker(markerOptions);
if (!!doc) {
doc.markers.push(marker);
}
// Set up and create the infowindow if it is not suppressed
if (!geoXml.options.suppressInfoWindows) {
var infoWindowOptions = geoXML3.combineOptions(geoXml.options.infoWindowOptions, {
content: '<div class="geoxml3_infowindow"><h3>' +
placemark.name +
'</h3><div>' +
placemark.description +
'</div></div>',
pixelOffset: new google.maps.Size(0, 2)
});
if (geoXml.options.infoWindow) {
marker.infoWindow = geoXml.options.infoWindow;
}
else {
marker.infoWindow = new google.maps.InfoWindow(infoWindowOptions);
}
marker.infoWindowOptions = infoWindowOptions;
// Infowindow-opening event handler
google.maps.event.addListener(marker, 'click', function() {
processMarkerClick(marker.getPosition());
this.infoWindow.close();
marker.infoWindow.setOptions(this.infoWindowOptions);
this.infoWindow.open(this.map, this);
});
}
placemark.marker = marker;
return marker;
};
</code></pre> |
20,264,644 | constexpr not compiling in VC2013 | <p>This constexpr code does not compiled in Visual Studio 2013 version 12.0.21005.1 REL</p>
<p>Is there a newer Visual Studio compiler that works with constexpr?</p>
<pre><code>#include <iostream>
constexpr int factorial(int n)
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}
int main(void)
{
const int fact_three = factorial(3);
std::cout << fact_three << std::endl;
return 0;
}
</code></pre>
<p>output from compilation:</p>
<pre> 1>------ Build started: Project: Project1, Configuration: Debug Win32 ------
1> Source.cpp
1>....\source.cpp(3): error C2144: syntax error : 'int' should be preceded by ';'
1>....\source.cpp(3): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========</pre>
<p>Herb Sutter mentions constexpr on his blog but is unclear in what version it works / will work? <a href="http://herbsutter.com/2013/09/09/visual-studio-2013-rc-is-now-available/#comment-13521">http://herbsutter.com/2013/09/09/visual-studio-2013-rc-is-now-available/#comment-13521</a></p> | 20,266,443 | 4 | 6 | null | 2013-11-28 11:14:04.33 UTC | 7 | 2020-09-19 08:06:55.687 UTC | 2016-04-18 23:01:55.547 UTC | null | 1,692,107 | null | 294,569 | null | 1 | 47 | c++|c++11|visual-studio-2013|constexpr | 35,219 | <p>Microsoft publishes a C++11 compatibility table, under which <code>constexpr</code> is <a href="http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx">clearly marked as not being available in Visual Studio 2013</a>.</p>
<p><a href="http://www.microsoft.com/en-us/download/details.aspx?id=41151">The November 2013 CTP</a> has it, though.</p>
<p><sub><strong>Source:</strong> Google <code>visual studio constexpr</code></sub></p> |
20,122,340 | Display amount in format $###,###,###.## using f:convertNumber | <p>I would like to display the amount in <code>$12,050,999.00</code> format.</p>
<p>I tried as follows:</p>
<pre><code><h:outputText value="#{sampleBean.Amount}">
<f:convertNumber pattern="###,###" currencySymbol="$" type="currency"/>
</h:outputText>
</code></pre>
<p>However, it didn't display the amount in the desired format. I got <code>12,050,999</code> instead.</p>
<p>The desired format is shown in the below image:</p>
<p><img src="https://i.stack.imgur.com/gBEir.png" alt="enter image description here"></p>
<p>How can I achieve this?</p> | 20,131,763 | 1 | 7 | null | 2013-11-21 13:30:34.67 UTC | 4 | 2013-11-21 21:30:11.467 UTC | 2013-11-21 14:02:53.623 UTC | null | 157,882 | null | 2,561,626 | null | 1 | 12 | jsf|number-formatting | 48,316 | <p>Your <code>pattern</code> is wrong for a currency. You should be using <code>pattern="¤#,##0.00"</code>.</p>
<pre><code><f:convertNumber pattern="¤#,##0.00" currencySymbol="$" />
</code></pre>
<p>However, there's more at matter: in your original code you also specified the <code>type</code> attribute, which is correct, but this is mutually exclusive with the <code>pattern</code> attribute whereby the <code>pattern</code> attribute gets precedence.</p>
<p>You should actually be omitting the <code>pattern</code> attribute and stick to the <code>type</code> attribute.</p>
<pre><code><f:convertNumber type="currency" currencySymbol="$" />
</code></pre>
<p>Note that this uses the locale as available by <code>UIViewRoot#getLocale()</code> which is expected to be an English/US based locale in order to get the right final format for the USD currency. You'd like to explicitly specify it in either the <code><f:view></code>:</p>
<pre><code><f:view locale="en_US">
</code></pre>
<p>or in the <code>locale</code> attribute of the <code><f:convertNumber></code>:</p>
<pre><code><f:convertNumber type="currency" currencySymbol="$" locale="en_US" />
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/19765009/does-fconvertnumber-use-the-right-number-separator-when-using-patterns-to-for/">Does <f:convertNumber> use the right number separator when using patterns to format currency?</a></li>
</ul> |
19,916,729 | How exactly is Python Bytecode Run in CPython? | <p>I am trying to understand how Python works (because I use it all the time!). To my understanding, when you run something like python script.py, the script is converted to bytecode and then the interpreter/VM/CPython–really just a C Program–reads in the python bytecode and executes the program accordingly.</p>
<p>How is this bytecode read in? Is it similar to how a text file is read in C? I am unsure how the Python code is converted to machine code. Is it the case that the Python interpreter (the python command in the CLI) is really just a precompiled C program that is already converted to machine code and then the python bytecode files are just put through that program? In other words, is my Python program never actually converted into machine code? Is the python interpreter already in machine code, so my script never has to be?</p> | 19,916,892 | 4 | 8 | null | 2013-11-11 21:53:57.927 UTC | 40 | 2021-12-05 21:00:15.69 UTC | 2015-06-07 22:56:16.3 UTC | null | 846,892 | null | 629,599 | null | 1 | 66 | python|cpython|python-internals | 14,967 | <p>Yes, your understanding is correct. There is basically (very basically) a giant switch statement inside the CPython interpreter that says "if the current opcode is so and so, do this and that".</p>
<p><a href="http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790">http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790</a></p>
<p>Other implementations, like Pypy, have JIT compilation, i.e. they translate Python to machine codes on the fly.</p> |
19,910,888 | Type safe physics operations in C++ | <p>Does it make sens in C++ to define physics units as separate types and define valid operations between those types?</p>
<p>Is there any advantage in introducing a lot of types and a lot of operator overloading instead of using just plain floating point values to represent them?</p>
<p>Example:</p>
<pre><code>class Time{...};
class Length{...};
class Speed{...};
...
Time operator""_s(long double val){...}
Length operator""_m(long double val){...}
...
Speed operator/(const Length&, const Time&){...}
</code></pre>
<p>Where <code>Time</code>, <code>Length</code> and <code>Speed</code> can be created only as a return type from different operators?</p> | 19,910,992 | 10 | 12 | null | 2013-11-11 16:12:22.333 UTC | 13 | 2022-02-05 09:47:05.877 UTC | null | null | null | null | 336,578 | null | 1 | 58 | c++|c++11|type-safety | 6,427 | <blockquote>
<p>Does it make sens in C++ to define physics units as separate types and define valid operations between those types?</p>
</blockquote>
<p>Absolutely. The standard Chrono library already does this for time points and durations.</p>
<blockquote>
<p>Is there any advantage in introducing a lot of types and a lot of operator overloading instead of using just plain floating point values to represent them?</p>
</blockquote>
<p>Yes: you can use the type system to catch errors like adding a mass to a distance at compile time, without adding any runtime overhead.</p>
<p>If you don't feel like defining the types and operators yourself, Boost has a <a href="http://www.boost.org/doc/libs/release/doc/html/boost_units.html">Units library</a> for that.</p> |
3,956,636 | C++ on Linux not recognizing commands like exit() and printf() | <p>I get these errors after issuing a g++ command on a .cpp file:
error: ‘exit’ was not declared in this scope
error: ‘printf’ was not declared in this scope</p>
<p>The problem is that when I compiled this program on another linux machine, everything went fine. I tried searching around, but all I found was that I need to include files like 'stdlib.h'.</p>
<p>Could it be I'm missing some library on my OS? If so, what might it be?</p> | 3,956,674 | 4 | 1 | null | 2010-10-18 04:39:18.803 UTC | 5 | 2021-02-27 06:43:33.617 UTC | null | null | null | null | 478,967 | null | 1 | 27 | c++|linux | 46,563 | <p>Recent versions of GCC have gotten stricter in what responsibilities the programmer needs to fulfill. Include the <code>cstdlib</code>, <code>cstdio</code>, etc. header and access these functions from the <code>std</code> namespace.</p> |
3,940,767 | How to get Client location using Google Maps API v3? | <p>How do you get Client location using Google Maps API v3? I tried the following code but kept getting the "google.loader.ClientLocation is null or not an object" error. Any ideas why ??</p>
<pre><code>if (google.loader.ClientLocation) {
alert(google.loader.ClientLocation.latitude+" "+google.loader.ClientLocation.longitude);
}
</code></pre>
<p>Thank You</p> | 4,919,754 | 5 | 0 | null | 2010-10-15 08:52:01.46 UTC | 20 | 2017-08-24 09:05:44.287 UTC | null | null | null | null | 188,477 | null | 1 | 19 | javascript|google-maps | 137,152 | <p>Try this :)</p>
<pre><code> <script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
function initialize() {
var loc = {};
var geocoder = new google.maps.Geocoder();
if(google.loader.ClientLocation) {
loc.lat = google.loader.ClientLocation.latitude;
loc.lng = google.loader.ClientLocation.longitude;
var latlng = new google.maps.LatLng(loc.lat, loc.lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
alert(results[0]['formatted_address']);
};
});
}
}
google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});
</script>
</code></pre> |
3,726,390 | Is that possible to display divs next to each other without floating? | <p>I want to put several <code>div</code>s next to each other in one row. All <code>div</code>s have the same height.</p>
<p><a href="http://jsfiddle.net/fnbVZ/" rel="noreferrer">Here</a> is how this can be done using <code>float: left</code>.</p>
<p>Can this be done without using <code>float</code> ?</p> | 3,726,474 | 5 | 2 | null | 2010-09-16 11:57:37.633 UTC | 4 | 2016-01-01 20:40:49.86 UTC | 2013-11-06 13:36:11.47 UTC | null | 1,457,300 | null | 247,243 | null | 1 | 21 | css|html | 45,716 | <p>Depends, on what you want to do.
You can use <code>display: inline-block;</code></p>
<p><a href="http://jsfiddle.net/sygL9/" rel="noreferrer">http://jsfiddle.net/sygL9/</a></p> |
3,497,168 | Lisp compiler design | <p>I am looking for a compiler design book. I am learning it at college; but lectures were never meant for me. Moreover, at my college they don't do much practical and I believe even if I sincerely do the course about finite automata and compiler design, I will not know how to implement a compiler. So, I am looking for books about implementing a compiler. I find "Modern Compiler Implementation" good. It had three options of language and I chose the C book because C being a small language there will be more for me to do and more to learn during doing. However, I wanted to learn the course designing a compiler for Lisp or python [may be in the same language too]; but I could not find much material available. Lisp is an old language and there should be some documentation about designing a compiler for it. I need your suggestions regarding this.</p>
<p>Thank you.</p> | 3,497,770 | 5 | 5 | null | 2010-08-16 20:45:29.467 UTC | 16 | 2019-05-30 20:44:56.61 UTC | null | null | null | null | 337,461 | null | 1 | 26 | compiler-construction|lisp | 8,977 | <p><a href="http://pagesperso-systeme.lip6.fr/Christian.Queinnec/WWW/LiSP.html" rel="nofollow noreferrer">Lisp in small pieces</a> is probably the best book on implementing Lisp. Highly recommended. Probably available through some used book service. It might be expensive, even as a used book. It is a translation from the French original. There is also a revised version in French, which hasn't been translated to English - unfortunately.</p>
<p>I would also recommend <a href="http://norvig.com/paip.html" rel="nofollow noreferrer">Paradigms of Artificial Intelligence Programming, Case Studies in Common Lisp</a> by Peter Norvig. It contains the description of a Scheme compiler written in Common Lisp. Generally this is an outstanding book.</p>
<p>Also see this Biblography on <a href="https://github.com/scheme-live/library.readscheme.org/blob/master/page8.md" rel="nofollow noreferrer">Scheme implementation techniques</a>.</p>
<p>For Common Lisp there are articles available and some Common Lisp compilers are coming with a little bit of documentation of implementation and compiler internals. Usually the compiler can't be seen in isolation, but should be seen in combination with the runtime it compiles to (GC, instruction sets, memory management in general, threading, FFI interfaces, ...). See for example the <a href="http://common-lisp.net/project/cmucl/doc/CMUCL-design.pdf" rel="nofollow noreferrer">Design of CMU Common Lisp</a>.</p> |
3,626,071 | Retrieve User-Agent programmatically | <p>Is there a way to retrieve Browser's user-agent without having a <code>WebView</code> in activity?</p>
<p>I know it is possible to get it via <code>WebView</code>:</p>
<pre><code>WebView view = (WebView) findViewById(R.id.someview);
String ua = view.getSettings().getUserAgentString() ;
</code></pre>
<p>But in my case I don't have/need a webview object and I don't want to create it just for retrieving user-agent string.</p> | 3,626,156 | 6 | 0 | null | 2010-09-02 10:09:35.137 UTC | 11 | 2017-04-04 12:25:13.79 UTC | 2017-04-04 12:25:13.79 UTC | null | 1,033,581 | null | 283,037 | null | 1 | 43 | android|webview|android-webview|user-agent | 44,338 | <p>If you don't <strong>have</strong> one you can try taking it like this</p>
<pre><code>String ua=new WebView(this).getSettings().getUserAgentString();
</code></pre>
<p>Edit-</p>
<p>The doc for <code>getUserAgentString()</code> says</p>
<p><strong>Return the WebView's user-agent string</strong>. </p>
<p>So i don't think you can get it unless you declare one. Some one correct me if i am wrong</p> |
3,908,171 | JQGrid, change row background color based on condition | <p>I have the following jqgrid that uses the jquery ui theme imported to my master page.</p>
<pre><code> $("#shippingscheduletable").jqGrid({
url: $("#shippingscheduleurl").attr('href'),
datatype: 'json',
mtype: 'GET',
altRows: true,
colNames: ['Dealer', 'Model', 'Invoice', 'Date', 'PO', 'Serial', 'Status', 'City', 'State', 'IsPaid', 'Promo', 'Carrier', 'Int Notes', 'Ord Notes', 'Terms'],
colModel: [
{ name: 'Company', index: 'id', width: 125, align: 'left' },
{ name: 'Model', index: 'Model', width: 50, align: 'left' },
{ name: 'Invoice', index: 'Invoice', width: 50, align: 'left' },
{ name: 'Date', index: 'OrderDate', width: 60, align: 'left' },
{ name: 'Po', index: 'PONum', width: 75, align: 'left' },
{ name: 'Serial', index: 'Serial', width: 50, align: 'left' },
{ name: 'Status', index: 'OrderStatus', width: 70, align: 'left' },
{ name: 'City', index: 'City', width: 100, align: 'left' },
{ name: 'State', index: 'State', width: 30, align: 'left' },
{ name: 'IsPaid', index: 'IsPaid', width: 30, align: 'left' },
{ name: 'Promo', index: 'Promo', width: 50, align: 'left' },
{ name: 'Carrier', index: 'Carrier', width: 80, align: 'left' },
{ name: 'InternalNotes', index: 'InternalNotes', width: 110, align: 'left' },
{ name: 'OrderNotes', index: 'OrderNotes', width: 110, align: 'left' },
{ name: 'Terms', index: 'Terms', width: 60, align: 'left' }
],
pager: jQuery("#shippingschedulepager"),
rowNum: 100,
rowList: [100, 150, 200],
sortname: 'Company',
sortorder: "asc",
viewrecords: true,
height: '700px',
multiselect: true
});
</code></pre>
<p>I would like to change the row color for all rows that have a true value for the IsPaid Field. Is this possible? if so, how would I do this?
I have been researching custom formatting, but I am unsure if this is the correct approach, as I cannot find anything about changing the color of the back ground.</p> | 3,908,232 | 9 | 0 | null | 2010-10-11 16:37:52.083 UTC | 11 | 2018-05-09 05:50:07.29 UTC | 2017-10-31 05:02:30.64 UTC | null | 5,821,989 | null | 359,506 | null | 1 | 29 | jquery|asp.net-mvc|jqgrid | 93,013 | <p>use formatter function :</p>
<p>like in this post</p>
<p><a href="http://www.trirand.net/forum/default.aspx?g=posts&m=2678" rel="noreferrer">http://www.trirand.net/forum/default.aspx?g=posts&m=2678</a></p> |
3,961,217 | How do I format XML in Notepad++? | <p>I have <a href="http://en.wikipedia.org/wiki/Notepad%2B%2B" rel="noreferrer">Notepad++</a> and I got some XML code which is very long. When I pasted it in Notepad++ there was a long line of code (difficult to read and work with).</p>
<p>I want to know if there is a simple way to make the text readable (by readable I mean properly tabbed code).</p>
<p>I can do it manually, but I want a permanent solution to this as I have faced this several times. I am sure there is a way to do this as I have done it once before a couple of years back, maybe with <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio" rel="noreferrer">Visual Studio</a> or some other editor, I don't remember.</p>
<p>But can Notepad++ do it?</p> | 3,961,326 | 21 | 3 | null | 2010-10-18 16:35:02.86 UTC | 213 | 2021-11-09 17:08:53.123 UTC | 2019-04-06 01:35:35.43 UTC | null | 63,550 | null | 162,223 | null | 1 | 1,983 | notepad++|code-formatting | 1,835,977 | <p>Try Plugins -> XML Tools -> Pretty Print (libXML) or (XML only - with line breaks <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Shift</kbd> + <kbd>B</kbd>)</p>
<p>You may need to install XML Tools using your plugin manager in order to get this option in your menu.</p>
<p>In my experience, libXML gives nice output but only if the file is 100% correctly formed.</p> |
8,072,700 | How to restart Jenkins manually? | <p>I've just started working with Jenkins and have run into a problem. After installing several plugins it said it needs to be restarted and went into a "shutting down" mode, but never restarts.</p>
<p>How do I do a manual restart?</p> | 8,077,830 | 31 | 3 | null | 2011-11-09 22:32:22.55 UTC | 217 | 2021-08-12 03:48:45.057 UTC | 2015-06-05 09:52:44.957 UTC | null | 1,305,344 | null | 344,769 | null | 1 | 815 | jenkins | 895,229 | <p>To restart Jenkins manually, you can use either of the following commands (by entering their URL in a browser):</p>
<p><code>(jenkins_url)/safeRestart</code> - Allows all running jobs to complete. New jobs will remain in the queue to run after the restart is complete. </p>
<p><code>(jenkins_url)/restart</code> - Forces a restart without waiting for builds to complete.</p> |
4,764,729 | How do you make a string in PHP with a backslash in it? | <p>I need a backslash to be a part of a string. How can I do it?</p> | 4,764,748 | 3 | 2 | null | 2011-01-21 22:59:37.363 UTC | 12 | 2019-02-25 21:47:25.64 UTC | 2017-02-09 20:54:42.567 UTC | null | 502,381 | null | 539,216 | null | 1 | 37 | php | 101,311 | <p>When the backslash <code>\</code> does not escape the terminating quote of the string or otherwise create a valid escape sequence (in double quoted strings), then either of these work to produce one backslash:</p>
<pre><code>$string = 'abc\def';
$string = "abc\def";
//
$string = 'abc\\def';
$string = "abc\\def";
</code></pre>
<p>When escaping the next character would cause a parse error (terminating quote of the string) or a valid escape sequence (in double quoted strings) then the backslash needs to be escaped:</p>
<pre><code>$string = 'abcdef\\';
$string = "abcdef\\";
$string = 'abc\012';
$string = "abc\\012";
</code></pre> |
4,791,288 | How to export table data to file | <p>I would like to export a single Postgres table's data into a .csv file. Can anyone give me an example of how to do that?</p> | 4,794,414 | 3 | 2 | null | 2011-01-25 08:29:29.853 UTC | 16 | 2020-07-05 15:21:06.193 UTC | 2017-05-11 09:42:17.317 UTC | null | 1,154,642 | null | 582,588 | null | 1 | 57 | postgresql | 103,032 | <p>In psql:</p>
<pre><code>\copy tablename to 'filename' csv;
</code></pre> |
4,295,678 | Understanding the difference between __getattr__ and __getattribute__ | <p>I am trying to understand the difference between <code>__getattr__</code> and <code>__getattribute__</code>, however, I am failing at it.</p>
<p>The <a href="https://stackoverflow.com/a/3278104/3798217">answer</a> to the Stack Overflow question <em><a href="https://stackoverflow.com/q/3278077/3798217">Difference between <code>__getattr__</code> vs <code>__getattribute__</code></a></em> says:</p>
<blockquote>
<p><code>__getattribute__</code> is invoked before looking at the actual attributes on
the object, and so can be tricky to
implement correctly. You can end up in
infinite recursions very easily.</p>
</blockquote>
<p>I have absolutely no idea what that means.</p>
<p>Then it goes on to say:</p>
<blockquote>
<p>You almost certainly want <code>__getattr__</code>.</p>
</blockquote>
<p>Why? </p>
<p>I read that if <code>__getattribute__</code> fails, <code>__getattr__</code> is called. So why are there two different methods doing the same thing? If my code implements the new style classes, what should I use? </p>
<p>I am looking for some code examples to clear this question. I have Googled to best of my ability, but the answers that I found don't discuss the problem thoroughly.</p>
<p>If there is any documentation, I am ready to read that.</p> | 4,295,743 | 4 | 2 | null | 2010-11-28 06:23:07.16 UTC | 113 | 2021-02-20 02:41:22.887 UTC | 2018-06-20 10:12:36.667 UTC | null | 1,485,877 | null | 225,312 | null | 1 | 261 | python|oop|encapsulation|getattr|getattribute | 116,181 | <h1>Some basics first.</h1>
<p>With objects, you need to deal with their attributes. Ordinarily, we do <code>instance.attribute</code>. Sometimes we need more control (when we do not know the name of the attribute in advance).</p>
<p>For example, <code>instance.attribute</code> would become <code>getattr(instance, attribute_name)</code>. Using this model, we can get the attribute by supplying the <em>attribute_name</em> as a string.</p>
<h1>Use of <code>__getattr__</code></h1>
<p>You can also tell a class how to deal with attributes which it doesn't explicitly manage and do that via <code>__getattr__</code> method.</p>
<p>Python will call this method whenever you request an attribute that hasn't already been defined, so you can define what to do with it.</p>
<p>A classic use case:</p>
<pre><code>class A(dict):
def __getattr__(self, name):
return self[name]
a = A()
# Now a.somekey will give a['somekey']
</code></pre>
<h1>Caveats and use of <code>__getattribute__</code></h1>
<p>If you need to catch every attribute <em>regardless whether it exists or not</em>, use <code>__getattribute__</code> instead. The difference is that <code>__getattr__</code> only gets called for attributes that don't actually exist. If you set an attribute directly, referencing that attribute will retrieve it without calling <code>__getattr__</code>.</p>
<p><code>__getattribute__</code> is called all the times.</p> |
4,477,454 | How is a HTTP PUT request typically issued? | <p>I know HTTP PUT is an idempotent request that store something at a specific URI, according to the definition (quoted from the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">rfc</a>)</p>
<pre><code>The PUT method requests that the enclosed entity be stored under the supplied Request-URI.
</code></pre>
<p>But what is the definition of 'enclosed entity'? It doesn't seem possible for me to send form data (like for HTTP POST request) over. What about sending representation of the entity via JSON/XML or in other serialization formats?</p>
<p>In short, how does one send a HTTP PUT request over to store/update info at a specific URI then?</p> | 4,478,672 | 5 | 1 | null | 2010-12-18 09:19:43.993 UTC | 5 | 2019-03-25 06:43:54.1 UTC | null | null | null | null | 5,742 | null | 1 | 21 | http|http-put | 97,657 | <p>The enclosed entity is the payload data contained in the HTTP message body (after any transfer encodings have been removed.) If you're having trouble sending the message body then it could be that you've forgotten to include a Content-Length header - that's one of two ways to indicate that the HTTP message has a body.</p>
<p>PUT is the same as POST except for this semantic difference: With POST the URI identifies a resource that will handle the entity, such as a servlet. With PUT the URI identifies the entity itself, for example a file that will be created/replaced with the contents of the entity body.</p> |
4,797,274 | How to send a status code in PHP, without maintaining an array of status names? | <p>All I want to do, is send a <code>404</code> status code from PHP - but in a generic fashion. Both <code>Router::statusCode(404)</code> and <code>Router::statusCode(403)</code> should work, as well as any other valid HTTP status code.</p>
<p>I do know, that you can specify a status code as third parameter to <a href="http://php.net/header" rel="noreferrer"><code>header</code></a>. Sadly this only works if you specify a <code>string</code>. Thus calling <code>header('', false, 404)</code> does <em>not</em> work.</p>
<p>Furthermore I know, that one can send a status code via a <code>header</code> call with a status line: <code>header('HTTP/1.1 404 Not Found')</code></p>
<p>But to do this I have to maintain an array of reason phrases (<code>Not Found</code>) for all status codes (<code>404</code>). I don't like the idea of this, as it somehow is a duplication of what PHP already does itself (for the third <code>header</code> parameter).</p>
<p>So, my question is: Is there any simple and clean way to send a status code in PHP?</p> | 11,070,412 | 5 | 1 | null | 2011-01-25 18:15:56.293 UTC | 8 | 2020-12-16 06:37:40.913 UTC | null | null | null | null | 385,378 | null | 1 | 34 | php|header|http-status-codes | 69,018 | <p>There is a new function for this in PHP >= 5.4.0 <a href="http://php.net/manual/function.http-response-code.php"><code>http_response_code</code></a></p>
<p>Simply do <code>http_response_code(404)</code>.</p>
<p>If you have a lower PHP version try <code>header(' ', true, 404);</code> (note the whitespace in the string).</p>
<p>If you want to set the reason phrase as well try:</p>
<pre><code>header('HTTP/ 433 Reason Phrase As You Wish');
</code></pre> |
4,181,690 | Choosing the right IOS XML parser | <p>There are a million different XML parsers for the iPhone. I have a medium sized XML file that contains alot of duplicate tags (at different points in the hierarchy). I was thinking about TBXML but I was concerned about its lack of XPath support. For instance lets say my XML file looked like this.</p>
<pre><code><blog>
<author> foo1 </author>
<comments>
<comment>
<text>
<![CDATA[ HTML code that must be extracted ]]>
</text>
<author>foo2</author>
</comment>
<comment>
<text>
<![CDATA[ Here is another post ]]>
</text>
<author>foo1</author>
</comment>
</comments>
</blog>
</code></pre>
<p>Basically my requirements are that I need to be able to extract that cdata. And know whether it is the blog author a comment author.</p> | 4,181,932 | 5 | 0 | null | 2010-11-15 05:36:30.817 UTC | 22 | 2017-09-15 16:12:47.293 UTC | 2017-09-15 16:12:47.293 UTC | null | 1,000,551 | null | 373,722 | null | 1 | 40 | ios|xml|parsing|sdk | 60,812 | <p>Best comparison I've seen on the subject:</p>
<p><a href="http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project">http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project</a> </p>
<p>The difference between the slowest and fastest parsers in his case was a factor of 2. Depending on your feature requirements, there are definitely parsers that can cut your parsing time in half.</p> |
4,199,444 | Functional dependency and normalization | <p>I am trying to find a great resource to study for functional dependency and normalization. </p>
<p>Anyone have any idea where should I look to? I am having difficulty differentiating whether a FD is in 1NF, 2NF or 3NF? </p>
<p>I've been reading Wikipedia and used Google search to find good research, but can't find any that explains it in simple terms. </p>
<p>Maybe you all can share on how you learned FD's and normalization during your life as well.</p> | 4,217,663 | 6 | 0 | null | 2010-11-16 21:57:24.757 UTC | 12 | 2022-07-15 11:04:32.373 UTC | 2019-01-14 23:43:01.51 UTC | null | 3,404,097 | null | 95,265 | null | 1 | 18 | database|database-normalization|functional-dependencies | 60,735 | <p>A functional dependency defines a functional relationship between attributes. For example: <code>PersonId</code> functionally determines <code>BirthDate</code> (normally written as <code>PersonId -> BirthDate</code>). Another way of saying this is: There is exactly one Birth Date for any given instance of a person. Note that the converse may or may not be true. Many people may have been born on the same day. Given a <code>BirthDate</code> we may find many <code>PersonId</code> sharing that date.</p>
<p>Sets of functional dependencies may be used to synthesize relations (tables). The definition of
the first 3 normal forms, including Boyce Codd Normal Form (BCNF) is stated in terms of
how a given set of relations represent functional dependencies. Fourth and fifth normal forms involve Multi-Valued dependencies (another kettle of fish).</p>
<p>Here are a few free resources about Functional Dependencies, Normalization and database design.
Be prepared to exercise your brain and math skills when studying this material.</p>
<p>The following are "slide shows" from various academic sites...</p>
<ul>
<li><a href="https://webhome.cs.uvic.ca/%7Ethomo/csc370/functional-dep2.ppt" rel="nofollow noreferrer">Functional Dependencies</a></li>
<li><a href="https://cs.gmu.edu/%7Eaobaidi/spring-02/Normalization.ppt" rel="nofollow noreferrer">Functional Dependencies and Normalization for Relational Databases</a></li>
<li><a href="https://web.archive.org/web/20100801142526/http://myweb.lmu.edu/dondi/share/db/fd-theory.pdf" rel="nofollow noreferrer">The Relational Data Model: Functional-Dependency Theory</a></li>
</ul>
<p>The following are academic papers. Heavier reading but well worth the effort.</p>
<ul>
<li><a href="https://watermark.silverchair.com/25-1-68.pdf?token=AQECAHi208BE49Ooan9kkhW_Ercy7Dm3ZL_9Cf3qfKAc485ysgAAAsIwggK-BgkqhkiG9w0BBwagggKvMIICqwIBADCCAqQGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMwpoGasMz9Dka07vFAgEQgIICdV-VGDNReZ-XrDCpiZRZHPVndN3hV3tJISvgHOfqyiQfeUQutLnYiHw8Yy-jtpR4CwenTc3bCZ767WzJYiMRf9dzWBSS04ElNzWKyAst5Un8V9PkwvZg1tn--Tlipgc8BMdPqQna-YQEu41-1hm1S7u0GWS1aWxPes76NJ3Vbzl77tdLBQ1MupqHaP_Gx8gyhTDRRSut-39B8PS9L5mnUVGXk4QsO1Dn-2ywQWNkfGIwggzustW_rbDTNTi7YVbfrU5cMgaTGA3gmKEB8RegaFhGNuqv_7zwiCSDokEtemiEfhbw1ImgtXbOQuRj06px-PMzTJ2iwI6qKTr-so3TtK52UbMpmwWzhjD9Mn08HIaodu0jATf_vljAwwExm-5l8mBDegI99nm3O39dWPsFg6RSZXX_mzrvLLmDgkf0g4XGEvdiNxumcSCj1PpKAPDLAUHG1JFrf6X--MxiiBU3qQ7Makjck9CCGVnjn0lMMbZIOyUjoalwF0ZyM5qbIztG8d2pOGoiCvg5CIUMvWQc8ozEbhtk8Ke3WjVv0uxyEVvleXv2ke71NSnmDZf1Ai6xkMB87yOgoVElyIoNNp2Ln6_1AI-bLKTCH-jB3b230dUZ_li3ZGb2m8aFjf0fYXWT2BOIAPAyXtOhQKVr4Ey7L3Z6JiOuyPeIS0E6O7kaM5NMr_XKjPo4sc0XX7x-FTnMs0Y8Dl-sFmVVMbAM61nyGbWtq5PNBJik0gKGYcZRlLyfEg52tpYQXnlSFRR-ivtjOXguKm1Pg--bwCEQDTAllPcCEffyODajISOwa05Jti50iUbnB2YFsZLnLT6qnCJTnpyvtWJ_" rel="nofollow noreferrer">The Application of Functional Dependency Theory to Relational Databases</a></li>
<li><a href="https://web.archive.org/web/20170922003307/http://www.mathe2.uni-bayreuth.de/axel/papers/kent:a_simple_guide_to_five_normal_forms_in_relational_database_theory.pdf" rel="nofollow noreferrer">A Simple Guide to Five Normal Forms in Relational Database</a></li>
<li><a href="https://web.archive.org/web/20090220214149/http://www.almaden.ibm.com:80/cs/people/fagin/tods92.pdf" rel="nofollow noreferrer">Simple Conditions for Guaranteeing Higher Normal Forms in Relational Databases</a></li>
</ul>
<p>If you are seriously interested in this subject I suggest you put out the cash for a good book
on the subject of Relational Database Design. For example: <a href="https://rads.stackoverflow.com/amzn/click/com/0321197844" rel="nofollow noreferrer" rel="nofollow noreferrer">An Introduction to Database Systems by C.J. Date</a></p> |
4,611,525 | Execute current UITextField autocorrect suggestion when another button is pressed | <p>I am implementing chat in my application, very similar to the iPhone's built-in Messages app. I have a UITextField next to a button. The user types something into the text field, and very often the text field suggests various autocorrections. In the built-in Messages app, tapping the Send button will cause the currently visible autocorrection suggestion to execute. I am seeking this behavior in my application, but haven't been able to find anything.</p>
<p>Does anyone know of a way to programmatically execute the currently visible autocorrection/autocomplete suggestion of a UITextField when a completely separate control is activated? It's obviously possible somehow.</p> | 4,611,546 | 6 | 0 | null | 2011-01-06 03:42:57.687 UTC | 6 | 2015-04-27 09:49:01.233 UTC | null | null | null | null | 453,284 | null | 1 | 30 | iphone|ios|uitextfield | 5,905 | <p>Call <code>-resignFirstResponder</code> on the field. That forces it to accept the autocorrect. If you don't want to dismiss the keyboard, you can immediately follow that with a call to <code>-becomeFirstResponder</code> again.</p> |
4,117,002 | Why can I access private variables in the copy constructor? | <p>I have learned that I can never access a private variable, only with a get-function in the class. But then why can I access it in the copy constructor?</p>
<p>Example:</p>
<pre><code>Field::Field(const Field& f)
{
pFirst = new T[f.capacity()];
pLast = pFirst + (f.pLast - f.pFirst);
pEnd = pFirst + (f.pEnd - f.pFirst);
std::copy(f.pFirst, f.pLast, pFirst);
}
</code></pre>
<p>My declaration:</p>
<pre><code>private:
T *pFirst,*pLast,*pEnd;
</code></pre> | 17,721,201 | 6 | 0 | null | 2010-11-07 08:30:28.113 UTC | 50 | 2021-11-28 01:19:40.537 UTC | 2010-11-08 10:57:04.047 UTC | Roger Pate | null | null | 499,126 | null | 1 | 102 | c++|private|access-specifier | 32,877 | <p>IMHO, existing answers do a poor job explaining the "Why" of this - focusing too much on reiterating what behaviour's valid. "access modifiers work on class level, and not on object level." - yes, but why?</p>
<p>The overarching concept here is that it's the programmer(s) designing, writing and maintaining a class who is(are) expected to understand the OO encapsulation desired and empowered to coordinate its implementation. So, if you're writing <code>class X</code>, you're encoding not just how an individual <code>X x</code> object can be used by code with access to it, but also how:</p>
<ul>
<li>derived classes are able to interact with it (through optionally-pure virtual functions and/or protected access), and</li>
<li>distinct <code>X</code> objects <em>cooperate</em> to provide intended behaviours while honouring the post-conditions and invariants from your design.</li>
</ul>
<p>It's not just the copy constructor either - a great many operations can involve two or more instances of your class: if you're comparing, adding/multiplying/dividing, copy-constructing, cloning, assigning etc. then it's often the case that you either simply must have access to private and/or protected data in the other object, or want it to allow a simpler, faster or generally better function implementation.</p>
<p>Specifically, these operations may want to take advantage of priviledged access to do things like:</p>
<ul>
<li>(copy constructors) use a private member of the "rhs" (right hand side) object in an initialiser list, so that a member variable is itself copy-constructed instead of default-constructed (if even legal) then assigned too (again, if legal)</li>
<li>share resources - file handles, shared memory segments, <code>shared_ptr</code>s to reference data etc.</li>
<li>take ownership of things, e.g. <code>auto_ptr<></code> "moves" ownership to the object under construction</li>
<li>copy private "cache", calibration, or state members needed to construct the new object in an optimally usable state without having to regenerate them from scratch</li>
<li>copy/access diagnostic/trace information kept in the object being copied that's not otherwise accessible through public APIs but might be used by some later exception object or logging (e.g. something about the time/circumstances when the "original" non-copy-constructed instance was constructed)</li>
<li>perform a more efficient copy of some data: e.g. objects may have e.g. an <code>unordered_map</code> member but publicly only expose <code>begin()</code> and <code>end()</code> iterators - with direct access to <code>size()</code> you could <code>reserve</code> capacity for faster copying; worse still if they only expose <code>at()</code> and <code>insert()</code> and otherwise <code>throw</code>....</li>
<li>copy references back to parent/coordination/management objects that might be unknown or write-only for the client code</li>
</ul> |
4,580,727 | Override jQuery UI Datepicker div visible strangely on first page load. | <p>Something strange afoot, here:</p>
<p>An instance of Datepicker is showing up in a weird place as a single bar in the upper left hand corner of <a href="http://bigsilkdesign.com/comida/#&panel1-1" rel="noreferrer">this</a> page.</p>
<p>I'm using both jQuery UI's Datepicker and Accordion on a page. In the CSS for the UI, the <code>display:none</code> for Datepicker seems to be overridden by the <code>display:block</code> for the Accordion, at least according to Firebug (see img below).</p>
<p>Then, once the Datepicker trigger is clicked in the 'catering/event room' tab (click one of the buttons to show div with Datepicker,) the <code>display:none</code> seems to then work.</p>
<p>Here's what the bad div looks like:</p>
<p><img src="https://i.stack.imgur.com/JoCv1.jpg" alt="bad div"></p>
<p>and here's the Firebug panel:</p>
<p><img src="https://i.stack.imgur.com/3gcS3.jpg" alt="css"></p> | 10,412,148 | 7 | 1 | null | 2011-01-02 21:55:11.11 UTC | 3 | 2016-01-21 11:39:42.857 UTC | 2013-10-18 11:45:05.883 UTC | null | 2,681,246 | null | 282,302 | null | 1 | 33 | css|jquery-ui|datepicker|accordion | 24,539 | <p>I had the same problem and while some of the above solutions work, the easiest fix of all is to add this to your css:</p>
<pre><code>#ui-datepicker-div {display: none;}
</code></pre>
<p>This basically hides the realigned datepicker element when it cannot be binded to an existing invisible element. You hide it, but it will be initialized again when you click on an element that needs to display the datepicker. Upon re-initialization, the datepicker element with id <code>#ui-datepicker-div</code> will have the correct position.</p> |
4,564,155 | How to get the number of columns of worksheet as integer (28) instead of Excel-letters ("AB")? | <p>Given:</p>
<pre><code>$this->objPHPExcelReader = PHPExcel_IOFactory::createReaderForFile($this->config['file']);
$this->objPHPExcelReader->setLoadSheetsOnly(array($this->config['worksheet']));
$this->objPHPExcelReader->setReadDataOnly(true);
$this->objPHPExcel = $this->objPHPExcelReader->load($this->config['file']);
</code></pre>
<p>I can iterate through the rows like this but it is <strong>very slow</strong>, i.e. in a 3MB Excel file with a worksheet that has <strong>"EL" columns</strong>, it takes about <strong>1 second per row</strong>:</p>
<pre><code>foreach ($this->objPHPExcel->setActiveSheetIndex(0)->getRowIterator() as $row)
{
$dataset = array();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
foreach ($cellIterator as $cell)
{
if (!is_null($cell))
{
$dataset[] = $cell->getCalculatedValue();
}
}
$this->datasets[] = $dataset;
}
</code></pre>
<p>When I iterate like this, it it significantly faster (approx. 2000 rows in 30 seconds), but I will have to convert the letters e.g. "EL" to a number:</p>
<pre><code>$highestColumm = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); // e.g. "EL"
$highestRow = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$number_of_columns = 150; // TODO: figure out how to get the number of cols as int
for ($row = 1; $row < $highestRow + 1; $row++) {
$dataset = array();
for ($column = 0; $column < $number_of_columns; $column++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCellByColumnAndRow($column, $row)->getValue();
}
$this->datasets[] = $dataset;
}
</code></pre>
<p><strong>Is there a way to get the highest column as an integer (e.g. "28") instead of in Excel-styled letters (e.g. "AB")?</strong></p> | 4,566,410 | 7 | 0 | null | 2010-12-30 16:08:14.853 UTC | 18 | 2022-06-11 20:46:46 UTC | 2015-09-04 02:13:47.977 UTC | null | 1,505,120 | null | 4,639 | null | 1 | 40 | php|phpexcel | 68,387 | <pre><code>$colNumber = PHPExcel_Cell::columnIndexFromString($colString);
</code></pre>
<p>returns 1 from a $colString of 'A', 26 from 'Z', 27 from 'AA', etc.</p>
<p>and the (almost) reverse</p>
<pre><code>$colString = PHPExcel_Cell::stringFromColumnIndex($colNumber);
</code></pre>
<p>returns 'A' from a $colNumber of 0, 'Z' from 25, 'AA' from 26, etc.</p>
<p><strong>EDIT</strong></p>
<p>A couple of useful tricks:</p>
<p>There is a toArray() method for the worksheet class:</p>
<pre><code>$this->datasets = $this->objPHPExcel->setActiveSheetIndex(0)->toArray();
</code></pre>
<p>which accepts the following parameters:</p>
<pre><code>* @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
* @param boolean $calculateFormulas Should formulas be calculated?
* @param boolean $formatData Should formatting be applied to cell values?
* @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero
* True - Return rows and columns indexed by their actual row and column IDs
</code></pre>
<p>although it does use the iterators, so would be slightly slower</p>
<p>OR</p>
<p>Take advantage of PHP's ability to <a href="http://www.php.net/manual/en/language.operators.increment.php" rel="noreferrer">increment character strings Perl Style</a></p>
<pre><code>$highestColumm = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); // e.g. "EL"
$highestRow = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$highestColumm++;
for ($row = 1; $row < $highestRow + 1; $row++) {
$dataset = array();
for ($column = 'A'; $column != $highestColumm; $column++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($column . $row)->getValue();
}
$this->datasets[] = $dataset;
}
</code></pre>
<p>and if you're processing a large number of rows, you might actually notice the performance improvement of ++$row over $row++</p> |
4,740,419 | Parentheses in Python Conditionals | <p>I have a simple question regarding the use of parentheses in Python's conditional statements.</p>
<p>The following two snippets work just the same but I wonder if this is only true because of its simplicity:</p>
<pre><code>>>> import os, socket
>>> if ((socket.gethostname() == "bristle") or (socket.gethostname() == "rete")):
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
</code></pre>
<p>and now without parentheses</p>
<pre><code>>>> import os, socket
>>> if socket.gethostname() == "bristle" or socket.gethostname() == "rete":
... DEBUG = False
... else:
... DEBUG = True
...
>>> DEBUG
</code></pre>
<p>Could anyone help shed some light on this? Are there any cases where I should definitely use them?</p> | 4,740,493 | 7 | 0 | null | 2011-01-19 20:37:38.387 UTC | 8 | 2022-08-15 02:53:10.603 UTC | 2020-08-11 16:09:24.627 UTC | null | 10,251,345 | null | 352,452 | null | 1 | 47 | python|conditional-statements|parentheses | 101,551 | <p>The other answers that Comparison takes place before Boolean are 100% correct. As an alternative (for situations like what you've demonstrated) you can also use this as a way to combine the conditions:</p>
<pre><code>if socket.gethostname() in ('bristle', 'rete'):
# Something here that operates under the conditions.
</code></pre>
<p>That saves you the separate calls to socket.gethostname and makes it easier to add additional possible valid values as your project grows or you have to authorize additional hosts.</p> |
4,534,146 | Properly removing an Integer from a List<Integer> | <p>Here's a nice pitfall I just encountered.
Consider a list of integers:</p>
<pre><code>List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);
</code></pre>
<p>Any educated guess on what happens when you execute <code>list.remove(1)</code>? What about <code>list.remove(new Integer(1))</code>? This can cause some nasty bugs.</p>
<p>What is the proper way to differentiate between <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#remove(int)" rel="noreferrer"><code>remove(int index)</code></a>, which removes an element from given index and <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/List.html#remove(java.lang.Object)" rel="noreferrer"><code>remove(Object o)</code></a>, which removes an element by reference, when dealing with lists of integers?</p>
<hr>
<p>The main point to consider here is the one <a href="https://stackoverflow.com/questions/4534146/properly-removing-an-integer-from-a-listinteger/4534152#4534152">@Nikita mentioned</a> - exact parameter matching takes precedence over auto-boxing.</p> | 4,534,196 | 8 | 1 | null | 2010-12-26 14:25:35.85 UTC | 42 | 2020-07-27 15:57:18.607 UTC | 2017-05-23 10:31:28.05 UTC | null | -1 | null | 24,545 | null | 1 | 215 | java|collections|overloading | 89,085 | <p>Java always calls the method that best suits your argument. Auto boxing and implicit upcasting is only performed if there's no method which can be called without casting / auto boxing.</p>
<p>The List interface specifies two remove methods (please note the naming of the arguments):</p>
<ul>
<li><code>remove(Object o)</code></li>
<li><code>remove(int index)</code></li>
</ul>
<p>That means that <code>list.remove(1)</code> removes the object at position 1 and <code>remove(new Integer(1))</code> removes the first occurrence of the specified element from this list.</p> |
4,437,291 | What is java interface equivalent in Ruby? | <p>Can we expose interfaces in Ruby like we do in java and enforce the Ruby modules or classes to implement the methods defined by interface. </p>
<p>One way is to use inheritance and method_missing to achieve the same but is there any other more appropriate approach available ?</p> | 4,439,733 | 10 | 5 | null | 2010-12-14 08:40:09.53 UTC | 34 | 2021-12-20 17:15:15.54 UTC | null | null | null | null | 531,897 | null | 1 | 120 | ruby|interface | 66,738 | <p>Ruby has <em>Interfaces</em> just like any other language.</p>
<p>Note that you have to be careful not to conflate the concept of the <em>Interface</em>, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the <code>interface</code> which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.</p>
<p>It is very important to distinguish the two. What's important is the <em>Interface</em>, not the <code>interface</code>. The <code>interface</code> tells you pretty much nothing useful. Nothing demonstrates this better than the <em>marker interfaces</em> in Java, which are interfaces that have no members at all: just take a look at <a href="http://Download.Oracle.Com/javase/7/docs/api/java/io/Serializable.html" rel="noreferrer"><code>java.io.Serializable</code></a> and <a href="http://Download.Oracle.Com/javase/7/docs/api/java/lang/Cloneable.html" rel="noreferrer"><code>java.lang.Cloneable</code></a>; those two <code>interface</code>s mean <em>very</em> different things, yet they have the <em>exact same</em> signature.</p>
<p>So, if two <code>interface</code>s that mean different things, have the same signature, what <em>exactly</em> is the <code>interface</code> even guaranteeing you?</p>
<p>Another good example:</p>
<pre class="lang-java prettyprint-override"><code>package java.util;
interface List<E> implements Collection<E>, Iterable<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException;
}
</code></pre>
<p>What is the <em>Interface</em> of <code>java.util.List<E>.add</code>?</p>
<ul>
<li>that the length of the collection does not decrease</li>
<li>that all the items that were in the collection before are still there</li>
<li>that <code>element</code> is in the collection</li>
</ul>
<p>And which of those actually shows up in the <code>interface</code>? None! There is nothing in the <code>interface</code> that says that the <code>Add</code> method must even <em>add</em> at all, it might just as well <em>remove</em> an element from the collection.</p>
<p>This is a perfectly valid implementation of that <code>interface</code>:</p>
<pre class="lang-java prettyprint-override"><code>class MyCollection<E> implements java.util.List<E> {
void add(int index, E element)
throws UnsupportedOperationException, ClassCastException,
NullPointerException, IllegalArgumentException,
IndexOutOfBoundsException {
remove(element);
}
}
</code></pre>
<p>Another example: where in <a href="http://Download.Oracle.Com/javase/7/docs/api/java/util/Set.html" rel="noreferrer"><code>java.util.Set<E></code></a> does it actually say that it is, you know, a <em>set</em>? Nowhere! Or more precisely, in the documentation. In English.</p>
<p>In pretty much all cases of <code>interfaces</code>, both from Java and .NET, all the <em>relevant</em> information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.</p>
<p>Note that there are <em>other</em> languages in which the <em>Interface</em> can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the <em>Interface</em> "<code>interface</code>", they call it <code>type</code>. In a dependently-typed programming language, you can, for example, express the properties that a <code>sort</code> function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.</p>
<p>So, in short: Ruby does not have an equivalent to a Java <code>interface</code>. It <em>does</em>, however, have an equivalent to a Java <em>Interface</em>, and it's exactly the same as in Java: documentation.</p>
<p>Also, just like in Java, <em>Acceptance Tests</em> can be used to specify <em>Interfaces</em> as well.</p>
<p>In particular, in Ruby, the <em>Interface</em> of an object is determined by what it can <em>do</em>, not what <code>class</code> is is, or what <code>module</code> it mixes in. Any object that has a <code><<</code> method can be appended to. This is very useful in unit tests, where you can simply pass in an <code>Array</code> or a <code>String</code> instead of a more complicated <code>Logger</code>, even though <code>Array</code> and <code>Logger</code> do not share an explicit <code>interface</code> apart from the fact that they both have a method called <code><<</code>.</p>
<p>Another example is <a href="http://RubyDoc.Info/docs/ruby-stdlib/1.9.2/StringIO/" rel="noreferrer"><code>StringIO</code></a>, which implements the same <em>Interface</em> as <code>IO</code> and thus a large portion of the <em>Interface</em> of <code>File</code>, but without sharing any common ancestor besides <code>Object</code>.</p> |
4,770,133 | rails - REGEX for email validation | <p>I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:</p>
<pre><code>def is_a_valid_email?(email)
email_regex = %r{
^ # Start of string
[0-9a-z] # First character
[0-9a-z.+]+ # Middle characters
[0-9a-z] # Last character
@ # Separating @ character
[0-9a-z] # Domain name begin
[0-9a-z.-]+ # Domain name middle
[0-9a-z] # Domain name end
$ # End of string
}xi # Case insensitive
(email =~ email_regex)
end
</code></pre>
<p>Problem with the above is <code>[email protected]</code> does not return as valid when it should be. Any thoughts or suggestions for a better regex?</p>
<p>Thanks</p> | 4,770,175 | 15 | 2 | null | 2011-01-22 19:44:21.467 UTC | 9 | 2021-08-09 10:58:38.13 UTC | 2011-01-22 19:47:02.14 UTC | null | 52,162 | null | 149,080 | null | 1 | 19 | ruby-on-rails|regex|ruby-on-rails-3 | 61,962 | <p>My shot at this (see comment and link above):</p>
<pre><code>^.+@.+$
</code></pre> |
4,086,107 | Fixed page header overlaps in-page anchors | <p>If I have a non-scrolling header in an HTML page, fixed to the top, having a defined height:</p>
<p>Is there a way to use the URL anchor (the <code>#fragment</code> part) to have the browser scroll to a certain point in the page, but still respect the height of the fixed element <strong>without the help of JavaScript</strong>?</p>
<pre class="lang-none prettyprint-override"><code>http://example.com/#bar
</code></pre>
<pre>
WRONG (but the common behavior): CORRECT:
+---------------------------------+ +---------------------------------+
| BAR///////////////////// header | | //////////////////////// header |
+---------------------------------+ +---------------------------------+
| Here is the rest of the Text | | BAR |
| ... | | |
| ... | | Here is the rest of the Text |
| ... | | ... |
+---------------------------------+ +---------------------------------+
</pre> | 13,117,744 | 37 | 6 | null | 2010-11-03 10:31:11.337 UTC | 162 | 2022-06-19 03:42:29.78 UTC | 2021-02-16 16:23:47.653 UTC | null | 2,680,216 | null | 18,771 | null | 1 | 499 | html|url|anchor | 246,000 | <p>I had the same problem.
I solved it by adding a class to the anchor element with the topbar height as the padding-top value.</p>
<pre><code><h1><a class="anchor" name="barlink">Bar</a></h1>
</code></pre>
<p>I used this CSS:</p>
<pre><code>.anchor { padding-top: 90px; }
</code></pre> |
14,735,085 | Clicking a JLabel to open a new frame | <p>I am designing the graphics for a game i am programming, i wanted to know if there is an easy way of opening a frame when a JLabel is cliked? </p>
<p>Is there easy code for this?</p>
<p><img src="https://i.stack.imgur.com/9Ij2Y.png" alt="enter image description here"></p> | 14,735,155 | 5 | 3 | null | 2013-02-06 17:24:00.43 UTC | 3 | 2013-02-06 17:50:25.59 UTC | 2013-02-06 17:42:34.137 UTC | null | 714,968 | null | 1,992,697 | null | 1 | 15 | java|swing|frame|jlabel|mouselistener | 50,915 | <p>Implement <code>MouseListener</code> interface and use it <code>mouseClicked</code> method to handle the clicks on the JLabel. </p>
<pre><code>label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
// you can open a new frame here as
// i have assumed you have declared "frame" as instance variable
frame = new JFrame("new frame");
frame.setVisible(true);
}
});
</code></pre> |
14,703,646 | jQuery - how to use the "on()" method instead of "live()"? | <p>I used <code>live()</code> for generated pages and frames. But in <code>jQuery 1.9</code> this function is deprecated and does not work.</p>
<p>I use <code>on()</code> instead of <code>live()</code> but this method works for one time, and does not work in frames.</p>
<p>My code looks like this:</p>
<pre><code> $("#element").live('click',function(){
$("#my").html(result);
});
</code></pre>
<p>What is the solution?</p> | 14,703,668 | 1 | 2 | null | 2013-02-05 09:06:09.113 UTC | 5 | 2015-02-25 06:46:42.373 UTC | 2015-02-25 06:46:42.373 UTC | null | 584,192 | null | 786,928 | null | 1 | 26 | javascript|deprecated|jquery|jquery-on | 49,014 | <pre><code>$('body').on('click', '#element', function(){
$("#my").html(result);
});
</code></pre>
<p>The clicked element selector is now passed through the <code>.on()</code> function parameters, and the previous selector should be replaced with the closest parent selector preferably with an ID. If you do not know what parent selector to use, <code>body</code> works too, but is less efficient.</p>
<p>see <a href="https://stackoverflow.com/q/14354040/584192">jQuery 1.9 .live() is not a function</a> on how to migrate existing code.</p> |
14,395,239 | Class 'DOMDocument' not found | <p>I've found an error on a page in my Magento application; it always show this message error when I visit it:</p>
<blockquote>
<p>Fatal error: Class 'DOMDocument' not found in /home/.../lib/Zend/Feed/Abstract.php on line 95</p>
</blockquote>
<p>Can you give me a solution? I'm using magento 1.4.1.1.</p> | 14,395,414 | 19 | 3 | null | 2013-01-18 08:48:33.01 UTC | 32 | 2022-07-11 06:49:57.743 UTC | 2022-07-11 06:49:57.743 UTC | null | 343,302 | null | 1,477,136 | null | 1 | 284 | php|xml|magento-1.4 | 280,079 | <p>You need to install the <a href="http://www.php.net/en/dom" rel="noreferrer">DOM</a> extension. You can do so on Debian / Ubuntu using:</p>
<pre><code>sudo apt-get install php-dom
</code></pre>
<p>And on Centos / Fedora / Red Hat:</p>
<pre><code>yum install php-xml
</code></pre>
<p>If you get conflicts between PHP packages, you could try to see if the specific PHP version package exists instead: e.g. <code>php53-xml</code> if your system runs PHP5.3.</p> |
14,602,072 | Styling notification InboxStyle | <p>I try to implement an extendable notification and I have used the <a href="http://developer.android.com/reference/android/support/v4/app/NotificationCompat.InboxStyle.html" rel="noreferrer">InboxStyle</a> for that.</p>
<p>Based on the following image from the <a href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html#BigNotify" rel="noreferrer">documentation</a>:</p>
<p><img src="https://i.stack.imgur.com/tmEU6.png" alt="inboxstyle notification"></p>
<p>it should be possible to style the text. In this case make "Google Play" bold.</p>
<p>InboxStyle has only <code>addLine()</code> where I can pass a CharSequence. I tried with <code>Html.fromHtml()</code> and used some html formatting but I couldn't succeed.</p>
<pre><code>NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("title");
inboxStyle.setSummaryText("summarytext");
// fetch push messages
synchronized (mPushMessages) {
HashMap<String, PushMessage> messages = mPushMessages.get(key);
if (messages != null) {
for (Entry<String, PushMessage> msg : messages.entrySet()) {
inboxStyle.addLine(Html.fromHtml("at least <b>one word</b> should be bold!");
}
builder.setStyle(inboxStyle);
builder.setNumber(messages.size());
}
}
</code></pre>
<p>Any idea about this?</p> | 21,661,375 | 5 | 0 | null | 2013-01-30 10:43:34.457 UTC | 8 | 2016-04-26 19:07:56.79 UTC | null | null | null | null | 180,538 | null | 1 | 31 | android|notifications | 26,353 | <p>You don't need to use <code>fromHtml</code>. I've had issues with <code>fromHtml</code> in the past (when what you display comes from user, code injection can result in ugly things). Also, I don't like putting formatting elements in <code>strings.xml</code> (if you use services for translation, they might screw up your HTML tags).</p>
<p>The <code>addLine</code> method, as most methods to set text in notifications (<code>setTicker</code>, <code>setContentInfo</code>, <code>setContentTitle</code>, etc.) take a <code>CharSequence</code> as parameter.</p>
<p>So you can pass a <code>Spannable</code>. Let's say you want "<strong>Bold</strong> this and <em>italic</em> that.", you can format it this way (of course don't hardcode positions):</p>
<pre><code>Spannable sb = new SpannableString("Bold this and italic that.");
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 14, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
inboxStyle.addLine(sb);
</code></pre>
<p>Now if you need to build string dynamically with localized strings, like "Today is <strong>[DAY]</strong>, good morning!", put string with a placeholder in <code>strings.xml</code>:</p>
<pre><code><string name="notification_line_format">Today is %1$s, good morning!</string>
</code></pre>
<p>Then format this way:</p>
<pre><code>String today = "Sunday";
String lineFormat = context.getString(R.string.notification_line_format);
int lineParamStartPos = lineFormat.indexOf("%1$s");
if (lineParamStartPos < 0) {
throw new InvalidParameterException("Something's wrong with your string! LINT could have caught that.");
}
String lineFormatted = context.getString(R.string.notification_line_format, today);
Spannable sb = new SpannableString(lineFormatted);
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), lineParamStartPos, lineParamStartPos + today.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
inboxStyle.addLine(sb);
</code></pre>
<p>You'll get "Today is <strong>Sunday</strong>, good morning!", and as far as I know it works with all versions of Android.</p> |
14,672,302 | How do I remove the selected tab indicator from the TabWidget? | <p>Here's what I'd like to remove :</p>
<p><img src="https://i.stack.imgur.com/y4yaV.png" alt="enter image description here"></p>
<p>How do I replace the indicator showing which tab is currently shown as well as the blue line that spans the entire tabwidget?</p>
<p>To Specify: All I want indicating which tab is selected is this : </p>
<ul>
<li>tab_button_active.9.png should be shown as background if the tab is SELECTED</li>
<li>tab_button_inactive.9.png should be shown as the background if the tab is NOT SELECTED. </li>
</ul>
<p>edit : Setting tabStripEnabled to false has no effect. Adding a style to it and having "@android:style/Widget.Holo.ActionBar" as its parent is also not possible since im targetting API level 7 and the ActionBar was implemented in API level 11.</p> | 15,261,139 | 17 | 2 | null | 2013-02-03 12:09:31.27 UTC | 6 | 2020-09-28 12:52:27.553 UTC | 2013-02-28 17:05:39.783 UTC | null | 1,126,097 | null | 1,126,097 | null | 1 | 36 | android | 48,545 | <p>If <code>android:tabStripEnabled="false"</code> did not work then I also assume calling <code>setStripEnabled(boolean stripEnabled)</code> will have no effect as well. If all of this is true then your problem is probably not in TabWidget.</p>
<p>I would suggest looking at your tab indicator. Try these modifications. This code is taken from a fragment that has tabs.</p>
<p>Here is the code that creates the tab indicator view.</p>
<pre><code> View indicator = LayoutInflater.from(getActivity()).inflate(R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
</code></pre>
<p>Your tab indicator view would probably like similar to this.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@drawable/tabselector"
android:padding="5dp" >
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/tab1icon"/>
</LinearLayout>
</code></pre>
<p>Now the important part here is the <code>android:background="@drawable/tabselector"</code> in the LinearLayout. Mine looks like this.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Non focused states -->
<item
android:state_focused="false"
android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/tab_unselected_light" />
<item
android:state_focused="false"
android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/tab_selected_light" />
<!-- Focused states -->
<item
android:state_focused="true"
android:state_selected="true"
android:state_pressed="false"
android:drawable="@drawable/tab_focused_light" />
<!-- Pressed state -->
<item
android:state_pressed="true"
android:drawable="@drawable/tab_pressed_light" />
</selector>
</code></pre>
<p>This tabselector.xml is where you will swap <code>@drawable/tab_pressed_light</code> with your <code>@drawable/tab_button_active</code> and <code>@drawable/tab_unselected_light</code> with <code>@drawable/tab_button_inactive</code></p>
<p>Be sure to check that all of your drawables that go into your tabselector.xml do not have the blue strips along the bottom. As I look at your image I can see little 5px gaps along that strip this is what gave me the idea that the strip was not from your TabWidget. Hope this helps.</p> |
14,577,412 | How to convert variable (object) name into String | <p>I have the following data frame with variable name <code>"foo"</code>;</p>
<pre><code> > foo <-c(3,4);
</code></pre>
<p>What I want to do is to convert <code>"foo"</code> into a string. So that in a function
I don't have to recreate another extra variables:</p>
<pre><code> output <- myfunc(foo)
myfunc <- function(v1) {
# do something with v1
# so that it prints "FOO" when
# this function is called
#
# instead of the values (3,4)
return ()
}
</code></pre> | 14,577,878 | 1 | 5 | null | 2013-01-29 07:05:01.66 UTC | 56 | 2014-01-25 07:31:36.58 UTC | 2014-01-25 07:31:36.58 UTC | null | 1,627,235 | null | 67,405 | null | 1 | 153 | string|r|object | 133,152 | <p>You can use <code>deparse</code> and <code>substitute</code> to get the name of a function argument:</p>
<pre><code>myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
</code></pre> |
42,463,172 | how to perform max/mean pooling on a 2d array using numpy | <p>Given a 2D(M x N) matrix, and a 2D Kernel(K x L), how do i return a matrix that is the result of max or mean pooling using the given kernel over the image?</p>
<p>I'd like to use numpy if possible.</p>
<p>Note: M, N, K, L can be both even or odd and they need not be perfectly divisible by each other, eg: 7x5 matrix and 2x2 kernel.</p>
<p>eg of max pooling:</p>
<pre><code>matrix:
array([[ 20, 200, -5, 23],
[ -13, 134, 119, 100],
[ 120, 32, 49, 25],
[-120, 12, 09, 23]])
kernel: 2 x 2
soln:
array([[ 200, 119],
[ 120, 49]])
</code></pre> | 42,463,491 | 6 | 0 | null | 2017-02-26 00:06:15.9 UTC | 13 | 2022-08-18 11:35:15.343 UTC | null | null | null | null | 3,656,414 | null | 1 | 55 | python|arrays|numpy|matrix|max-pooling | 65,138 | <p>You could use scikit-image <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.block_reduce" rel="noreferrer">block_reduce</a>:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import skimage.measure
a = np.array([
[ 20, 200, -5, 23],
[ -13, 134, 119, 100],
[ 120, 32, 49, 25],
[-120, 12, 9, 23]
])
skimage.measure.block_reduce(a, (2,2), np.max)
</code></pre>
<p>Gives:</p>
<pre class="lang-none prettyprint-override"><code>array([[200, 119],
[120, 49]])
</code></pre> |
29,882,642 | How to run a flask application? | <p>I want to know the correct way to start a flask application. The docs show two different commands:</p>
<pre class="lang-none prettyprint-override"><code>$ flask -a sample run
</code></pre>
<p>and</p>
<pre class="lang-none prettyprint-override"><code>$ python3.4 sample.py
</code></pre>
<p>produce the same result and run the application correctly. </p>
<p>What is the difference between the two and which should be used to run a Flask application?</p> | 29,883,397 | 6 | 0 | null | 2015-04-26 19:45:57.467 UTC | 21 | 2022-09-17 14:54:35.79 UTC | 2015-04-26 21:00:41.05 UTC | null | 400,617 | null | 4,095,771 | null | 1 | 90 | python|flask | 214,379 | <p>The <code>flask</code> command is a CLI for interacting with Flask apps. The <a href="http://flask.palletsprojects.com/cli/" rel="nofollow noreferrer">docs</a> describe how to use CLI commands and add custom commands. The <code>flask run</code> command is the preferred way to start the development server.</p>
<p>Never use this command to deploy publicly, use a production WSGI server such as Gunicorn, uWSGI, Waitress, or mod_wsgi.</p>
<p>As of Flask 2.2, use the <code>--app</code> option to point the command at your app. It can point to an import name or file name. It will automatically detect an app instance or an app factory called <code>create_app</code>. Use the <code>--debug</code> option to run in debug mode with the debugger and reloader.</p>
<pre class="lang-none prettyprint-override"><code>$ flask --app sample --debug run
</code></pre>
<hr />
<p>Prior to Flask 2.2, the <code>FLASK_APP</code> and <code>FLASK_ENV=development</code> environment variables were used instead. <code>FLASK_APP</code> and <code>FLASK_DEBUG=1</code> can still be used in place of the CLI options above.</p>
<pre class="lang-none prettyprint-override"><code>$ export FLASK_APP=sample
$ export FLASK_ENV=development
$ flask run
</code></pre>
<p>On Windows CMD, use <code>set</code> instead of <code>export</code>.</p>
<pre class="lang-none prettyprint-override"><code>> set FLASK_APP=sample
</code></pre>
<p>For PowerShell, use <code>$env:</code>.</p>
<pre class="lang-none prettyprint-override"><code>> $env:FLASK_APP = "sample"
</code></pre>
<hr />
<p>The <code>python sample.py</code> command runs a Python file and sets <code>__name__ == "__main__"</code>. If the main block calls <code>app.run()</code>, it will run the development server. If you use an app factory, you could also instantiate an app instance at this point.</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == "__main__":
app = create_app()
app.run(debug=True)
</code></pre>
<hr />
<p>Both these commands ultimately start the Werkzeug <a href="http://flask.palletsprojects.com/server/" rel="nofollow noreferrer">development server</a>, which as the name implies starts a simple HTTP server that should only be used during development. You should prefer using the <code>flask run</code> command over the <code>app.run()</code>.</p> |
44,992,512 | How to checkout merge request locally, and create new local branch? | <p>I have GitLab repository there and I need to test every merge request locally, before merging to the target branch. </p>
<p>How can I pull/fetch merge request as a new branch?</p> | 44,992,513 | 4 | 0 | null | 2017-07-09 02:50:02.503 UTC | 15 | 2021-04-07 09:13:21.023 UTC | 2020-04-22 13:50:17.32 UTC | null | 6,904,888 | null | 3,758,949 | null | 1 | 59 | git|gitlab|git-merge | 44,084 | <ol>
<li><p>Pull merge request to new branch </p>
<p><code>git fetch origin merge-requests/REQUESTID/head:BRANCHNAME</code></p>
<p>i.e
<code>git fetch origin merge-requests/10/head:file_upload</code></p></li>
<li><p>Checkout to newly created branch</p>
<p><code>git checkout BRANCHNAME</code></p>
<p>i.e (<code>git checkout file_upload</code>)</p></li>
</ol>
<p>OR with single command </p>
<p><code>git fetch origin merge-requests/REQUESTID/head:BRANCHNAME && git checkout BRANCHNAME</code></p>
<p>i.e
<code>git fetch origin merge-requests/18/head:file_upload && git checkout file_upload</code></p> |
40,373,030 | How to create an instance of a class from a String in Swift | <p>I have tried creating an instance of a class using a string in numerous ways with none of them working <strong>in Swift 3</strong>.</p>
<p><strong>Below are pre-Swift 3 solutions I have tried that are not working</strong></p>
<p><strong>- Making class an objective-c class</strong></p>
<pre><code>@objc(customClass)
class customClass {
...
}
//Error here: cannot convert value of type 'AnyClass?' to expected argument type 'customClass'
let c: customClass = NSClassFromString("customClass")
</code></pre>
<p><strong>- Specifying class using NSString value (both with and without using @objc attribute)</strong></p>
<pre><code>@objc(customClass)
class customClass {
...
}
//Error here: cannot convert value of type 'String' to expected argument type 'AnyClass' (aka 'AnyObject.Type')
var className = NSStringFromClass("customClass")
let c: customClass = NSClassFromString(className)
</code></pre>
<p>I'm not doing something right but have not found any solutions online.</p>
<p><em>How do I create an instance of a class using a string in Swift 3?</em></p> | 40,373,130 | 4 | 2 | null | 2016-11-02 05:27:15.193 UTC | 8 | 2021-12-01 09:02:37.04 UTC | 2019-07-17 12:30:35.317 UTC | null | 2,108,547 | null | 4,486,146 | null | 1 | 43 | swift | 39,041 | <p>You can try this: </p>
<pre><code>func classFromString(_ className: String) -> AnyClass! {
/// get namespace
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
/// get 'anyClass' with classname and namespace
let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!
// return AnyClass!
return cls
}
</code></pre>
<p>use the func like this:</p>
<pre><code>class customClass: UITableView {}
let myclass = classFromString("customClass") as! UITableView.Type
let instance = myclass.init()
</code></pre> |
39,352,644 | How to change tab width in git diff? | <p>The standard spacing for a tab is 8 characters.</p>
<p>I prefer to view that as 4 characters in my editors and console. I can easily change this default behavior on console with the <code>tabs</code> command:</p>
<pre><code>tabs -4
</code></pre>
<p>However, when using <code>git diff</code> or <code>git show</code> it displays in the default 8 character tab whitespace.</p>
<p>How can I get <code>git diff</code> to render tabs as 4 character spaces?</p> | 39,352,670 | 1 | 0 | null | 2016-09-06 15:22:03.597 UTC | 3 | 2016-09-06 15:26:47.8 UTC | null | null | null | null | 4,233,593 | null | 1 | 32 | git|whitespace|git-diff | 10,009 | <p>This actually has nothing to do with <code>git diff</code>.</p>
<p>git diff actually renders a tab, which is later converted by your terminal emulators (for instance, <code>gnome-terminal</code>) to <em>spaces</em>.</p>
<p>Go to the preference of your terminal emulator to change that setting.</p>
<hr>
<p>Also, git may use a pager, so you might want to configure it like that:</p>
<pre><code>git config --global core.pager 'less -x1,5'
</code></pre>
<p>More information here: <a href="https://stackoverflow.com/questions/10581093/setting-tabwidth-to-4-in-git-show-git-diff">setting tabwidth to 4 in git show / git diff</a></p> |
32,422,867 | When do I need to use hasOwnProperty()? | <p>I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want.</p>
<p>But is this always required? Are there situations where it's not needed? Is this required for local variables too?</p>
<pre><code>function my(){
var obj = { ... };
for(var key in obj){
if(obj.hasOwnProperty(key)){
safe
}
}
}
</code></pre>
<p>I just don't like adding an extra <em>if</em> inside the loop if I don't have to.</p>
<p><em><a href="http://phrogz.net/death-to-hasownproperty" rel="noreferrer">Death to hasOwnProperty</a></em></p>
<p>This guy says I shouldn't use it at all any more.</p> | 32,422,910 | 4 | 0 | null | 2015-09-06 11:07:31.253 UTC | 6 | 2022-04-22 11:57:44.79 UTC | 2020-10-06 12:37:04.157 UTC | null | 63,550 | null | 1,325,399 | null | 1 | 29 | javascript|loops|object | 10,009 | <p><code>Object.hasOwnProperty</code> determines if the whole property is defined in the object itself or in the prototype chain.</p>
<p>In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.</p>
<p>For example:</p>
<pre><code>function A() {
this.x = "I'm an own property";
}
A.prototype.y = "I'm not an own property";
var instance = new A();
var xIsOwnProperty = instance.hasOwnProperty("x"); // true
var yIsOwnProperty = instance.hasOwnProperty("y"); // false
</code></pre>
<h2>Do you want to avoid the whole check if you want own properties only?</h2>
<p>Since ECMAScript 5.x, <code>Object</code> has a new function <code>Object.keys</code> which returns an array of strings where its items are the <em>own properties from a given object</em>:</p>
<pre><code>var instance = new A();
// This won't contain "y" since it's in the prototype, so
// it's not an "own object property"
var ownPropertyNames = Object.keys(instance);
</code></pre>
<p>Also, since ECMAScript 5.x, <code>Array.prototype</code> has <code>Array.prototype.forEach</code> which let’s perform a <em>for-each loop</em> fluently:</p>
<pre><code>Object.keys(instance).forEach(function(ownPropertyName) {
// This function will be called for each found "own property", and
// you don't need to do the instance.hasOwnProperty check any more
});
</code></pre> |
37,872,561 | HTML: Add elements dynamically using JS | <p>Working with HTML5, I have created a simple table that consists of a series of pair fields (Activity log, time). I've been searching on the web how to dynamically create fields using Javascript, but I've only found how to create one field at a time (using getElementById). The thing is that I'd like to create a series of tags. Meaning, when the user clicks on "add another field", I'd like that JS to generate another row on the table, with a pair of fields, instead of having to hard code the complete table (the snippet below only has two rows, but I'd probably need 10-15 rows).</p>
<p>The snippet of the code for the table appears below. Using CSS the page looks as it's on the screenshot.
<a href="https://i.stack.imgur.com/BFnXo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFnXo.png" alt="screenshot" /></a></p>
<p>I'd appreciate any help.
Thanks in advance.</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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Activity Log</title>
<link href="styles.css" rel="stylesheet">
<script type="text/javascript" language="javascript" src="script.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="leftcol">
<form name='mainForm' id='mainForm' method="get" action="http://www.randyconnolly.com/tests/process.php">
<fieldset>
<legend>Input Activity Logs</legend>
<table id=tracklist>
<tr>
<th colspan="3">Track List: </th>
</tr>
<tr>
<td>1</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
</tr>
<tr>
<td>2</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
</tr>
</table>
<input type="submit" />
</fieldset>
</form>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p> | 37,872,980 | 7 | 0 | null | 2016-06-17 03:20:07.73 UTC | 3 | 2022-09-11 16:34:52.733 UTC | 2021-12-29 13:32:16.6 UTC | null | 2,255,718 | null | 6,035,562 | null | 1 | 6 | javascript|html | 38,923 | <p>You can use the .innerHTML += method wired up to an "Add Activity" button. Each time you click the button a new table row is added with the correct index numbers. Here is a fully working example - for the sake of simplicity and having only one file, I've included the javascript directly in the HTML code:</p>
<pre><code><!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Activity Log</title>
<script>
// Wait until the window finishes loaded before executing any script
window.onload = function() {
// Initialize the activityNumber
var activityNumber = 3;
// Select the add_activity button
var addButton = document.getElementById("add_activity");
// Select the table element
var tracklistTable = document.getElementById("tracklist");
// Attach handler to the button click event
addButton.onclick = function() {
// Add a new row to the table using the correct activityNumber
tracklistTable.innerHTML += '<tr><td>' + activityNumber + '</td><td><label>Activity Log: </label><br/><input type="text" name="actlog' + activityNumber + '" class="required"></td><td><label>Time: </label><br/><input type="time" name="time' + activityNumber + '" class="required"></td></tr>';
// Increment the activityNumber
activityNumber += 1;
}
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="leftcol">
<form name='mainForm' id='mainForm' method="get" action="#">
<fieldset>
<legend>Input Activity Logs</legend>
<table id="tracklist">
<tr>
<th colspan="3">Track List: </th>
</tr>
<tr>
<td>1</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time1" class="required"></td>
</tr>
<tr>
<td>2</td>
<td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td>
<td><label>Time: </label><br/><input type="time" name="time2" class="required"></td>
</tr>
</table>
<input type="submit" />
</fieldset>
</form>
<button id="add_activity">Add Activity</button>
</div>
</div>
</div>
</body>
</html>
</code></pre> |
35,341,435 | Getting I/art: Explicit concurrent mark sweep GC freed | <p>I'm starting a service => background service, And starting a check for files in "new Thread", In the log i'm getting the following, the service/app gets paused .</p>
<p>Log : <code>I/art: Explicit concurrent mark sweep GC freed 25935(1686KB) AllocSpace objects, 13(903KB) LOS objects, 39% free, 13MB/22MB, paused 649us total 43.569ms
</code></p>
<p>It's just a scan for files in MyData in SDcard, which contain a bunch of pics ( about 20 pics ) .</p>
<p>**Scan = Getting the pics names and saving them to String .</p> | 35,341,695 | 2 | 0 | null | 2016-02-11 14:03:09.533 UTC | 7 | 2021-11-11 01:38:19.667 UTC | null | null | null | null | 5,646,429 | null | 1 | 24 | java|android|android-service | 49,706 | <p>All this means is that the garbage collector is doing its job and freeing up memory.</p>
<p>If you are seeing this frequently (or consistently), then you are likely allocating too many objects. A common cause is allocating many (or a few large) objects within a loop like so:</p>
<pre><code>for (int i = 0; i < 100; i++) {
Bitmap bmp = Bitmap.create(100, 100, Bitmap.Config.ARGB_4444);
}
</code></pre>
<p>Every time we hit this loop, we allocate one hundred new Bitmap objects.</p>
<p>The best way to prevent GC sweeps is to not allocate objects. Of course you have to allocate objects in Java, so you need to ensure that you are not allocating unnecessarily.</p>
<p><a href="https://www.youtube.com/watch?v=OrLEoIsMIAc">Here is one of many YouTube videos</a> that Google has release with tips on avoiding GC events and managing memory properly.</p> |
51,338,041 | How to Save Image File in Flutter ? File selected using Image_picker plugin | <p>I am really confused. Flutter is awesome but some time is stuck the mind</p>
<p>All the code are done. selected file also showing in preview but I try to save that file in local android storage. I can't get success in </p>
<pre><code> Future getImage(ImageSource imageSource) async {
var image = await ImagePicker.pickImage(source: imageSource);
setState(() {
_image = image;
});
}
</code></pre>
<p>Select file using this code and my file in <code>_image</code> now I try to store using path_provider and <code>dart.io</code> but I can't get save methodology.</p> | 51,338,178 | 7 | 0 | null | 2018-07-14 11:28:57.183 UTC | 25 | 2022-06-10 06:38:47.523 UTC | 2019-01-08 05:03:57.04 UTC | null | 3,681,880 | null | 8,854,366 | null | 1 | 39 | dart|flutter | 97,671 | <p>Using <code>await ImagePicker.pickImage(...)</code>, you are already on the right track because the function returns a <a href="https://github.com/flutter/plugins/blob/master/packages/image_picker/lib/image_picker.dart#L56" rel="noreferrer"><code>File</code></a>.</p>
<p>The <code>File</code> class has a <a href="https://docs.flutter.io/flutter/dart-io/File/copy.html" rel="noreferrer"><code>copy</code> method</a>, which you can use to copy the file (which is already saved on disk by either the camera or by lying in gallery) and put it into your application documents directory:</p>
<pre><code>// using your method of getting an image
final File image = await ImagePicker.pickImage(source: imageSource);
// getting a directory path for saving
final String path = await getApplicationDocumentsDirectory().path;
// copy the file to a new path
final File newImage = await image.copy('$path/image1.png');
setState(() {
_image = newImage;
});
</code></pre>
<p>You should also note that you can get the path of the image file from <code>ImagePicker</code> using <code>image.path</code>, which will also contain the file ending that you might want to extract and you can save your image path by using <code>newImage.path</code>.</p> |
25,862,896 | Text with newline inside a div element is not working | <p>I have a div element </p>
<pre><code><div id="testResult" style="padding-left: 120px;">
</code></pre>
<p>I am trying to print some text with newline character <code>'\n'</code> inside the <code>div</code> element.</p>
<p>But in my <code>html</code> page displayed text is ignoring the newline character.</p>
<pre><code> $("#testResult").html("Feature: Apply filter to image\n As an user\n I want to be able to apply a filter to my image\n So I can make it look better and match my card's stile\n\n @US2330 @done\n Scenario Outline: Apply filter to a picture # features/card_edit_filter.feature:33\n Given I am on \"Filters Editor\" screen # features/step_definitions/common_steps.rb:1\n And I see my card with the original image # features/step_definitions/card_filter_steps.rb:21\n When I touch the \"<filter_name>\" filter # features/step_definitions/card_filter_steps.rb:1\n Then I see the image with the filter applied # features/step_definitions/card_filter_steps.rb:26\n\n Examples: \n | filter_name |\n | Black & White |\n | Sepia |\n | Vintage |\n\n @US2330 @done\n Scenario: Restore image after applying filter # features/card_edit_filter.feature:47\n")
</code></pre>
<p>I want to show the text as:</p>
<pre><code>Feature: Apply filter to image
As an user
I want to be able to apply a filter to my image
So I can make it look better and match my card's stile
@US2330 @done
Scenario Outline: Apply filter to a picture # features/card_edit_filter.feature:33
Given I am on "Filters Editor" screen # features/step_definitions/common_steps.rb:1
And I see my card with the original image # features/step_definitions/card_filter_steps.rb:21
When I touch the "<filter_name>" filter # features/step_definitions/card_filter_steps.rb:1
Then I see the image with the filter applied # features/step_definitions/card_filter_steps.rb:26
Examples:
| filter_name |
</code></pre> | 25,863,037 | 7 | 0 | null | 2014-09-16 07:25:05.407 UTC | 3 | 2020-11-10 10:50:45.477 UTC | 2017-08-23 21:44:02.537 UTC | null | 1,812,727 | null | 609,219 | null | 1 | 38 | javascript|jquery|html|css | 34,313 | <p>Add this css:</p>
<pre><code>#testResult
{
white-space:pre-wrap;
}
</code></pre>
<p><a href="http://jsfiddle.net/h7takw5k/" rel="noreferrer">Demo</a></p> |
42,867,039 | GitLab CI runner can't connect to unix:///var/run/docker.sock in kubernetes | <p>GitLab's running in kubernetes cluster. Runner can't build docker image with build artifacts. I've already tried several approaches to fix this, but no luck. Here are some configs snippets:</p>
<p>.gitlab-ci.yml</p>
<pre><code>image: docker:latest
services:
- docker:dind
variables:
DOCKER_DRIVER: overlay
stages:
- build
- package
- deploy
maven-build:
image: maven:3-jdk-8
stage: build
script: "mvn package -B --settings settings.xml"
artifacts:
paths:
- target/*.jar
docker-build:
stage: package
script:
- docker build -t gitlab.my.com/group/app .
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN gitlab.my.com/group/app
- docker push gitlab.my.com/group/app
</code></pre>
<p>config.toml</p>
<pre><code>concurrent = 1
check_interval = 0
[[runners]]
name = "app"
url = "https://gitlab.my.com/ci"
token = "xxxxxxxx"
executor = "kubernetes"
[runners.kubernetes]
privileged = true
disable_cache = true
</code></pre>
<p>Package stage log:</p>
<pre><code>running with gitlab-ci-multi-runner 1.11.1 (a67a225)
on app runner (6265c5)
Using Kubernetes namespace: default
Using Kubernetes executor with image docker:latest ...
Waiting for pod default/runner-6265c5-project-4-concurrent-0h9lg9 to be running, status is Pending
Waiting for pod default/runner-6265c5-project-4-concurrent-0h9lg9 to be running, status is Pending
Running on runner-6265c5-project-4-concurrent-0h9lg9 via gitlab-runner-3748496643-k31tf...
Cloning repository...
Cloning into '/group/app'...
Checking out 10d5a680 as master...
Skipping Git submodules setup
Downloading artifacts for maven-build (61)...
Downloading artifacts from coordinator... ok id=61 responseStatus=200 OK token=ciihgfd3W
$ docker build -t gitlab.my.com/group/app .
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
ERROR: Job failed: error executing remote command: command terminated with non-zero exit code: Error executing in Docker Container: 1
</code></pre>
<p>What am I doing wrong?</p> | 42,903,164 | 4 | 0 | null | 2017-03-17 21:02:08.163 UTC | 6 | 2019-10-25 13:57:17.737 UTC | null | null | null | null | 3,906,452 | null | 1 | 31 | docker|gitlab|kubernetes|gitlab-ci-runner | 28,359 | <p>Don't need to use this: </p>
<pre><code>DOCKER_DRIVER: overlay
</code></pre>
<p>cause it seems like OVERLAY isn't supported, so svc-0 container is unable to start with it:</p>
<pre><code>$ kubectl logs -f `kubectl get pod |awk '/^runner/{print $1}'` -c svc-0
time="2017-03-20T11:19:01.954769661Z" level=warning msg="[!] DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING [!]"
time="2017-03-20T11:19:01.955720778Z" level=info msg="libcontainerd: new containerd process, pid: 20"
time="2017-03-20T11:19:02.958659668Z" level=error msg="'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded."
</code></pre>
<p>Also, add <code>export DOCKER_HOST="tcp://localhost:2375"</code> to the docker-build:</p>
<pre><code> docker-build:
stage: package
script:
- export DOCKER_HOST="tcp://localhost:2375"
- docker build -t gitlab.my.com/group/app .
- docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN gitlab.my.com/group/app
- docker push gitlab.my.com/group/app
</code></pre> |
49,424,378 | Does using var with a literal result in a primitive or a primitive wrapper class? | <p>After reading and talking about Java 10s new reserved type name <strong><code>var</code></strong>
(<a href="http://openjdk.java.net/jeps/286" rel="noreferrer">JEP 286: Local-Variable Type Inference</a>), one question arose in the discussion.</p>
<p>When using it with literals like:</p>
<pre><code>var number = 42;
</code></pre>
<p>is <code>number</code> now an <code>int</code> or an <code>Integer</code>? If you just use it with comparison operators or as a parameter it usually doesn't matter thanks to autoboxing and -unboxing.
But due to <code>Integer</code>s member functions it <em>could matter</em>.</p>
<p>So which type is created by <code>var</code>, a primitive <code>int</code> or class <code>Integer</code>?</p> | 49,424,437 | 4 | 1 | null | 2018-03-22 09:00:53.377 UTC | 2 | 2018-05-01 06:01:03.067 UTC | 2018-03-24 15:04:42.35 UTC | null | 1,746,118 | null | 726,776 | null | 1 | 36 | java|type-inference|local-variables|java-10 | 2,187 | <p><code>var</code> asks the compiler to infer the type of the variable from the type of the initializer, and the natural type of <code>42</code> is <code>int</code>. So <code>number</code> will be an <code>int</code>. That is what the <a href="https://docs.oracle.com/javase/specs/jls/se10/html/jls-14.html#jls-14.4.1" rel="noreferrer">JLS example says</a>:</p>
<pre><code>var a = 1; // a has type 'int'
</code></pre>
<p>And I would be surprised if it worked any other way, when I write something like this, I definitely expect a primitive. </p>
<p>If you need a <code>var</code> as boxed primitive, you could do:</p>
<pre><code>var x = (Integer) 10; // x is now an Integer
</code></pre> |
47,920,305 | "Can not set org.eclipse.aether.spi.log.Logger" with custom maven plugin | <p>I have written a small custom maven plugin, and it runs fine.. most of the time. </p>
<p>When using it, it's configured to run on test phase, and I see it executing, no problem. Now problem comes later, when I do <em>mvn clean install</em> or <em>mvn clean deploy</em> in the project using the plugin : it fails with a message I can't make sense of. And it clearly comes from my plugin, because if I remove it, then <em>mvn clean install</em> works.</p>
<p>Error message is very long and it has 4 similar traces as the one below.</p>
<p>I am quite clueless with where it can come from.. any idea ? </p>
<pre><code> Error injecting: private org.eclipse.aether.spi.log.Logger org.apache.maven.repository.internal.DefaultVersionResolver.logger
[ERROR] while locating org.apache.maven.repository.internal.DefaultVersionResolver
[ERROR] while locating java.lang.Object annotated with *
[ERROR] at org.eclipse.sisu.wire.LocatorWiring
[ERROR] while locating org.eclipse.aether.impl.VersionResolver
[ERROR] for parameter 2 at org.eclipse.aether.internal.impl.DefaultArtifactResolver.<init>(Unknown Source)
[ERROR] while locating org.eclipse.aether.internal.impl.DefaultArtifactResolver
[ERROR] while locating java.lang.Object annotated with *
[ERROR] at org.eclipse.sisu.wire.LocatorWiring
[ERROR] while locating org.eclipse.aether.impl.ArtifactResolver
[ERROR] for parameter 2 at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.<init>(Unknown Source)
[ERROR] while locating org.apache.maven.repository.internal.DefaultArtifactDescriptorReader
[ERROR] while locating java.lang.Object annotated with *
[ERROR] at org.eclipse.sisu.wire.LocatorWiring
[ERROR] while locating org.eclipse.aether.impl.ArtifactDescriptorReader
[ERROR] for parameter 1 at org.eclipse.aether.internal.impl.DefaultDependencyCollector.<init>(Unknown Source)
[ERROR] while locating org.eclipse.aether.internal.impl.DefaultDependencyCollector
[ERROR] while locating java.lang.Object annotated with *
[ERROR] at org.eclipse.sisu.wire.LocatorWiring
[ERROR] while locating org.eclipse.aether.impl.DependencyCollector
[ERROR] for parameter 5 at org.eclipse.aether.internal.impl.DefaultRepositorySystem.<init>(Unknown Source)
[ERROR] while locating org.eclipse.aether.internal.impl.DefaultRepositorySystem
[ERROR] while locating java.lang.Object annotated with *
[ERROR] while locating org.apache.maven.artifact.installer.DefaultArtifactInstaller
[ERROR] at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
[ERROR] at ClassRealm[plexus.core, parent: null] (via modules: org.eclipse.sisu.wire.WireModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
[ERROR] while locating org.apache.maven.artifact.installer.ArtifactInstaller
[ERROR] while locating org.apache.maven.plugin.install.InstallMojo
[ERROR] at ClassRealm[plugin>org.apache.maven.plugins:maven-install-plugin:2.4, parent: sun.misc.Launcher$AppClassLoader@5c647e05] (via modules: org.eclipse.sisu.wire.Wir
eModule -> org.eclipse.sisu.plexus.PlexusBindingModule)
[ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.apache.maven.plugins:maven-install-plugin:2.4:install)
[ERROR] Caused by: java.lang.IllegalArgumentException: Can not set org.eclipse.aether.spi.log.Logger field org.apache.maven.repository.internal.DefaultVersionResolver.log
ger to org.eclipse.aether.internal.impl.slf4j.Slf4jLoggerFactory
[ERROR] at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
[ERROR] at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
[ERROR] at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
[ERROR] at java.lang.reflect.Field.set(Field.java:758)
[ERROR] at org.eclipse.sisu.bean.BeanPropertyField.set(BeanPropertyField.java:72)
[ERROR] at org.eclipse.sisu.plexus.ProvidedPropertyBinding.injectProperty(ProvidedPropertyBinding.java:48)
[ERROR] at org.eclipse.sisu.bean.BeanInjector.injectMembers(BeanInjector.java:52)
[ERROR] at com.google.inject.internal.MembersInjectorImpl.injectMembers(MembersInjectorImpl.java:140)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:117)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.wire.BeanProviders.firstOf(BeanProviders.java:179)
[ERROR] at org.eclipse.sisu.wire.BeanProviders$7.get(BeanProviders.java:160)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
[ERROR] at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:107)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.wire.BeanProviders.firstOf(BeanProviders.java:179)
[ERROR] at org.eclipse.sisu.wire.BeanProviders$7.get(BeanProviders.java:160)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
[ERROR] at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:107)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.wire.BeanProviders.firstOf(BeanProviders.java:179)
[ERROR] at org.eclipse.sisu.wire.BeanProviders$7.get(BeanProviders.java:160)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
[ERROR] at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:107)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1059)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.wire.BeanProviders.firstOf(BeanProviders.java:179)
[ERROR] at org.eclipse.sisu.wire.BeanProviders$7.get(BeanProviders.java:160)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.SingleParameterInjector.inject(SingleParameterInjector.java:38)
[ERROR] at com.google.inject.internal.SingleParameterInjector.getAll(SingleParameterInjector.java:62)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:107)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.FactoryProxy.get(FactoryProxy.java:56)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
[ERROR] at org.eclipse.sisu.plexus.PlexusRequirements$RequirementProvider.get(PlexusRequirements.java:250)
[ERROR] at org.eclipse.sisu.plexus.ProvidedPropertyBinding.injectProperty(ProvidedPropertyBinding.java:48)
[ERROR] at org.eclipse.sisu.bean.BeanInjector.injectMembers(BeanInjector.java:52)
[ERROR] at com.google.inject.internal.MembersInjectorImpl.injectMembers(MembersInjectorImpl.java:140)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:117)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1044)
[ERROR] at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1059)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
[ERROR] at org.eclipse.sisu.plexus.PlexusRequirements$RequirementProvider.get(PlexusRequirements.java:250)
[ERROR] at org.eclipse.sisu.plexus.ProvidedPropertyBinding.injectProperty(ProvidedPropertyBinding.java:48)
[ERROR] at org.eclipse.sisu.bean.BeanInjector.injectMembers(BeanInjector.java:52)
[ERROR] at com.google.inject.internal.MembersInjectorImpl.injectMembers(MembersInjectorImpl.java:140)
[ERROR] at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:117)
[ERROR] at com.google.inject.internal.ConstructorInjector.access$000(ConstructorInjector.java:32)
[ERROR] at com.google.inject.internal.ConstructorInjector$1.call(ConstructorInjector.java:92)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
[ERROR] at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:269)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1066)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1044)
[ERROR] at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:54)
[ERROR] at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
[ERROR] at org.eclipse.sisu.bean.BeanScheduler$Activator.onProvision(BeanScheduler.java:176)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:126)
[ERROR] at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
[ERROR] at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68)
[ERROR] at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:46)
[ERROR] at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1009)
[ERROR] at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1059)
[ERROR] at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1005)
[ERROR] at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:36)
[ERROR] at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
[ERROR] at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
[ERROR] at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
[ERROR] at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
[ERROR] at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:543)
[ERROR] at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:121)
[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
[ERROR] at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
[ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
[ERROR] at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
[ERROR] at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
[ERROR] at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
[ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
[ERROR] at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
[ERROR] at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
[ERROR] at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
[ERROR] at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
[ERROR] at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
[ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR] at java.lang.reflect.Method.invoke(Method.java:483)
[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
[ERROR] at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
[ERROR]
[ERROR] 4 errors
[ERROR] role: org.apache.maven.plugin.Mojo
[ERROR] roleHint: org.apache.maven.plugins:maven-install-plugin:2.4:install
</code></pre> | 47,920,306 | 11 | 1 | null | 2017-12-21 07:52:22.307 UTC | 3 | 2021-11-18 12:49:34.203 UTC | null | null | null | null | 3,067,542 | null | 1 | 30 | java|maven|maven-plugin | 27,253 | <p>After some research, I felt it looked like some version incompatibility. and indeed, it is, between the maven version I am using to build the applications using the plugin, and the maven core version used in the plugin. </p>
<ul>
<li>in my plugin, I was using latest maven core version available as a dependency, ie 3.5.2</li>
<li>I am building the plugin with Maven 3.3.1 and build is OK.</li>
<li>but when I build a project using the plugin, with Maven 3.3.1, the problem happens. </li>
</ul>
<p>I downgraded maven core to 3.3.9, then rebuilt my plugin, and it works now. </p>
<p>I guess there are some incompatibilities between maven core 3.5.x and previous maven runtime.. </p>
<p>I see on <a href="https://jaxenter.com/apache-maven-3-5-0-nothing-see-3-4-0-move-along-133180.html" rel="noreferrer">https://jaxenter.com/apache-maven-3-5-0-nothing-see-3-4-0-move-along-133180.html</a> that they switched <em>... from Eclipse Aether to Maven Artifact Resolver</em></p>
<p>but what was very confusing is that my build was failing not at the time of my plugin being called, but after. </p> |
26,292,718 | Laravel get class name of related model | <p>In my Laravel application I have an <code>Faq</code> model. An <code>Faq</code> model can contain many <code>Product</code> models, so the <code>Faq</code> class contains the following function:</p>
<pre><code>class Faq extends Eloquent{
public function products(){
return $this->belongsToMany('Product');
}
}
</code></pre>
<p>In a controller, I would like to be able to retrieve the class name that defines the relationship. For example, if I have an <code>Faq</code> object, like this:</p>
<pre><code>$faq = new Faq();
</code></pre>
<p>How can I determine the class name of the relationship, which in this case would be <code>Product</code>. Currently I am able to do it like this:</p>
<pre><code>$className = get_class($faq->products()->get()->first());
</code></pre>
<p>However, I'm wondering if there is a way to accomplish this same thing without having to actually run a query.</p> | 26,296,283 | 1 | 0 | null | 2014-10-10 05:49:33.903 UTC | 13 | 2018-05-11 18:51:44.59 UTC | null | null | null | null | 736,864 | null | 1 | 64 | php|laravel|eloquent | 125,877 | <p>Yes, there is a way to get related model without query:</p>
<pre><code>$className = get_class($faq->products()->getRelated());
</code></pre>
<p>It will work for all relations.</p>
<p>This will return full name with namespace. In case you want just base name use:</p>
<pre><code>// laravel helper:
$baseClass = class_basename($className);
// generic solution
$reflection = new ReflectionClass($className);
$reflection->getShortName();
</code></pre> |
55,004,302 | How do you pass arguments from command line to main in Flutter/Dart? | <p>How would you run a command and pass some custom arguments with Flutter/Dart so they can then be accessed in the <code>main()</code> call such as:</p>
<pre><code>flutter run -device [my custom arg]
</code></pre>
<p>So then I can access it with:</p>
<pre><code>void main(List<String> args) {
print(args.toString());
}
</code></pre>
<p>Thank you. </p> | 55,004,516 | 5 | 0 | null | 2019-03-05 13:45:38.343 UTC | 4 | 2021-01-03 15:57:15.557 UTC | null | null | null | null | 6,919,963 | null | 1 | 43 | dart|flutter|command|program-entry-point|args | 23,473 | <p>There is no way to do that, because when you start an app on your device there are also no parameters that are passed.</p>
<p>If this is for development, you can pass <code>-t lib/my_alternate_main.dart</code> to
<code>flutter run</code> to easily switch between different settings<br />
where each alternate entry-point file calls the same application code with different parameters or with differently initialized global variables.</p>
<p><strong>Update</strong></p>
<p>For</p>
<ul>
<li><code>flutter run</code></li>
<li><code>flutter build apk</code></li>
<li><code>flutter build ios</code></li>
<li><code>flutter drive</code></li>
</ul>
<p>the <code>--dart-define=...</code> command line parameter was added for that purpose.</p>
<blockquote>
<p>Additional key-value pairs that will be available as constants from the String.fromEnvironment, bool.fromEnvironment, int.fromEnvironment, and double.fromEnvironment constructors.</p>
</blockquote>
<p>For more details see <a href="https://medium.com/@tatsu.ukraine/flutter-1-17-no-more-flavors-no-more-ios-schemas-command-argument-that-solves-everything-8b145ed4285d" rel="noreferrer">Flutter 1.17 no more Flavors, no more iOS Schemas. Command argument that changes everything</a></p>
<h3>Example</h3>
<pre class="lang-dart prettyprint-override"><code>const t = String.fromEnvironment("TEST");
</code></pre>
<pre class="lang-sh prettyprint-override"><code>flutter run --dart-define="TEST=from command line"
</code></pre>
<p>Be aware that <code>const</code> is required and that the variable name is case sensitive.</p> |
7,226,147 | Clarifications on signed/unsigned load and store instructions (MIPS) | <p>I can't seem to grasp the concept on these stuff, even with the help of Google and a textbook in my hand.</p>
<p>Following the format (opcode, rs, rt, offset)...</p>
<ul>
<li>Do you sign extend the offset before adding it to the value of the address? Or add before extending?</li>
<li>In the case of <strong>lb</strong> and <strong>lbu</strong>, what's the difference? Does it also follow the MIPS arithmetic definition that 'unsigned' just means it won't report an overflow?</li>
<li>Why doesn't <strong>lw</strong> have an unsigned version? Even the store instructions don't have one...</li>
</ul> | 7,226,383 | 1 | 0 | null | 2011-08-29 04:44:43.323 UTC | 9 | 2020-08-14 17:20:44.23 UTC | 2020-08-14 17:20:44.23 UTC | null | 224,132 | null | 917,150 | null | 1 | 15 | assembly|mips|sign-extension|zero-extension | 26,533 | <blockquote>
<p>In the case of <code>lb</code> and <code>lbu</code>, what's the difference?</p>
</blockquote>
<p>The "load byte" instructions <code>lb</code> and <code>lbu</code> load a single byte into the right-most byte of a 32-bit register. How do you set the upper 24 bits? The <em>unsigned</em> operation will set them to zero; the signed operation will <a href="http://en.wikipedia.org/wiki/Sign_extension" rel="noreferrer">sign-extend</a> the loaded byte. </p>
<p>For example, suppose you read the byte <code>0xFF</code> from memory. <code>lbu</code> will 0-extend this value to <code>0x000000FF</code> and interpret it as 255, while <code>lb</code> will sign-extend it to <code>0xFFFFFFFF</code>, which is interpreted as -1.</p>
<blockquote>
<p>Why doesn't <code>lw</code> have an unsigned version? Even the store instructions don't have one...</p>
</blockquote>
<p>The "load word" instruction (<code>lw</code>), on the other hand, loads a 32-bit quantity into a 32-bit register, so there is no ambiguity, and no need to have a special signed version.</p>
<p>If you are storing less than a full 32-bit word, there is nothing you can do with the extra bits in the register except throw them away (ignore them). </p>
<blockquote>
<p>Does it also follow the MIPS arithmetic definition that 'unsigned' just means it won't report an overflow?</p>
</blockquote>
<p>I think this convention is only for the add and subtract instructions. For the other instructions, signed/unsigned indicates whether sign-extension will be performed.</p>
<blockquote>
<p>Do you sign extend the offset before adding it to the value of the address? Or add before extending?</p>
</blockquote>
<p>If an offset is sign-extended, it only makes sense to do it before adding it to the base address. I think a review of <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">two's complement</a> arithmetic will make this clear.</p> |
2,603,169 | Update Tkinter Label from variable | <p>I wrote a Python script that does some task to generate, and then keep changing some text stored as a string variable. This works, and I can print the string each time it gets changed.</p>
<p>I can get the Label to display the string for the first time, but it never updates. </p>
<p>Here's my code:</p>
<pre><code>from tkinter import *
outputText = 'Ready'
counter = int(0)
root = Tk()
root.maxsize(400, 400)
var = StringVar()
l = Label(root, textvariable=var, anchor=NW, justify=LEFT, wraplength=398)
l.pack()
var.set(outputText)
while True:
counter = counter + 1
outputText = result
outputText = result
outputText = result
if counter == 5:
break
root.mainloop()
</code></pre>
<p>The Label will show <code>Ready</code>, but won't update to change that to the strings as they're generated later.</p>
<p>After a fair bit of googling and looking through answers on this site, I thought the solution might be to use <code>update_idletasks</code>. I tried putting that in after each time the variable was changed, but it didn't help.</p> | 2,603,371 | 3 | 1 | null | 2010-04-08 20:22:12.063 UTC | 17 | 2021-01-17 09:57:00.547 UTC | 2015-03-11 18:32:48.677 UTC | null | 3,924,118 | null | 312,265 | null | 1 | 29 | python|label|tkinter | 200,663 | <p>The window is only displayed once the mainloop is entered. So you won't see any changes you make in your <code>while True</code> block preceding the line <code>root.mainloop()</code>.</p>
<hr />
<p>GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.</p>
<pre><code>from tkinter import *
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
t = Entry(root, textvariable = var)
t.pack()
root.mainloop() # the window is now displayed
</code></pre>
<p>I like the following reference: <a href="https://web.archive.org/web/20190524140835id_/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html" rel="noreferrer">tkinter 8.5 reference: a GUI for Python</a></p>
<hr />
<p>Here is a working example of what you were trying to do:</p>
<pre><code>from tkinter import *
from time import sleep
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
for i in range(6):
sleep(1) # Need this to slow the changes down
var.set('goodbye' if i%2 else 'hello')
root.update_idletasks()
</code></pre>
<p><code>root.update</code> Enter event loop until all pending events have been processed by <code>Tcl</code>.</p> |
2,607,263 | How precise is the internal clock of a modern PC? | <p>I know that 10 years ago, typical clock precision equaled a system-tick, which was in the range of 10-30ms. Over the past years, precision was increased in multiple steps. Nowadays, there are ways to measure time intervals in nanoseconds. However, usual frameworks still return time with a precision of only around 15ms.</p>
<p>Which steps decrease the precision? How is it possible to measure in nanoseconds? Why are we still often getting worse-than-microsecond precision, for instance in .NET?</p> | 2,615,977 | 3 | 2 | null | 2010-04-09 12:16:54.26 UTC | 5 | 2022-09-04 22:21:13.073 UTC | 2022-05-18 21:36:28.79 UTC | null | 3,064,538 | null | 39,590 | null | 1 | 33 | datetime|clock|time-precision | 25,158 | <p>It really is a feature of the history of the PC.
The original IBM-PC used a chip called the Real Time Clock which was battery backed up (Do you remember needing to change the batteries on these ?) These operated when the machine was powered off and kept the time. The frequency of these was 32.768 kHz (2^15 cycles/second) which made it easy to calculate time on a 16 bit system.
This real time clock was then written to CMOS which was available via an interrupt system in older operating systems.</p>
<p>A newer standard is out from Microsoft and Intel called High Precision Event Timer which specifies a clock speed of 10MHz
<a href="http://www.intel.com/hardwaredesign/hpetspec_1.pdf" rel="noreferrer">http://www.intel.com/hardwaredesign/hpetspec_1.pdf</a>
Even newer PC architectures take this and put it on the Northbridge controller and the HPET can tun at 100MHz or even greater.
At 10Mhz we should be able to get a resolution of 100 nano-seconds and at 100MHZ we should be able to get 10 nano-second resolution.</p>
<p>The following operating systems are known not to be able to use HPET: Windows XP, Windows Server 2003, and earlier Windows versions, older Linux versions</p>
<p>The following operating systems are known to be able to use HPET: Windows Vista, Windows 2008, Windows 7, x86 based versions of Mac OS X, Linux operating systems using the 2.6 kernel and FreeBSD.</p>
<p>With a Linux kernel, you need the newer "rtc-cmos" hardware clock device driver rather than the original "rtc" driver</p>
<p>All that said how do we access this extra resolution?
I could cut and paste from previous stackoverflow articles, but not - Just search for HPET and you will find the answers on how to get finer timers working</p> |
2,579,017 | PHP file that should run once and delete itself. Is it possible? | <p>Is it possible to create a PHP file that runs once with no errors and deletes itself?</p> | 2,579,068 | 4 | 3 | null | 2010-04-05 14:57:10.953 UTC | 7 | 2020-01-31 04:37:40.453 UTC | 2017-08-31 01:43:56.97 UTC | null | 1,454,671 | null | 434,051 | null | 1 | 28 | php|file|self-destruction | 13,674 | <pre><code><?php unlink(__FILE__); ?>
</code></pre> |
2,760,283 | Does Mercurial have an equivalent to git clean? | <p>hg clean does not seem to exist, which kinda bothers me. Is this a feature that Mercurial doesn't have or did they just name it differently?</p> | 2,760,320 | 4 | 0 | null | 2010-05-03 18:31:32.21 UTC | 5 | 2018-02-22 10:19:09.64 UTC | null | null | null | null | 310,121 | null | 1 | 39 | git|mercurial | 20,491 | <p>There is no equivalent to <code>git clean</code> in the core Mercurial package. </p>
<p>However, the <a href="https://www.mercurial-scm.org/wiki/PurgeExtension" rel="nofollow noreferrer"><code>hg purge</code></a> extension does what you are after. </p>
<p>There is an <a href="https://bz.mercurial-scm.org/show_bug.cgi?id=1665" rel="nofollow noreferrer">open issue</a> to make this extension part of the core package.</p> |
28,947,205 | Class 'App\Http\Controllers\admin\Auth' not found in Laravel 5 | <p>I am getting error like Class <code>App\Http\Controllers\admin\Auth</code> not found in Laravel 5 during login.</p>
<p><strong>Routes.php</strong></p>
<pre><code>Route::group(array('prefix'=>'admin'),function(){
Route::get('login', 'admin\AdminHomeController@showLogin');
Route::post('check','admin\AdminHomeController@checkLogin');
});
</code></pre>
<p><strong>AdminHomeController.php</strong></p>
<pre><code><?php namespace App\Http\Controllers\admin;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AdminHomeController extends Controller {
//
public function showLogin()
{
return view('admin.login');
}
public function checkLogin(Request $request)
{
$data=array(
'username'=>$request->get('username'),
'password'=>$request->get('password')
);
if(Auth::attempt($data))
{
return redirect::intended('admin/dashboard');
}
else
{
return redirect('admin/login');
}
}
public function logout()
{
Auth::logout();
return redirect('admin/login');
}
public function showDashboard()
{
return view('admin.dashboard');
}
}
</code></pre>
<p><strong>login.blade.php</strong></p>
<pre><code><html>
<body>
{!! Form::open(array('url' => 'admin/check', 'id' => 'login')) !!}
<input type="text" name="username" id="username" placeholder="Enter any username" />
<input type="password" name="password" id="password" placeholder="Enter any password" />
<button name="submit">Sign In</button>
{!! Form::close() !!}
</body>
</html>
</code></pre> | 28,947,257 | 1 | 0 | null | 2015-03-09 16:35:55.753 UTC | null | 2021-10-22 08:28:34.453 UTC | 2021-10-22 08:28:34.453 UTC | null | 1,145,388 | null | 1,385,107 | null | 1 | 23 | php|laravel|authentication|runtime-error | 96,220 | <p>Because your controller is namespaced unless you specifically import the <code>Auth</code> namespace, PHP will assume it's under the namespace of the class, giving this error. </p>
<p>To fix this, add <code>use Auth;</code> at the top of <code>AdminHomeController</code> file along with your other use statements or alternatively prefix all instances of <code>Auth</code> with backslash like this: <code>\Auth</code> to let PHP know to load it from the global namespace. </p> |
48,992,252 | Move selected text to the left or right in Visual Studio Code | <p>In Visual Studio Code, is there any command currently to move the selected text to the left or right?</p>
<p>I'm not talking about indentation btw.</p> | 53,386,180 | 5 | 0 | null | 2018-02-26 15:54:29.853 UTC | 11 | 2022-08-24 07:04:32.857 UTC | 2019-12-11 19:42:47.19 UTC | null | 1,265,393 | null | 5,951,102 | null | 1 | 28 | visual-studio-code|vscode-settings | 50,162 | <p>This feature has been implemented by <a href="https://github.com/Microsoft/vscode/pull/6887" rel="noreferrer">a pull request</a> some time ago.</p>
<p>To use it you need to bind the <code>editor.action.moveCarretLeftAction</code> and <code>editor.action.moveCarretRightAction</code> actions in the keyboard shortcuts editor.</p>
<p><a href="https://i.stack.imgur.com/VDJEq.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/VDJEq.gif" alt="Animation showing how the solution works"></a></p> |
13,674,449 | Checking Password Code | <p>Problem Description:</p>
<p>Some Websites impose certain rules for passwords. Write a method that checks whether a string is a valid password. Suppose the password rule is as follows:</p>
<ul>
<li>A password must have at least eight characters.</li>
<li>A password consists of only letters and digits.</li>
<li>A password must contain at least two digits.</li>
</ul>
<p>Write a program that prompts the user to enter a password and displays "valid password" if the rule is followed or "invalid password" otherwise.</p>
<p>This is what I have so far:</p>
<pre><code>import java.util.*;
import java.lang.String;
import java.lang.Character;
/**
* @author CD
* 12/2/2012
* This class will check your password to make sure it fits the minimum set requirements.
*/
public class CheckingPassword {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
//return true if and only if password:
//1. have at least eight characters.
//2. consists of only letters and digits.
//3. must contain at least two digits.
if (password.length() < 8) {
return false;
} else {
char c;
int count = 1;
for (int i = 0; i < password.length() - 1; i++) {
c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else if (Character.isDigit(c)) {
count++;
if (count < 2) {
return false;
}
}
}
}
return true;
}
}
</code></pre>
<p>When I run the program it only checks for the length of the password, I cannot figure out how to make sure it is checking for both letters and digits, and to have at least two digits in the password.</p> | 13,674,591 | 6 | 3 | null | 2012-12-02 22:09:35.73 UTC | 2 | 2021-11-15 20:03:58.513 UTC | 2016-03-06 11:34:06.153 UTC | null | 5,277,820 | null | 1,867,612 | null | 1 | 1 | java|passwords|bluej | 103,948 | <p>You almost got it. There are some errors though:</p>
<ul>
<li>you're not iterating over all the chars of the password (<code>i < password.length() - 1</code> is wrong)</li>
<li>you start with a digit count of 1 instead of 0</li>
<li>you make the check that the count of digits is at least 2 as soon as you meet the first digit, instead of checking it after you have scanned all the characters</li>
</ul> |
1,210,571 | How to batch update multiple workitems in TFS | <p>I need to update same field to same value for hundreds of workitems in TFS. Is there any way to do it in a batch instead of updating them manually one by one?</p> | 1,210,728 | 2 | 0 | null | 2009-07-31 03:36:34.057 UTC | 4 | 2016-11-18 06:14:24.39 UTC | 2009-07-31 20:16:09.757 UTC | null | 74,439 | null | 42,356 | null | 1 | 30 | api|tfs|powershell|bug-tracking | 12,929 | <p>You can do this in <strong>Excel</strong>:</p>
<ol>
<li>Open the work items in Excel, via:
<ul>
<li>right click a query in Team Explorer -> open in Excel </li>
<li>multi-select some work items in a WIT result pane, then right click -> open in Excel</li>
<li>load Excel, use Team -> Import to load a predefined query</li>
<li>open a *.xls file that is already bound to TFS</li>
</ul></li>
<li>Make your bulk edits</li>
<li>Click the Publish button on the Team ribbon</li>
</ol>
<p><img src="https://i.stack.imgur.com/Fss1R.png" alt="enter image description here"></p>
<p>Full documentation:
<a href="http://msdn.microsoft.com/en-us/library/dd286627(VS.100).aspx" rel="noreferrer">Managing work items in Excel</a> (overview page; lots & lots of links inside)</p>
<p><a href="http://blogs.msdn.com/buckh/archive/2007/11/06/tswa-tip-bulk-edit.aspx" rel="noreferrer">You can bulk-edit in the web interface too</a></p>
<p><strong>Windows command line</strong>:</p>
<pre><code>REM make Martin Woodward fix all my bugs
tfpt query /format:id "TeamProject\public\My Work Items" |
tfpt workitem /update @ /fields:"Assigned To=Martin"
</code></pre>
<p><strong>Powershell</strong>:</p>
<pre><code># make Bill & Steve happy
$tfs = tfserver -path . -all
$items = $tfs.wit.Query("
SELECT id FROM workitems
WHERE [Created By] IN ('bill gates', 'steve ballmer')") |
% {
$_.Open()
$_.Fields["priority"].value = 1
$_
}
# note: this will be much faster than tfpt since it's only one server call
$tfs.wit.BatchSave($items)
</code></pre> |
2,912,281 | Thread safety in Singleton | <p>I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is:</p>
<pre><code>class Singleton{
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null) instance = new Singleton();
return instance;
}
}
</code></pre>
<p>Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)</p> | 2,912,312 | 5 | 6 | null | 2010-05-26 11:04:55.743 UTC | 18 | 2013-06-14 04:29:14.86 UTC | null | null | null | null | 137,435 | null | 1 | 14 | java|multithreading|singleton | 7,866 | <p>Josh Bloch recommends using a single-element <code>enum</code> type to implement singletons (see <em>Effective Java 2nd Edition, Item 3: Enforce the singleton property with a private constructor or an enum type</em>).</p>
<p>Some people think this is a hack, since it doesn't clearly convey intent, but it does work.</p>
<p>The following example is taken straight from the book.</p>
<pre><code>public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
</code></pre>
<p>Here is his closing arguments:</p>
<blockquote>
<p>This approach [...] is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>.</p>
</blockquote>
<hr />
<h3>On <code>enum</code> constant singleton guarantee</h3>
<h3><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9" rel="noreferrer">JLS 8.9. Enums</a></h3>
<blockquote>
<p>An enum type has no instances other than those defined by its enum constants. It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1).</p>
<p>The <code>final clone</code> method in <code>Enum</code> ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.</p>
</blockquote>
<hr />
<h3>On lazy initialization</h3>
<p>The following snippet:</p>
<pre><code>public class LazyElvis {
enum Elvis {
THE_ONE;
Elvis() {
System.out.println("I'M STILL ALIVE!!!");
}
}
public static void main(String[] args) {
System.out.println("La-dee-daaa...");
System.out.println(Elvis.THE_ONE);
}
}
</code></pre>
<p>Produces the following output:</p>
<pre><code>La-dee-daaa...
I'M STILL ALIVE!!!
THE_ONE
</code></pre>
<p>As you can see, <code>THE_ONE</code> constant is not instantiated through the constructor until the first time it's accessed.</p> |
3,015,203 | Remember (persist) the filter, sort order and current page of jqGrid | <p>My application users asked if it were possible for pages that contain a jqGrid to remember the filter, sort order and current page of the grid (because when they click a grid item to carry out a task and then go back to it they'd like it to be "as they left it")</p>
<p><strong>Cookies</strong> seem to be the way forward, but how to get the page to <em>load these</em> and <em>set them</em> in the grid <em>before</em> it makes its first data request is a little beyond me at this stage.</p>
<p>Does anyone have any experience with this kind of thing with jqGrid? Thanks!</p> | 3,044,974 | 5 | 0 | null | 2010-06-10 14:13:37.407 UTC | 16 | 2015-01-10 02:35:42.537 UTC | null | null | null | null | 175,893 | null | 1 | 28 | jquery|cookies|persistence|jqgrid|filtering | 26,894 | <p><strong>PROBLEM SOLVED</strong></p>
<p>I eventually ended up using cookies in javascript to store the sort column, sort order, page number, grid rows and filter details of the grid (using <a href="http://www.phpied.com/json-javascript-cookies/" rel="noreferrer">JSON/Javascript cookies</a> - the <code>prefs</code> object)</p>
<p><strong>Save Preferences</strong>
- Called from <code>$(window).unload(function(){ ... });</code></p>
<pre><code>var filters = {
fromDate: $('#fromDateFilter').val(),
toDate: $('#toDateFilter').val(),
customer: $('#customerFilter').val()
};
prefs.data = {
filter: filters,
scol: $('#list').jqGrid('getGridParam', 'sortname'),
sord: $('#list').jqGrid('getGridParam', 'sortorder'),
page: $('#list').jqGrid('getGridParam', 'page'),
rows: $('#list').jqGrid('getGridParam', 'rowNum')
};
prefs.save();
</code></pre>
<p><strong>Load Preferences</strong>
- Called from <code>$(document).ready(function(){ ... });</code></p>
<pre><code>var gridprefs = prefs.load();
$('#fromDateFilter').val(gridprefs.filter.fromDate);
$('#toDateFilter').val(gridprefs.filter.toDate);
$('#customerFilter').val(gridprefs.filter.customer);
$('#list').jqGrid('setGridParam', {
sortname: gridprefs.scol,
sortorder: gridprefs.sord,
page: gridprefs.page,
rowNum: gridprefs.rows
});
// filterGrid method loads the jqGrid postdata with search criteria and re-requests its data
filterGrid();
</code></pre>
<p>jqGrid Reference: <a href="http://www.secondpersonplural.ca/jqgriddocs/_2eb0fi5wo.htm" rel="noreferrer">http://www.secondpersonplural.ca/jqgriddocs/_2eb0fi5wo.htm</a></p>
<p><strong>BY POPULAR DEMAND - THE FILTERGRID CODE</strong></p>
<pre><code> function filterGrid() {
var fields = "";
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "ge", dateFrom);
if (dateTo != "") fields += (fields.length == 0 ? "" : ",") + createField("shipmentDate", "le", dateTo);
var filters = '"{\"groupOp\":\"AND\",\"rules\":[' + fields + ']}"';
if (fields.length == 0) {
$("#list").jqGrid('setGridParam', { search: false, postData: { "filters": ""} }).trigger("reloadGrid");
} else {
$("#list").jqGrid('setGridParam', { search: true, postData: { "filters": filters} }).trigger("reloadGrid");
}
}
function createField(name, op, data) {
var field = '{\"field\":\"' + name + '\",\"op\":\"' + op + '\",\"data\":\"' + data + '\"}';
return field;
}
</code></pre> |
2,544,905 | How to change an UILabel/UIFont's letter spacing? | <p>I've searched loads already and couldn't find an answer.</p>
<p>I have a normal UILabel, defined this way:</p>
<pre><code> UILabel *totalColors = [[[UILabel alloc] initWithFrame:CGRectMake(5, 7, 120, 69)] autorelease];
totalColors.text = [NSString stringWithFormat:@"%d", total];
totalColors.font = [UIFont fontWithName:@"Arial-BoldMT" size:60];
totalColors.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0];
totalColors.backgroundColor = [UIColor clearColor];
[self addSubview:totalColors];
</code></pre>
<p>And I wanted the horizontal spacing between letters, to be tighter, whilst mantaining the font size.</p>
<p>Is there a way to do this? It should be a pretty basic thing to do.</p>
<p>Cheers guys,
Andre</p>
<p><strong>UPDATE:</strong></p>
<p>So I was forced to do it like this:</p>
<pre><code>- (void) drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSelectFont (context, "Arial-BoldMT", 60, kCGEncodingMacRoman);
CGContextSetCharacterSpacing (context, -10);
CGContextSetTextDrawingMode (context, kCGTextFill);
CGContextSetRGBFillColor(context, 221/255.0, 221/255.0, 221/255.0, 221/255.0);
CGAffineTransform xform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, xform);
char* result = malloc(17);
sprintf(result, "%d", totalNumber);
CGContextShowTextAtPoint (context, 0, 54, result, strlen(result));
}
</code></pre>
<p>But I need to align this to the right.
I could do that manually if I knew the width of the drawn text, but it's proving near impossible to find that.</p>
<p>I've read about ATSU, but I couldn't find any examples.</p>
<p>This sucks :/</p> | 2,546,501 | 5 | 5 | null | 2010-03-30 12:02:26.377 UTC | 16 | 2015-11-17 22:20:59.837 UTC | 2010-03-30 14:30:57.11 UTC | null | 297,587 | null | 297,587 | null | 1 | 38 | iphone|xcode|uilabel|spacing|uifont | 47,357 | <p>I've come up with a solution for the letter spacing and the alignment to the right.</p>
<p>Here it goes:</p>
<pre><code> NSString *number = [NSString stringWithFormat:@"%d", total];
int lastPos = 85;
NSUInteger i;
for (i = number.length; i > 0; i--)
{
NSRange range = {i-1,1};
NSString *n = [number substringWithRange:range];
UILabel *digit = [[[UILabel alloc] initWithFrame:CGRectMake(5, 10, 35, 50)] autorelease];
digit.text = n;
digit.font = [UIFont fontWithName:@"Arial-BoldMT" size:60];
digit.textColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1.0];
digit.backgroundColor = [UIColor clearColor];
[self addSubview:digit];
CGSize textSize = [[digit text] sizeWithFont:[digit font]];
CGFloat textWidth = textSize.width;
CGRect rect = digit.frame;
rect.origin.x = lastPos - textWidth;
digit.frame = rect;
lastPos = rect.origin.x + 10;
}
</code></pre>
<p>The letter spacing is the "10" on the last line.
The alignment comes from the lastPos.</p>
<p>Hope this helps anyone out there.</p> |
2,731,297 | file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request? | <p><code>file_get_contents("php://input")</code> or <code>$HTTP_RAW_POST_DATA</code> - which one is better to get the body of JSON request?</p>
<p>And which request type (<code>GET</code> or <code>POST</code>) should I use to send JSON data when using client side <code>XmlHTTPRequest</code>?</p>
<p>My question was inspired from this answer:
<a href="https://stackoverflow.com/questions/813487/how-to-post-json-to-php-with-curl/813512#813512">How to post JSON to PHP with curl</a></p>
<p>Quote from that answer:</p>
<blockquote>
<p>From a protocol perspective <code>file_get_contents("php://input")</code> is actually more correct, since you're not really processing http multipart form data anyway.</p>
</blockquote> | 2,731,431 | 6 | 0 | null | 2010-04-28 16:20:28.063 UTC | 37 | 2021-12-17 10:48:29.437 UTC | 2018-05-11 12:01:01.593 UTC | null | 4,695,280 | null | 240,338 | null | 1 | 135 | php|json|xmlhttprequest | 303,025 | <p>Actually <code>php://input</code> allows you to read raw request body.</p>
<p><strong>It is a less memory intensive alternative to $HTTP_RAW_POST_DATA and does not need any special php.ini directives</strong>.
From <a href="https://www.php.net/manual/en/wrappers.php.php#wrappers.php.input" rel="noreferrer">Reference</a></p>
<blockquote>
<p><code>php://input</code> is not available with <code>enctype="multipart/form-data"</code>.</p>
</blockquote> |
3,027,832 | Drop all stored procedures in MySQL or using temporary stored procedures | <p>Is there a statement that can drop all stored procedures in MySQL?
Alternatively (if the first one is not possible), is there such thing as temporary stored procedures in MySQL? Something similar to temporary tables?</p> | 3,028,277 | 7 | 2 | null | 2010-06-12 07:07:23.363 UTC | 9 | 2017-01-21 21:25:55.157 UTC | 2017-01-21 21:25:55.157 UTC | null | 4,370,109 | null | 241,379 | null | 1 | 21 | mysql|stored-procedures | 32,302 | <p>Since DROP PROCEDURE and DROP FUNCTION does not allow sub selects, I thought it might be possible to perform the operation through another stored procedure, but alas, MySQL does not allow stored procedures to drop other stored procedures.</p>
<p>I tried to trick MySQL to to this anyway by creating prepared statements and thus separating the drop call somewhat from the stored procedure, but I've had no luck.</p>
<p>So therefore my only contribution is this select statement which creates a list of the statements needed to drop all stored procedures and functions.</p>
<pre><code>SELECT
CONCAT('DROP ',ROUTINE_TYPE,' `',ROUTINE_SCHEMA,'`.`',ROUTINE_NAME,'`;') as stmt
FROM information_schema.ROUTINES;
</code></pre> |
3,005,095 | Can I get name of all tables of SQL Server database in C# application? | <p>I want to get name of all table of SQL Server database in my C# application. Is It possible? Plz tell me Solution.</p> | 3,005,157 | 9 | 0 | null | 2010-06-09 10:51:33.76 UTC | 10 | 2017-11-20 09:08:24.597 UTC | 2010-06-09 11:01:38.837 UTC | null | 41,956 | null | 355,063 | null | 1 | 38 | c#|sql-server | 86,667 | <p>It is as simple as this:</p>
<pre><code>DataTable t = _conn.GetSchema("Tables");
</code></pre>
<p>where <code>_conn</code> is a SqlConnection object that has already been connected to the correct database.</p> |
2,442,525 | How to select min and max values of a column in a datatable? | <p>For the following datatable column, what is the fastest way to get the min and max values?</p>
<pre><code>AccountLevel
0
1
2
3
</code></pre> | 2,442,717 | 11 | 0 | null | 2010-03-14 14:56:43.563 UTC | 11 | 2017-02-16 21:26:59.627 UTC | null | null | null | null | 14,118 | null | 1 | 71 | c#|.net|select|datatable | 230,264 | <pre><code>int minAccountLevel = int.MaxValue;
int maxAccountLevel = int.MinValue;
foreach (DataRow dr in table.Rows)
{
int accountLevel = dr.Field<int>("AccountLevel");
minAccountLevel = Math.Min(minAccountLevel, accountLevel);
maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);
}
</code></pre>
<p>Yes, this really is the fastest way. Using the Linq <code>Min</code> and <code>Max</code> extensions will always be slower because you have to iterate twice. You could potentially use Linq <code>Aggregate</code>, but the syntax isn't going to be much prettier than this already is.</p> |
2,955,251 | PHP function to make slug (URL string) | <p>I want to have a function to create slugs from Unicode strings, e.g. <code>gen_slug('Andrés Cortez')</code> should return <code>andres-cortez</code>. How should I do that?</p> | 2,955,878 | 27 | 9 | null | 2010-06-02 05:41:17.31 UTC | 112 | 2022-08-16 07:59:53.64 UTC | 2019-06-10 09:42:39.977 UTC | user719662 | null | null | 338,840 | null | 1 | 214 | php|internationalization|slug | 329,684 | <p>Instead of a lengthy replace, try this one:</p>
<pre><code>public static function slugify($text, string $divider = '-')
{
// replace non letter or digits by divider
$text = preg_replace('~[^\pL\d]+~u', $divider, $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, $divider);
// remove duplicate divider
$text = preg_replace('~-+~', $divider, $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
</code></pre>
<p>This was based off the one in Symfony's Jobeet tutorial.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.