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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16,699,593 | Uninitialized Object vs Object Initialized to NULL | <p>I'm working in Java.</p>
<p>I commonly setup some objects as such:</p>
<pre><code>public class Foo {
private SomeObject someName;
// do stuff
public void someMethod() {
if (this.someName != null) {
// do some stuff
}
}
}
</code></pre>
<p>The question is: Is <code>someName</code> in this example equated to <code>null</code>, as-in I can <code>reliably for all objects</code> assume null-checking uninitialized objects will be accurate?</p> | 16,699,632 | 2 | 0 | null | 2013-05-22 18:57:19.753 UTC | 24 | 2019-03-06 20:04:28.897 UTC | null | null | null | null | 2,161,954 | null | 1 | 103 | java|null|initialization | 102,372 | <p>Correct, both static and instance members of reference type not explicitly initialized are set to <code>null</code> by Java. The same rule applies to array members.</p>
<p>From the <a href="http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf">Java Language Specification</a>, section 4.12.5:</p>
<blockquote>
<p><strong>Initial Values of Variables</strong></p>
<p>Every variable in a program must have a value before its value is used:</p>
<p>Each class variable, instance variable, or array component is initialized with a
default value when it is created</p>
<p>[...] For all reference types, the default value is <code>null</code>.</p>
</blockquote>
<p>Note that the above rule excludes local variables: they must be initialized explicitly, otherwise the program will not compile.</p> |
4,268,288 | How can I best find out how django works internally? | <p>so I have been playing around with django for a bit and I really do like this framework. However, I would like to understand better how it actually works 'under the covers'. </p>
<p>Here is my current view of client-server-django world, which is very rough and will probably make your toenails curl (sorry)...</p>
<ol>
<li>The browser sends a Http request to the server.</li>
<li>The server does its magic and dumps the request via the CGI to django (?)</li>
<li>Some part of django (which?) receives the request and turns it into a django request object.</li>
<li>The request object wanders on some nebulous paths through the middleware which does strange things with it.</li>
<li>The request object finally ends up in some function (which?) which looks at the urls, takes the patterns out of urls.py and calls up a view function.</li>
<li>The view functions do their magic (with models and templates as partners in vice) , this is probably where I have the strongest illusion of understanding (well, apart from the database abstraction magic, that is... ;)</li>
<li>The view functions returns an HttpResponse object, I guess this is returned on some nebulous paths to the CGI.</li>
<li>Webserver takes over again and sends the Http response to the client.</li>
</ol>
<p>Ok, so what the heck is my question you ask? Well, how does this all work, really? I am not expecting that you spoon-feed me everything... I suspect that the answer will ultimately be to "read the source, luke", however, I would be grateful if</p>
<ol>
<li>You could clear up my grosses misconseptions</li>
<li>tell me where to start? What I would like to do is grap a debugger and just walk through the process a couple of times, but I don't really know where to get started</li>
<li>you could point me to any documents that explain this well... yes, I have heard of this google thing but haven't really found anything super-useful.</li>
</ol>
<p>thanks a lot
Paul</p> | 4,268,658 | 2 | 0 | null | 2010-11-24 15:11:44.807 UTC | 13 | 2017-10-15 01:17:58.847 UTC | null | null | null | null | 346,587 | null | 1 | 19 | django|cgi|webserver|internals | 5,876 | <p>Watch James Bennett's <a href="https://www.youtube.com/watch?v=tkwZ1jG3XgA" rel="nofollow noreferrer">Django in Depth</a> tutorial from Pycon 2015.</p>
<p>From the <a href="http://us.pycon.org/2010/tutorials/bennet_django/" rel="nofollow noreferrer">Pycon website</a>, here's the abstract of James' talk:</p>
<blockquote>
<p>Most books, tutorials and other documentation for Django take a high-level approach to its components and APIs, and so barely scratch the surface of the framework. In this tutorial, however, we'll take a detailed look under the hood, covering everything from the guts of the ORM to the innards of the template system to how the admin interface really works.</p>
<p>Whether you're the newest of newbies or the most seasoned of application developers, you'll come away with a deeper knowledge of Django, and a plethora of new tips and tricks you can use in your own applications.</p>
</blockquote> |
4,161,359 | Save BitmapImage to File | <p>I am working on a program that downloads images from a URL to a bitmapimageand displays it. Next I try to save the bitmapimage to the harddrive using jpegbitmapencoder. The file is successfully created but the actual jpeg image is empty or 1 black pixel.</p>
<pre><code>public Guid SavePhoto(string istrImagePath)
{
ImagePath = istrImagePath;
BitmapImage objImage = new BitmapImage(
new Uri(istrImagePath, UriKind.RelativeOrAbsolute));
PictureDisplayed.Source = objImage;
savedCreationObject = objImage;
Guid photoID = System.Guid.NewGuid();
string photolocation = photoID.ToString() + ".jpg"; //file name
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(objImage));
using (FileStream filestream = new FileStream(photolocation, FileMode.Create))
{
encoder.Save(filestream);
}
return photoID;
}
</code></pre>
<p>This is the function that saves and displays the photo. The photo is displayed correctly but again when it is saved I get an empty jpeg or 1 black pixel.</p> | 4,161,485 | 2 | 1 | null | 2010-11-12 03:24:03.523 UTC | 6 | 2019-06-22 07:35:49.88 UTC | 2019-06-22 07:35:49.88 UTC | null | 1,136,211 | null | 505,329 | null | 1 | 22 | c#|save|bitmapimage | 73,746 | <p>When you create your BitmapImage from a Uri, time is required to download the image.</p>
<p>If you check the following property, the value will likely be TRUE</p>
<pre><code>objImage.IsDownloading
</code></pre>
<p>As such, you much attach a listener to the DownloadCompleted event handler and move all processing to that EventHandler.</p>
<pre><code>objImage.DownloadCompleted += objImage_DownloadCompleted;
</code></pre>
<p>Where that handler will look something like:</p>
<pre><code>private void objImage_DownloadCompleted(object sender, EventArgs e)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
Guid photoID = System.Guid.NewGuid();
String photolocation = photoID.ToString() + ".jpg"; //file name
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));
using (var filestream = new FileStream(photolocation, FileMode.Create))
encoder.Save(filestream);
}
</code></pre>
<p>You will likely also want to add another EventHandler for DownloadFailed in order to gracefully handle any error cases. </p>
<p><strong>Edit</strong></p>
<p>Added full sample class based on Ben's comment:</p>
<pre><code>public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SavePhoto("http://www.google.ca/intl/en_com/images/srpr/logo1w.png");
}
public void SavePhoto(string istrImagePath)
{
BitmapImage objImage = new BitmapImage(new Uri(istrImagePath, UriKind.RelativeOrAbsolute));
objImage.DownloadCompleted += objImage_DownloadCompleted;
}
private void objImage_DownloadCompleted(object sender, EventArgs e)
{
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
Guid photoID = System.Guid.NewGuid();
String photolocation = photoID.ToString() + ".jpg"; //file name
encoder.Frames.Add(BitmapFrame.Create((BitmapImage)sender));
using (var filestream = new FileStream(photolocation, FileMode.Create))
encoder.Save(filestream);
}
}
</code></pre> |
4,275,440 | How to Convert Hex String to Hex Number | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3705429/how-do-i-convert-hex-string-into-signed-integer">How do I convert hex string into signed integer?</a> </p>
</blockquote>
<p>example:"3A" convert to 0x3A,thanks a lot!</p> | 4,275,492 | 2 | 2 | null | 2010-11-25 09:22:59.88 UTC | 3 | 2010-11-25 09:29:04.437 UTC | 2017-05-23 12:34:27.447 UTC | null | -1 | null | 519,909 | null | 1 | 43 | c#|hex | 71,536 | <pre><code>Convert.ToInt32("3A", 16)
</code></pre> |
9,912,590 | Adding event hovertext in fullcalendar | <p>I'm trying to include a hover text on events in a month calendar page of full calendar.</p>
<p>I have and array object declaring the events that need to be on the page as loaded in by a php script. It looks as followed:</p>
<pre><code>$('#calendar').fullCalendar({
events: [
{
title : 'event1',
start : '2010-01-01'
},
{
title : 'event2',
start : '2010-01-05',
end : '2010-01-07'
}
]
</code></pre>
<p>});</p>
<p>I am trying to use the eventMouseover function to include a hover text with each event. This function's prototype is as followed: function( event, jsEvent, view ) { } Where event is the event object, jsEvent is the native JavaScript event with low-level information such as mouse coordinates. and the view holds the view object of fullcalendar. I am not able to correctly call the arguments of this function. My info is coming from here: <a href="http://arshaw.com/fullcalendar/docs/mouse/eventMouseover/" rel="noreferrer">http://arshaw.com/fullcalendar/docs/mouse/eventMouseover/</a> and I'm totally cool with other ways of achieving a hovertext on each event. Thank you.</p> | 12,466,543 | 8 | 0 | null | 2012-03-28 17:23:19.823 UTC | 6 | 2022-07-02 09:07:16.92 UTC | 2013-12-05 11:46:44.827 UTC | null | 2,567,813 | null | 1,298,803 | null | 1 | 15 | javascript|jquery|fullcalendar | 43,253 | <p>You're on the right track. I did something similar to show the event end time at the bottom of the event in agenda view.</p>
<p><strong>Options on the calendar:</strong></p>
<pre><code>eventMouseover: function(event, jsEvent, view) {
$('.fc-event-inner', this).append('<div id=\"'+event.id+'\" class=\"hover-end\">'+$.fullCalendar.formatDate(event.end, 'h:mmt')+'</div>');
}
eventMouseout: function(event, jsEvent, view) {
$('#'+event.id).remove();
}
</code></pre>
<p><strong>CSS for the hover over:</strong></p>
<pre><code>.hover-end{padding:0;margin:0;font-size:75%;text-align:center;position:absolute;bottom:0;width:100%;opacity:.8}
</code></pre>
<p>Hopefully this helps you!</p> |
9,964,823 | How to check if a file is empty in Bash? | <p>I have a file called <em><strong>diff.txt</strong></em>. I Want to check whether it is empty.</p>
<p>I wrote a bash script something like below, but I couldn't get it work.</p>
<pre><code>if [ -s diff.txt ]
then
touch empty.txt
rm full.txt
else
touch full.txt
rm emtpy.txt
fi
</code></pre> | 9,964,890 | 11 | 4 | null | 2012-04-01 13:41:05.617 UTC | 48 | 2022-04-18 16:41:54.807 UTC | 2021-06-15 09:38:46.53 UTC | null | 108,207 | null | 1,149,061 | null | 1 | 277 | linux|bash|unix|file-handling|is-empty | 479,271 | <p>Misspellings are irritating, aren't they? Check your spelling of <code>empty</code>, but then also try this:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash -e
if [ -s diff.txt ]; then
# The file is not-empty.
rm -f empty.txt
touch full.txt
else
# The file is empty.
rm -f full.txt
touch empty.txt
fi
</code></pre>
<p>I like shell scripting a lot, but one disadvantage of it is that the shell cannot help you when you misspell, whereas a compiler like your C++ compiler can help you.</p>
<p>Notice incidentally that I have swapped the roles of <code>empty.txt</code> and <code>full.txt</code>, as @Matthias suggests.</p> |
9,989,687 | Maven Dependencies Eclipse | <p>I added the below depdencies in my pom</p>
<pre><code> <dependency>
<artifactId>richfaces-api</artifactId>
<groupId>org.richfaces.framework</groupId>
<version>3.3.3.Final</version>
</dependency>
<dependency>
<groupId>org.richfaces.ui</groupId>
<artifactId>richfaces-ui</artifactId>
<version>3.3.3.Final</version>
</dependency>
<dependency>
<artifactId>richfaces-impl</artifactId>
<groupId>org.richfaces.framework</groupId>
<version>3.3.3.Final</version>
</dependency>
</code></pre>
<p>When I did mvn clean install in command prompt , these dependency jars got downloaded. However in Eclipse this is not showing under referenced libraries section. The other jar files that are part of dependencies are showing up though. Is there anything that I must do for this to get reflected? Thanks.</p> | 9,989,946 | 5 | 4 | null | 2012-04-03 08:28:04.71 UTC | 5 | 2021-06-08 17:09:57.7 UTC | 2012-04-03 08:46:04.36 UTC | null | 1,228,454 | null | 1,042,646 | null | 1 | 25 | java|maven|richfaces|pom.xml | 86,539 | <p>This depends on how you have integrated Maven in Eclipse:</p>
<ul>
<li>No Eclipse integration: run <code>mvn eclipse:eclipse</code> on command line to refresh the project definition.</li>
<li>M2Eclipse or m2e: Update the POM file (select, press <em>F5</em>), then right-click the project, <em>Maven > Update Dependencies</em></li>
</ul>
<p>This should fix it.</p> |
10,122,813 | Tracking flexitime using Emacs (& org-mode) | <p>So, at work we use flexitime (flex hours, flexi hours...) which is nice but can be hard to keep track of. I'm currently using org-mode to keep track of my hours (<code>org-clock-(out|in)</code>) but I'd like to extend that to automagically calculate if I've worked more than 8 hours (surplus time should be added to my flexitime 'account') or less (depending on how long lunch break I took etc), the balance on my flexitime 'account' and such.</p>
<p>Does anyone else use Emacs for this? </p>
<p>I'm currently using a very basic setup to track my time:</p>
<pre class="lang-lisp prettyprint-override"><code>(defun check-in ()
(interactive)
(let (pbuf (current-buffer))
(find-file (convert-standard-filename "whatnot"))
(goto-char (point-max))
(insert "\n")
(org-insert-heading)
(org-insert-time-stamp (current-time))
(org-clock-in)
(save-buffer)
(switch-to-buffer pbuf)))
(defun check-out ()
(interactive)
(let (pbuf (current-buffer))
(find-file (convert-standard-filename "whatnot"))
(goto-char (point-max))
(org-clock-out)
(save-buffer)
(switch-to-buffer pbuf)))
</code></pre> | 12,758,207 | 1 | 1 | null | 2012-04-12 11:40:10.827 UTC | 11 | 2012-10-06 08:53:07.103 UTC | 2012-09-25 01:21:00.747 UTC | null | 523,044 | null | 285,103 | null | 1 | 38 | emacs|org-mode | 2,500 | <p>Assuming that I understood your problem correctly, I hacked together a quick solution. First, you should ensure that you create only one outline entry per day, if you are checking in and out multiple times. Define the following function that'll compute the overtime for a given day.</p>
<pre class="lang-lisp prettyprint-override"><code>(defun compute-overtime (duration-string)
"Computes overtime duration string for the given time DURATION-STRING."
(let (minutes-in-a-workday
work-minutes
overtime-minutes)
(defconst minutes-in-a-workday 480)
(setq work-minutes (org-duration-string-to-minutes duration-string)
overtime-minutes (- work-minutes minutes-in-a-workday))
(if (< overtime-minutes 0) (setq overtime-minutes 0))
(org-minutes-to-hh:mm-string overtime-minutes)))
</code></pre>
<p>Then, use this in a clock table formula in the file <code>whatnot</code>.</p>
<pre><code>#+BEGIN: clocktable :maxlevel 1 :emphasize nil :scope file :formula "$3='(compute-overtime $2)::@2$3=string(\"Overtime\")"
#+END: clocktable
</code></pre>
<p>Hit <kbd>C-c C-c</kbd> when you are on the clock table to regenerate it.</p>
<p>You can get the total overtime by summing the overtimes using another formula. But, I haven't worked that out.</p> |
9,958,846 | Converting int arrays to string arrays in numpy without truncation | <p>Trying to convert int arrays to string arrays in numpy</p>
<pre><code>In [66]: a=array([0,33,4444522])
In [67]: a.astype(str)
Out[67]:
array(['0', '3', '4'],
dtype='|S1')
</code></pre>
<p>Not what I intended</p>
<pre><code>In [68]: a.astype('S10')
Out[68]:
array(['0', '33', '4444522'],
dtype='|S10')
</code></pre>
<p>This works but I had to know 10 was big enough to hold my longest string. Is there a way of doing this easily without knowing ahead of time what size string you need? It seems a little dangerous that it just quietly truncates your string without throwing an error.</p> | 9,958,935 | 5 | 1 | null | 2012-03-31 19:10:50.617 UTC | 13 | 2020-11-15 21:47:44.343 UTC | 2020-11-15 21:47:44.343 UTC | null | 9,209,546 | null | 1,024,495 | null | 1 | 41 | python|arrays|string|numpy | 121,996 | <p>Again, this can be solved in pure Python:</p>
<pre><code>>>> map(str, [0,33,4444522])
['0', '33', '4444522']
</code></pre>
<p>Or if you need to convert back and forth:</p>
<pre><code>>>> a = np.array([0,33,4444522])
>>> np.array(map(str, a))
array(['0', '33', '4444522'],
dtype='|S7')
</code></pre> |
9,893,217 | Error with NSJSONSerialization - Invalid type in JSON write (Menu) | <p>I have an App using core data with 3 entities with very similar attributes. The relationship is such as:</p>
<p>Branch ->> Menu ->> Category ->> FoodItem </p>
<p>Each entity has an associated class: example</p>
<p><img src="https://i.stack.imgur.com/cJwYB.png" alt="enter image description here"></p>
<p><strong>I am trying to generate JSON representation of the data in sqlite database.</strong></p>
<pre><code>//gets a single menu record which has some categories and each of these have some food items
id obj = [NSArray arrayWithObject:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
</code></pre>
<p>But instead of JSON, i get a SIGABRT error.</p>
<pre><code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Menu)'
</code></pre>
<p>Any ideas how to fix it or how to make the entity classes (Branch, Menu etc) JSON serialization compatible? </p> | 9,893,370 | 4 | 0 | null | 2012-03-27 15:58:28.28 UTC | 8 | 2016-05-23 17:07:39.19 UTC | null | null | null | null | 187,025 | null | 1 | 52 | iphone|objective-c|json|serialization|ios5 | 69,039 | <p>That's because your "Menu" class is not serializable in JSON. Bascially the language doesn't know how your object should be represented in JSON (which fields to include, how to represent references to other objects...)</p>
<p>From the <a href="http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html" rel="noreferrer">NSJSONSerialization Class Reference</a></p>
<blockquote>
<p>An object that may be converted to JSON must have the following
properties:</p>
<ul>
<li>The top level object is an NSArray or NSDictionary. </li>
<li>All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.</li>
<li>All dictionary keys are instances of NSString. </li>
<li>Numbers are not NaN or infinity.</li>
</ul>
</blockquote>
<p>This means that the language knows how to serialize dictionaries. So a simple way to get a JSON representation from your menu is to provide a Dictionary representation of your Menu instances, which you will then serialize into JSON:</p>
<pre><code>- (NSDictionary *)dictionaryFromMenu:(Menu)menu {
[NSDictionary dictionaryWithObjectsAndKeys:[menu.dateUpdated description],@"dateUpdated",
menu.categoryId, @"categoryId",
//... add all the Menu properties you want to include here
nil];
}
</code></pre>
<p>And you could will use it like this :</p>
<pre><code>NSDictionary *menuDictionary = [self dictionaryFromMenu:[[DataStore singleton] getHomeMenu]];
NSError *err;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:menuDictionary options:NSJSONWritingPrettyPrinted error:&err];
NSLog(@"JSON = %@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
</code></pre> |
10,069,204 | Function declarations inside if/else statements? | <p>How are function declarations handled?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var abc = '';
if (1 === 0) {
function a() {
abc = 7;
}
} else if ('a' === 'a') {
function a() {
abc = 19;
}
} else if ('foo' === 'bar') {
function a() {
abc = 'foo';
}
}
a();
document.write(abc); //writes "foo" even though 'foo' !== 'bar'</code></pre>
</div>
</div>
</p>
<p>This example produces different outputs in Chrome and Firefox. Chrome outputs <code>foo</code> while FF outputs <code>19</code>.<br /></p> | 10,069,457 | 4 | 9 | null | 2012-04-09 05:17:54.397 UTC | 20 | 2021-03-31 04:04:52.013 UTC | 2021-03-31 04:04:52.013 UTC | null | 11,926,970 | null | 947,478 | null | 1 | 55 | javascript|function|scope | 57,503 | <p>When this question was asked, ECMAScript 5 (ES5) was prevalent. In strict mode of ES5, function declarations cannot be nested inside of an <code>if</code> block as shown in the question. In non-strict mode, the results were unpredictable. Different browsers and engines implemented their own rules for how they would handle function declarations inside blocks.</p>
<p>As of 2018, many browsers support ECMAScript 2015 (ES2015) to the extent that <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-block" rel="noreferrer">function declarations are now allowed inside blocks</a>. In an ES2015 environment, a function declaration inside of a block will be scoped inside that block. The code in the question will result in an undefined function error because the function <code>a</code> is only declared within the scope of <code>if</code> statements and therefore doesn't exist in the global scope.</p>
<p>If you need to conditionally define a function, then you should use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#Constructor_vs._declaration_vs._expression" rel="noreferrer">function expressions</a>.</p> |
9,854,995 | Javascript dynamically invoke object method from string | <p>Can I dynamically call an object method having the method name as a string? I would imagine it like this:</p>
<pre><code>var FooClass = function() {
this.smile = function() {};
}
var method = "smile";
var foo = new FooClass();
// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();
</code></pre> | 9,855,029 | 5 | 0 | null | 2012-03-24 19:51:43.363 UTC | 22 | 2020-05-08 23:43:43.463 UTC | null | null | null | null | 326,257 | null | 1 | 114 | javascript|oop|dynamic|methods|invoke | 74,616 | <p>if the name of the property is stored in a variable, use <code>[]</code></p>
<pre><code>foo[method]();
</code></pre> |
7,716,691 | How to properly handle errors in Express? | <p>I am beginning to work with Express JS and have run into an issue. I can't seem to figure out the proper way to handle errors.</p>
<p>For example, I have a web services API that serves an object called "event". I'd like to return a simple string of "cannot find event" when a user submits an event id that isn't found. Here is how I'm currently structuring my code:</p>
<pre><code>app.get('/event/:id', function(req, res, next) {
if (req.params.id != 1) {
next(new Error('cannot find event ' + req.params.id));
}
req.send('event found!');
});
</code></pre>
<p>When I submit an <em>id</em> other than 1, Node crashes with the following output:</p>
<pre><code>http.js:527
throw new Error("Can't set headers after they are sent.");
^
Error: Can't set headers after they are sent.
at ServerResponse.<anonymous> (http.js:527:11)
at ServerResponse.setHeader (/usr/local/kayak/node_modules/express/node_modules/connect/lib/patch.js:62:20)
at /usr/local/kayak/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js:72:19
at [object Object].<anonymous> (fs.js:107:5)
at [object Object].emit (events.js:61:17)
at afterRead (fs.js:878:12)
at wrapper (fs.js:245:17)
</code></pre>
<p>From what I can tell by using the node.js <em>debugger</em>, execution of the block of code continues after <code>next()</code> is called, meaning that <code>req.send('event found!')</code> tries to run. I don't want this to happen.</p>
<p>The only workaround that I've found is to simply throw a <code>new Error()</code> instead of "next-ing" it, but this results in a default Express HTML error page being generated. I'd like a little more control than that.</p>
<p>I have taken the time to read over the <a href="http://expressjs.com/guide.html#error-handling" rel="noreferrer">error handling section</a> of the Express documentation, but I couldn't make sense of it.</p> | 7,716,860 | 3 | 0 | null | 2011-10-10 17:53:00.61 UTC | 13 | 2017-09-07 09:21:08.327 UTC | 2015-11-14 16:08:40.223 UTC | null | 3,924,118 | null | 752,837 | null | 1 | 24 | javascript|node.js|middleware|express | 35,863 | <p>You'll want to check out <a href="http://expressjs.com/guide/error-handling.html">Express Error Handling</a>. From there:</p>
<pre><code>app.param('userId', function(req, res, next, id) {
User.get(id, function(err, user) {
if (err) return next(err);
if (!user) return next(new Error('failed to find user'));
req.user = user;
next();
});
});
</code></pre>
<p>The sweetspot that you are missing is the <strong><code>return</code></strong> <code>next(...)</code> </p> |
11,957,595 | MongoDB / Pymongo Query with Datetime | <p>I am trying to retrieve the data I have inserted into mongodb via pymongo.</p>
<p>My code for insert is below (after parsing via regex)</p>
<pre><code>if connection is not None:
db.model.insert({"time": datetime.datetime(int(int3), int(int1),
int(int2), int(int4),
int(int5), int(int6),
int(int7))})
</code></pre>
<p>I then entered two data points in the shell.</p>
<pre><code>>>> start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764)
>>> end = datetime.datetime(2012, 2, 2, 6, 55, 3, 381)
</code></pre>
<p>I then tried to query the range of data between these two data points and received what is returned.</p>
<pre><code>>>> db.wing_model.find({'time': {'$gte': start, '$lt': end}})
<pymongo.cursor.Cursor object at 0x0301CFD0>
>>> db.wing_model.find({'time': {'$gte': start, '$lt': end}})
<pymongo.cursor.Cursor object at 0x0301C110>
</code></pre>
<p>Data is listed below.</p>
<pre><code>[02/02/2012 06:32:07.334][INFO]
[02/02/2012 06:32:07.334][INFO]
[02/02/2012 06:32:07.334][INFO]
[02/02/2012 06:32:13.711][INFO]
[02/02/2012 06:32:13.711][INFO]
[02/02/2012 06:32:13.711][INFO]
[02/02/2012 06:32:22.473][INFO]
[02/02/2012 06:32:22.473][INFO]
[02/02/2012 06:32:22.473][INFO]
[02/02/2012 06:35:06.764][INFO]
[02/02/2012 06:35:06.765][INFO]
[02/02/2012 06:35:06.765][INFO]
[02/02/2012 06:54:52.008][INFO]
[02/02/2012 06:54:52.008][INFO]
[02/02/2012 06:54:52.008][INFO]
[02/02/2012 06:54:59.512][INFO]
[02/02/2012 06:54:59.512][INFO]
[02/02/2012 06:54:59.512][INFO]
[02/02/2012 06:55:03.381][INFO]
[02/02/2012 06:55:03.381][INFO]
[02/02/2012 06:55:03.381][INFO]
[02/02/2012 06:55:06.142][INFO]
[02/02/2012 06:55:06.142][INFO]
[02/02/2012 06:55:06.142][INFO]
[02/02/2012 06:55:09.652][INFO]
[02/02/2012 06:55:09.652][INFO]
[02/02/2012 06:55:09.652][INFO]
[02/02/2012 06:55:13.396][INFO]
[02/02/2012 06:55:13.396][INFO]
</code></pre>
<p>How do I get my query to return everything between the 'start' and 'end' data? </p>
<p>Also, how do I receive this in an intelligible form?</p>
<p>Finally, why does the same query return different cursor object locations?</p>
<p>Thank you.</p> | 11,957,746 | 2 | 0 | null | 2012-08-14 17:26:52.463 UTC | 4 | 2019-01-11 21:06:40.613 UTC | 2012-08-14 17:33:04.717 UTC | null | 19,556 | null | 1,590,999 | null | 1 | 14 | python|mongodb|datetime|pymongo | 42,179 | <p>Repeating existing basic tutorial documentation:</p>
<pre><code>start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764)
end = datetime.datetime(2012, 2, 2, 6, 55, 3, 381)
for doc in db.wing_model.find({'time': {'$gte': start, '$lt': end}}):
print doc
</code></pre>
<blockquote>
<p>Finally, why does the same query return different cursor object
locations?</p>
</blockquote>
<p>Where should that be the case? </p>
<p>You see two different cursor instances which will likely return the same result set - or?</p> |
11,777,844 | java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener when using MyFaces with WASCE/Geronimo | <p>I am trying to create a simple JSF web application using MyFaces v 2.1 with WebSphere Application Server Community Edition v3.0.0.1 and Eclipse Juno but when I try to run the application the following error is returned</p>
<pre><code> java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
org.apache.geronimo.common.DeploymentException: java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.createWebAppClassFinder(AbstractWebModuleBuilder.java:665)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.configureBasicWebModuleAttributes(AbstractWebModuleBuilder.java:698)
at org.apache.geronimo.tomcat.deployment.TomcatModuleBuilder.addGBeans(TomcatModuleBuilder.java:469)
at org.apache.geronimo.j2ee.deployment.SwitchingModuleBuilder.addGBeans(SwitchingModuleBuilder.java:174)
at org.apache.geronimo.j2ee.deployment.EARConfigBuilder.buildConfiguration(EARConfigBuilder.java:764)
at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:255)
at org.apache.geronimo.deployment.Deployer.deploy(Deployer.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
at org.apache.geronimo.kernel.KernelGBean.invoke(KernelGBean.java:344)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.apache.geronimo.gbean.runtime.ReflectionMethodInvoker.invoke(ReflectionMethodInvoker.java:34)
at org.apache.geronimo.gbean.runtime.GBeanOperation.invoke(GBeanOperation.java:131)
at org.apache.geronimo.gbean.runtime.GBeanInstance.invoke(GBeanInstance.java:883)
at org.apache.geronimo.kernel.basic.BasicKernel.invoke(BasicKernel.java:245)
at org.apache.geronimo.system.jmx.MBeanGBeanBridge.invoke(MBeanGBeanBridge.java:172)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:773)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1438)
at javax.management.remote.rmi.RMIConnectionImpl.access$200(RMIConnectionImpl.java:83)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1276)
at java.security.AccessController.doPrivileged(AccessController.java:284)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1378)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:799)
at sun.reflect.GeneratedMethodAccessor73.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
at sun.rmi.transport.Transport$1.run(Transport.java:171)
at java.security.AccessController.doPrivileged(AccessController.java:284)
at sun.rmi.transport.Transport.serviceCall(Transport.java:167)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:547)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:802)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:661)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:897)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:919)
at java.lang.Thread.run(Thread.java:736)
Caused by: java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:513)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:429)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:417)
at org.apache.geronimo.hook.equinox.GeronimoClassLoader.loadClass(GeronimoClassLoader.java:85)
at java.lang.ClassLoader.loadClass(ClassLoader.java:626)
at org.eclipse.osgi.internal.loader.BundleLoader.loadClass(BundleLoader.java:345)
at org.eclipse.osgi.framework.internal.core.BundleHost.loadClass(BundleHost.java:229)
at org.eclipse.osgi.framework.internal.core.AbstractBundle.loadClass(AbstractBundle.java:1207)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.addClass(AbstractWebModuleBuilder.java:670)
at org.apache.geronimo.web25.deployment.AbstractWebModuleBuilder.createWebAppClassFinder(AbstractWebModuleBuilder.java:661)
... 45 more
</code></pre>
<p>Presumably the error is occurring because the MyFaces jar files are not in the class path however I cannot figure out where I’m going wrong as the build path in Eclipse contains the required jars. I’ve also tried copying the jar files into the WEB-INF/lib directory but to no avail.</p>
<p>The screenshot below shows the project structure along with the libraries.</p>
<p><img src="https://i.stack.imgur.com/Ab9gK.jpg" alt="Eclipse Project Structure"></p>
<p>Is there something specific I need to do either in Eclipse or WASCE to include the jar files or does the problem lie elsewhere?</p> | 11,778,091 | 4 | 1 | null | 2012-08-02 12:53:05.483 UTC | 6 | 2015-12-21 21:30:08.93 UTC | 2012-08-02 13:09:08.96 UTC | null | 157,882 | null | 1,274,662 | null | 1 | 22 | java|jsf|myfaces|geronimo|websphere-ce | 69,465 | <pre><code>Caused by: java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
</code></pre>
<p>The missing class is part of <a href="http://javaserverfaces.java.net">Mojarra</a>, which is actually the competitor of <a href="http://myfaces.apache.org">MyFaces</a>.</p>
<p>You shouldn't need that class at all when using MyFaces. This exception can have the following possible causes:</p>
<ul>
<li><p>There's a manually definied <code><listener></code> entry in webapp's <code>web.xml</code> or the <code>web-fragment.xml</code> of any of the deployed JARs in <code>/WEB-INF/lib</code> which references this Mojarra-specific listener class. </p></li>
<li><p>There's somewhere a loose Mojarra <code>.tld</code> file in the classpath (very unlikely, who would ever extract a JAR file and put its loose contents in the classpath?). TLD files get autoinitialized and can contain a <code><listener></code> entry which can trigger autoregistration of a <code>ServletContextListener</code> implementation (such as the Mojarra <code>ConfigureListener</code>).</p></li>
</ul>
<p>Those conflicts can be fixed by just removing it.</p> |
11,615,504 | Parse dates when YYYYMMDD and HH are in separate columns using pandas in Python | <p>I have a simple question related with csv files and parsing datetime.</p>
<p>I have a csv file that look like this:</p>
<pre><code>YYYYMMDD, HH, X
20110101, 1, 10
20110101, 2, 20
20110101, 3, 30
</code></pre>
<p>I would like to read it using pandas (read_csv) and have it in a dataframe indexed by the datetime. So far I've tried to implement the following:</p>
<pre><code>import pandas as pnd
pnd.read_csv("..\\file.csv", parse_dates = True, index_col = [0,1])
</code></pre>
<p>and the result I get is:</p>
<pre><code> X
YYYYMMDD HH
2011-01-01 2012-07-01 10
2012-07-02 20
2012-07-03 30
</code></pre>
<p>As you see the parse_dates in converting the HH into a different date.</p>
<p>Is there a simple and efficient way to combine properly the column "YYYYMMDD" with the column "HH" in order to have something like this? :</p>
<pre><code> X
Datetime
2011-01-01 01:00:00 10
2011-01-01 02:00:00 20
2011-01-01 03:00:00 30
</code></pre>
<p>Thanks in advance for the help.</p> | 11,617,682 | 2 | 0 | null | 2012-07-23 15:20:43.083 UTC | 21 | 2017-01-05 00:03:47.08 UTC | 2017-01-05 00:03:47.08 UTC | null | 2,336,654 | null | 1,520,997 | null | 1 | 26 | python|pandas | 19,966 | <p>If you pass a list to <code>index_col</code>, it means you want to create a hierarchical index out of the columns in the list.</p>
<p>In addition, the <code>parse_dates</code> keyword can be set to either True or a list/dict. If True, then it tries to parse individual columns as dates, otherwise it combines columns to parse a single date column.</p>
<p>In summary, what you want to do is:</p>
<pre><code>from datetime import datetime
import pandas as pd
parse = lambda x: datetime.strptime(x, '%Y%m%d %H')
pd.read_csv("..\\file.csv", parse_dates = [['YYYYMMDD', 'HH']],
index_col = 0,
date_parser=parse)
</code></pre> |
11,616,493 | XCode "Too few items in teams" error when refreshing provisioning profiles | <p>I'm trying to build my apps. I've installed the provisioning profiles that my team has set up. I've installed my developer certificate and the WWDR certificate. But when I refresh my provisioning profile library it throws this error:</p>
<p><img src="https://i.stack.imgur.com/shDnW.png" alt="enter image description here"></p>
<p>I have no idea what to do.</p> | 11,921,426 | 8 | 4 | null | 2012-07-23 16:21:23.95 UTC | 5 | 2017-07-02 10:28:09.997 UTC | 2013-03-18 03:41:00.16 UTC | null | 1,077,789 | null | 1,406,867 | null | 1 | 34 | ios|xcode|provisioning-profile | 26,300 | <p>It seems like I had two accounts for apple like most people: 1) email address account and 2) just apple user ID login.</p>
<p>When you sign up for an iOS developer account, only one account gets approved as an iOS developer. It doesn't matter if those two accounts are merged and linked inside apple profile, only one gets approved. You can check this by logging into both accounts separately to their developer website. One account will say you are a member and another will say pay up the fee to become iOS developer.</p>
<p>The problem is that your keychain already stored one of apple id credentials from the past... and you probably signed up for apple iOS developer program using the other apple login. Xcode automatically gets keychain's previously stored credential for 'Teams' section and since that account from keychain was not activated for the iOS developer account, it's complaining that no one is a valid developer in 'Teams'.</p>
<p>To solve this, </p>
<ol>
<li><p>delete any, all apple related stuff from your keychain login.</p></li>
<li><p>revoke all the problematic profiles, certs, etc from apple website.</p></li>
<li><p>just redo provisioning process only using iOS developer approved apple login.</p></li>
<li><p>From XCode Organizer's Teams section, click 'refresh' icon at the bottom and follow direction.</p></li>
</ol> |
11,798,394 | Polymorphism in jackson annotations: @JsonTypeInfo usage | <p>I would like to know if <code>@JsonTypeInfo</code> annotation can be used for interfaces. I have set of classes which should be serialized and deserialized.</p>
<p>Here is what I'm trying to do. I have two implementation classes <code>Sub1</code>, <code>Sub2</code> implementing <code>MyInt</code>. Some of the model classes have the interface reference for the implementation types. I would like to deserialize the objects based on polymorphism</p>
<pre><code>@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT)
@JsonSubTypes({
@Type(name="sub1", value=Sub1.class),
@Type(name="sub2", value=Sub2.class)})
public interface MyInt{
}
@JsonTypeName("sub1")
public Sub1 implements MyInt{
}
@JsonTypeName("sub2")
public Sub2 implements MyInt{
}
</code></pre>
<p>I get the following <code>JsonMappingException</code>:</p>
<blockquote>
<p>Unexpected token (END_OBJECT), expected FIELD_NAME: need JSON String
that contains type id</p>
</blockquote> | 11,798,485 | 3 | 2 | null | 2012-08-03 15:09:36.57 UTC | 18 | 2022-06-02 16:41:04.377 UTC | 2017-09-12 10:25:34.08 UTC | null | 632,293 | null | 1,083,951 | null | 1 | 58 | java|polymorphism|jackson|deserialization | 66,169 | <p><code>@JsonSubTypes.Type</code> must have a value and a name like this,</p>
<pre><code>@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=As.WRAPPER_OBJECT, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(value=Dog.class, name="dog"),
@JsonSubTypes.Type(value=Cat.class, name="cat")
})
</code></pre>
<p>In the subclass, use <code>@JsonTypeName("dog")</code> to say the name.<br>
The values <code>dog</code> and <code>cat</code> will be set in the property named <code>type</code>.</p> |
20,089,594 | DateTime.Compare in Linq | <p>I am trying to use DateTime.Compare in Linq : </p>
<pre><code>from ---
where DateTime.Compare(Convert.ToDateTime(ktab.KTABTOM), DateTime.Now) < 1
select new
{
-------
}
</code></pre>
<p>But this gives me an error : </p>
<pre><code>LINQ to Entities does not recognize the method 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' method, and this method cannot be translated into a store expression
</code></pre>
<p><a href="https://stackoverflow.com/questions/14583254/linq-to-entities-does-not-recognize-the-method-system-datetime-addsecondsdoubl">This</a> link suggests that we should use EntityFunctions to fix dateTime manipulation in Linq. But here I need to compare the complete date. Even <a href="https://stackoverflow.com/questions/15264319/linq-to-entities-does-not-recognize-the-method-system-timespan-subtractsystem">this</a> won't help me. </p>
<p>The date is in format yyyy-MM-dd. </p> | 20,090,324 | 1 | 14 | null | 2013-11-20 07:09:52.847 UTC | 2 | 2017-09-13 10:25:13.673 UTC | 2017-09-13 10:25:13.673 UTC | null | 472,495 | null | 541,786 | null | 1 | 5 | c#|linq | 54,490 | <p>You don't need <code>DateTime.Compare</code> just write <code>ktab.KTABTOM <= DateTime.Now</code></p>
<p><strong>Examples with nullable DateTime:</strong></p>
<p>doesn't compile</p>
<pre><code>from p in Projects
where DateTime.Compare(DateTime.Now, p.EndDate) <= 0
select p.EndDate
</code></pre>
<p>and </p>
<pre><code>from p in Projects
where DateTime.Now <= p.EndDate
select p.EndDate
</code></pre>
<p>translates into </p>
<pre><code>SELECT
[Extent1].[EndDate] AS [EndDate]
FROM [dbo].[Project] AS [Extent1]
WHERE CAST( SysDateTime() AS datetime2) <= [Extent1].[EndDate]
</code></pre>
<p><strong>Examples without nullable DateTime:</strong></p>
<pre><code>from p in Projects
where DateTime.Compare(DateTime.Now, p.StartDate) <= 0
select p.StartDate
</code></pre>
<p>and </p>
<pre><code>from p in Projects
where DateTime.Now <= p.StartDate
select p.StartDate
</code></pre>
<p>both translates into</p>
<pre><code>SELECT
[Extent1].[StartDate] AS [StartDate]
FROM [dbo].[Project] AS [Extent1]
WHERE (SysDateTime()) <= [Extent1].[StartDate]
</code></pre> |
3,331,805 | Using clipRect - explanation | <pre><code>public class POCII extends Activity {
myView mv = new myView(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mv);
}
}
class myView extends View {
public myView(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
canvas.drawRect(0,0,100,100, paint);
canvas.clipRect(0,0,50,50);
}
}
</code></pre>
<p>My question is, shouldn't the above code draw a rectangle and then crop the top left portion? The rectangle is not getting cropped.</p>
<p>Please explain what clipRect does. What is it actually clipping? Does it clip in the form of a rectangle, given the co-ordinates? If so, Why is the above code not working?</p> | 4,651,665 | 4 | 1 | null | 2010-07-26 01:54:56.713 UTC | 11 | 2021-06-24 06:53:54.21 UTC | 2016-12-26 12:06:56.75 UTC | null | 1,554,215 | null | 381,699 | null | 1 | 47 | android|android-canvas|android-view | 42,652 | <p><a href="http://developer.android.com/reference/android/graphics/Canvas.html#clipRect(int,%20int,%20int,%20int)" rel="nofollow noreferrer"><code>Canvas.clipRect(left, top, right, bottom)</code></a> reduces the region of the screen that future draw operations can write to. It sets the clipBounds to be the spacial intersection of the current clipping rectangle and the rectangle specified. There are lot of variants of the clipRect method that accept different forms for regions and allow different operations on the clipping rectangle. If you want to explicitly set the clipping region, try:</p>
<pre><code>canvas.clipRect(left, top, right, bottom, Region.Op.REPLACE);
</code></pre>
<p>The 5th argument means replace the clipping rectangle rather than creating the intersection with the previous version.</p>
<p>Try moving the clipRect statement before the drawRect statement. Or, try adding:</p>
<pre><code>paint.setColor(Color.YELLOW);
drawRect(0,0,75,75);
</code></pre>
<p>after your existing clipRect statement. It should draw a 50x50 yellow square over what you had before.</p>
<p>Another note: (after long frustration with the apparently, largely undocumented View/ViewGroup/drawing code) I found that canvas.translate(x,y) also adjusts the clipRect. The interaction of clipRect and the drawing matrix is very confusing. It is helpful to point out:</p>
<pre><code>canvas.getMatrix()
</code></pre>
<p>and</p>
<pre><code>canvas.getClipBounds()
</code></pre>
<p>before and after modifications to the canvas and before drawing things.</p> |
3,343,623 | Javascript: Comparing two float values | <p>I have this JavaScript function:</p>
<pre><code>Contrl.prototype.EvaluateStatement = function(acVal, cfVal) {
var cv = parseFloat(cfVal).toFixed(2);
var av = parseFloat(acVal).toFixed(2);
if( av < cv) // do some thing
}
</code></pre>
<p>When i compare float numbers <code>av=7.00</code> and <code>cv=12.00</code> the result of <code>7.00<12.00</code> is <code>false</code>!</p>
<p>Any ideas why?</p> | 3,343,658 | 5 | 0 | null | 2010-07-27 12:33:38.237 UTC | 8 | 2021-08-14 08:37:19.917 UTC | 2010-07-27 12:45:20.71 UTC | null | 18,771 | null | 2,095,507 | null | 1 | 32 | javascript|comparison|floating-point|numbers | 55,099 | <p>toFixed returns a string, and you are comparing the two resulting strings. Lexically, the 1 in 12 comes before the 7 so 12 < 7.</p>
<p>I guess you want to compare something like: </p>
<pre><code>(Math.round(parseFloat(acVal)*100)/100)
</code></pre>
<p>which rounds to two decimals</p> |
3,660,787 | How to list custom types using Postgres information_schema | <p>I am trying to find the equivalent SQL of \dT using the information_schema and can't seem to find anything. Does such a thing exist?</p>
<p>Example: If I add the following custom type enum, how can I see it in the information_schema?</p>
<pre><code>CREATE TYPE communication.channels AS ENUM
('text_message',
'email',
'phone_call',
'broadcast');
</code></pre>
<p>NOTE: I do have the exact SQL used by \dT (retrieved by turning up the logging) but I am looking specifically for a cleaner implementation using the information_schema</p> | 6,245,537 | 7 | 1 | null | 2010-09-07 16:52:13.24 UTC | 8 | 2020-01-13 16:30:24.81 UTC | 2010-09-07 17:11:17.61 UTC | null | 135,152 | null | 354,767 | null | 1 | 60 | sql|postgresql | 55,862 | <p>Enums are not in the SQL standard and therefore not represented in the information schema. Other user-defined types would normally be in the view <code>user_defined_types</code>, but that's not implemented. So at the moment, you can't use the information schema to list user-defined types in PostgreSQL.</p> |
3,706,379 | What is a good naming convention for vars, methods, etc in C++? | <p>I come from a the Objective-C and Cocoa world where there are lots of conventions and many people will say it makes your code beautiful!
Now programming in C++ I cannot find a good document like this one for C++.</p>
<p><a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html" rel="noreferrer">http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html</a></p>
<p>Standard C++ probably does not have something like above but I hope I can stick to some other SDK or APIs (like Microsoft's(?),etc) conventions. </p>
<p>I hope you can provide me with some links.</p> | 3,706,598 | 10 | 9 | null | 2010-09-14 05:48:49.757 UTC | 37 | 2019-04-01 06:24:44.123 UTC | 2012-01-25 19:09:05.293 UTC | null | 1,288 | null | 149,008 | null | 1 | 74 | c++|naming-conventions | 131,859 | <p>Do whatever you want as long as its minimal, consistent, and <a href="https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier">doesn't break any rules</a>.</p>
<p>Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on <code>m</code> and <code>p</code> prefixes to members and parameters, respectively, giving:</p>
<pre><code>#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>
#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"
#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS
namespace lowercase_identifers
{
class separated_by_underscores
{
public:
void because_underscores_are() const
{
volatile int mostLikeSpaces = 0; // but local names are condensed
while (!mostLikeSpaces)
single_statements(); // don't need braces
for (size_t i = 0; i < 100; ++i)
{
but_multiple(i);
statements_do();
}
}
const complex_type& value() const
{
return mValue; // no conflict with value here
}
void value(const complex_type& pValue)
{
mValue = pValue ; // or here
}
protected:
// the more public it is, the more important it is,
// so order: public on top, then protected then private
template <typename Template, typename Parameters>
void are_upper_camel_case()
{
// gman was here
}
private:
complex_type mValue;
};
}
#endif
</code></pre>
<p>That.
(And like I've said in comments, do <em>not</em> adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)</p> |
3,947,555 | java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind (JBOSS) | <p><br>
I'm using JBoss 4.0.5 GA on Windows 7 with Java version 1.5 (I have to use older java version and a JBoss because I'm working with a legacy system). And when I'm starting the server I get the following error: </p>
<pre><code>java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind
</code></pre>
<p>And I believe this causes many other exceptions: </p>
<pre><code>11:09:26,925 WARN [ServiceController] Problem starting servicejboss.cache:service=TomcatClustering Cache
java.lang.NullPointerException
at org.jgroups.protocols.FD_SOCK.down(FD_SOCK.java:235)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.FD.down(FD.java:278)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.stack.Protocol.down(Protocol.java:540)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.pbcast.NAKACK.down(NAKACK.java:297)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.UNICAST.down(UNICAST.java:262)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.pbcast.STABLE.down(STABLE.java:292)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.pbcast.GMS.down(GMS.java:605)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.FC.down(FC.java:122)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.FRAG2.down(FRAG2.java:146)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.Protocol.passDown(Protocol.java:510)
at org.jgroups.protocols.pbcast.STATE_TRANSFER.down(STATE_TRANSFER.java:217)
at org.jgroups.stack.Protocol.receiveDownEvent(Protocol.java:467)
at org.jgroups.stack.ProtocolStack.down(ProtocolStack.java:331)
at org.jgroups.JChannel.down(JChannel.java:1035)
at org.jgroups.JChannel.connect(JChannel.java:374)
at org.jboss.cache.TreeCache.startService(TreeCache.java:1424)
at org.jboss.cache.aop.PojoCache.startService(PojoCache.java:94)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy4.start(Unknown Source)
at org.jboss.deployment.SARDeployer.start(SARDeployer.java:302)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy8.deploy(Unknown Source)
at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:634)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
at org.jboss.deployment.scanner.AbstractDeploymentScanner.startService(AbstractDeploymentScanner.java:336)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy4.start(Unknown Source)
at org.jboss.deployment.SARDeployer.start(SARDeployer.java:302)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy5.deploy(Unknown Source)
at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482)
at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362)
at org.jboss.Main.boot(Main.java:200)
at org.jboss.Main$1.run(Main.java:490)
at java.lang.Thread.run(Thread.java:619)
</code></pre>
<p>I greatly appreciate if anyone could help. At least to figure out where I should look for the solution (e.g. Is this an error related to windows 7 and JBoss clustering incompatability? Is this because of a wrong port configuration? etc.) </p>
<p>Thanks.</p> | 9,706,108 | 11 | 2 | null | 2010-10-16 03:28:00.867 UTC | 7 | 2020-02-05 09:17:00.607 UTC | null | null | null | null | 370,904 | null | 1 | 22 | java|windows-7|jboss|jakarta-ee|jvm | 100,712 | <p>This problem occurs on some Windows systems that have the IPv6 TCP Stack installed. If both IPv4 and IPv6 are installed on the computer, the Java Virtual Machine (JVM) may have problems closing or opening sockets at the operating system level. </p>
<p>Add the following JVM option: <code>-Djava.net.preferIPv4Stack=true</code> </p>
<p>I've seen this happen on Windows 7 and Windows 2008 systems which have both IPv4 and IPv6 stacks installed by default.</p> |
3,265,357 | Compiled vs. Interpreted Languages | <p>I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.</p>
<p>Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand that there are other kinds of interpreted and compiled languages. Aside from the fact that executable files can be distributed from programs written in compiled languages, are there any advantages/disadvantages to each type? Oftentimes, I hear people arguing that interpreted languages can be used interactively, but I believe that compiled languages can have interactive implementations as well, correct?</p> | 3,265,602 | 13 | 4 | null | 2010-07-16 13:35:33.05 UTC | 228 | 2021-09-29 06:09:29.777 UTC | 2010-07-18 16:15:21.327 UTC | null | 49,246 | null | 391,126 | null | 1 | 313 | java|python|compiler-construction|programming-languages|interpreter | 250,417 | <p>A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code.</p>
<p>An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally <em>is</em> written in the language of the native machine). For example, the same "+" operation would be recognised by the interpreter at run time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then execute the machine code "ADD" instruction.</p>
<p>You can do anything that you can do in an interpreted language in a compiled language and vice-versa - they are both Turing complete. Both however have advantages and disadvantages for implementation and use.</p>
<p>I'm going to completely generalise (purists forgive me!) but, roughly, here are the advantages of compiled languages:</p>
<ul>
<li>Faster performance by directly using the native code of the target machine</li>
<li>Opportunity to apply quite powerful optimisations during the compile stage</li>
</ul>
<p>And here are the advantages of interpreted languages:</p>
<ul>
<li>Easier to implement (writing good compilers is very hard!!)</li>
<li>No need to run a compilation stage: can execute code directly "on the fly"</li>
<li>Can be more convenient for dynamic languages</li>
</ul>
<p>Note that modern techniques such as bytecode compilation add some extra complexity - what happens here is that the compiler targets a "virtual machine" which is not the same as the underlying hardware. These virtual machine instructions can then be compiled again at a later stage to get native code (e.g. as done by the Java JVM JIT compiler).</p> |
7,961,091 | Mac Rmagick won't install with Xcode 4.2 | <p>I just got a new macbook pro and trying to setup my dev environment.
I downloaded xcode 4.2 from the app store and installed it, after this i installed homebrew and RVM.
ImageMagick, readline, ruby 1.9.3-head all installed perfectly until i ran bundle update which tried to install rmagick.</p>
<p>After a long long time investigating i come down to the conclusion that it can't find libgomp.</p>
<p>The output is from <code>gem install rmagick</code> is:</p>
<pre><code>$ gem install rmagick
Building native extensions. This could take a while...
ERROR: Error installing rmagick:
ERROR: Failed to build gem native extension.
/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/bin/ruby extconf.rb
checking for Ruby version >= 1.8.5... yes
extconf.rb:128: Use RbConfig instead of obsolete and deprecated Config.
checking for clang... yes
checking for Magick-config... yes
checking for ImageMagick version >= 6.4.9... yes
checking for HDRI disabled version of ImageMagick... yes
checking for stdint.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/bin/ruby
/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/lib/ruby/1.9.1/mkmf.rb:381:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
</code></pre>
<p>Here is my mkmf.log file:</p>
<pre><code>"clang -o conftest -I/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/include/ruby-1.9.1/x86_64-darwin11.2.0 -I/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/include/ruby-1.9.1/ruby/backward -I/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/include/ruby-1.9.1 -I. -I/usr/local/Cellar/imagemagick/6.7.1-1/include/ImageMagick -I/usr/local/Cellar/imagemagick/6.7.1-1/include/ImageMagick -fopenmp conftest.c -L. -L/Users/dhiemstra/.rvm/rubies/ruby-1.9.3-head/lib -L/usr/local/Cellar/imagemagick/6.7.1-1/lib -L/usr/X11/lib -L/usr/local/Cellar/imagemagick/6.7.1-1/lib -lMagickCore -llcms -ltiff -lfreetype -ljpeg -L/usr/X11/lib -lfontconfig -lXext -lSM -lICE -lX11 -lXt -lbz2 -lz -lm -lgomp -lpthread -lltdl -lruby.1.9.1 -lpthread -ldl -lobjc "
ld: library not found for -lgomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: int main() {return 0;}
/* end */
</code></pre>
<p>Now i assumed here that something was wrong with xcode i tried several things:</p>
<ul>
<li>Reinstall xcode</li>
<li>Remove imagemagick and reinstalled it including other libraries like jpg, libpng etc</li>
<li>Installed older version of imagemagick</li>
<li>Removed .rvm and reinstalled a fresh copy of ruby</li>
</ul>
<p>I have no clue what's left for me to try, could anyone help to push me in the good direction?</p> | 7,964,605 | 4 | 0 | null | 2011-10-31 23:52:07.073 UTC | 17 | 2017-04-26 16:11:17.263 UTC | 2017-04-26 16:11:17.263 UTC | null | 1,033,581 | null | 626,649 | null | 1 | 20 | ruby|xcode|gcc|imagemagick|rmagick | 7,091 | <p>I tried to download and install 4.1 for lion and this didn't even install (without a proper error message).
Now a colleague gave me this great link to GCC for Mac which worked like a charm:
<a href="https://github.com/kennethreitz/osx-gcc-installer" rel="nofollow">https://github.com/kennethreitz/osx-gcc-installer</a></p>
<p>Don't forget to download the v2 if you run on > 10.7.0</p> |
8,182,880 | SQLException: No value specified for parameter 1 | <p>I encountered the following error when I was executing my application:</p>
<blockquote>
<p>java.sql.SQLException: No value specified for parameter 1</p>
</blockquote>
<p>What does it mean?</p>
<p>My <code>UserGroup</code> list in my dao:</p>
<pre><code>public List<UsuariousGrupos> select(Integer var) {
List<UsuariousGrupos> ug= null;
try {
conn.Connection();
stmt = conn.getPreparedStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo ='" + var + "'");
ResultSet rs = stmt.executeQuery();
ug = new ArrayList<UsuariousGrupos>();
while (rs.next()) {
ug.add(getUserGrupos(rs));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn.Disconnected();
}
return ug;
}
public UsuariousGrupos getUserGrupos(ResultSet rs) {
try {
UsuariousGrupos ug = new UsuariousGrupos(rs.getInt("id_usuario"), rs.getInt("id_grupo"));
return ug;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
</code></pre>
<p>My get list of User groups in my managed bean:</p>
<pre><code>public List<UsuariousGrupos> getListOfUserGroups() {
List<UsuariousGrupos> usuariosGruposList = userGrpDAO.select(var2);
listOfUserGroups = usuariosGruposList;
return listOfUserGroups;
}
</code></pre>
<p>My JSF page:</p>
<pre><code> <p:dataTable var="usergroups" value="#{usuariousGruposBean.listOfUserGroups}">
<p:column headerText="" style="height: 0" rendered="false">
<h:outputText value="#{usergroups.id_grupo}"/>
</p:column>
</code></pre>
<p>My data table is able to display the list of groups from the database. However, when I select an individual row within my data table, it takes some time for the application to establish connection with my database to display the selected result.</p>
<p>Also, it is weird that the application is able to display certain selected results quicker than others. Does it have anything to do with the Exception I pointed out at the beginning? </p>
<p>Error:</p>
<pre><code>Disconnected
Connected!!
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2560)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2536)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2462)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2216)
at br.dao.UsuariousGruposDAO.select(UsuariousGruposDAO.java:126)
at br.view.UsuariousGruposBean.getListOfUserGroups(UsuariousGruposBean.java:54)
SEVERE: Error Rendering View[/index.xhtml]
javax.el.ELException: /index.xhtml @61,99 value="#{usuariousGruposBean.listOfUserGroups}": Error reading 'listOfUserGroups' on type br.view.UsuariousGruposBean
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
</code></pre> | 8,183,320 | 5 | 5 | null | 2011-11-18 13:06:58.52 UTC | 1 | 2020-05-13 06:18:42.053 UTC | 2017-09-01 09:32:32.66 UTC | null | 4,165,377 | null | 1,007,036 | null | 1 | 13 | java|jsf|jdbc | 63,859 | <p>There is no such method as <code>Connection()</code> and <code>getPreparedStatement()</code> on <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Connection.html" rel="noreferrer"><code>java.sql.Connection</code></a>.</p>
<pre><code>conn.Connection();
stmt = conn.getPreparedStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo ='" + var + "'");
</code></pre>
<p>The <code>conn</code> is clearly a homegrown wrapper around JDBC code. Your particular problem is likely caused by the code behind the <code>getPreparedStatement()</code> method. It's apparently appending a <code>?</code> to the SQL string before delegating through to the <em>real</em> <a href="http://download.oracle.com/javase/6/docs/api/java/sql/Connection.html#prepareStatement%28java.lang.String%29" rel="noreferrer"><code>connection.prepareStatement()</code></a> method.</p>
<p>You probably don't want to hear this, but your JDBC approach is totally broken. This design indicates that the JDBC <code>Connection</code> is hold as a static or instance variable which is <strong>threadunsafe</strong>. </p>
<p>You need to totally rewrite it so that it boils down to the following proper usage and variable scoping:</p>
<pre><code>public List<UsuariousGrupos> select(Integer idGrupo) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<UsuariousGrupos> usuariousGrupos = new ArrayList<UsariousGrupos>();
try {
connection = database.getConnection();
statement = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
statement.setInt(1, idGrupo);
resultSet = statement.executeQuery();
while (resultSet.next()) {
usuariousGrupos.add(mapUsuariousGrupos(resultSet));
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return usuariousGrupos;
}
</code></pre>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2237220/how-to-declare-a-global-static-class-in-java/2237300#2237300">How to declare a global static class in Java?</a></li>
</ul>
<hr>
<p><strong>Unrelated</strong> to the concrete question, you've another problem. The following exception</p>
<blockquote>
<p>javax.el.ELException: /index.xhtml @61,99 value="#{usuariousGruposBean.listOfUserGroups}": Error reading 'listOfUserGroups' on type br.view.UsuariousGruposBean</p>
</blockquote>
<p>indicates that you're doing the JDBC stuff inside a <strong>getter</strong> method instead of (post)constructor or (action)listener method. This is also a very bad idea because a getter can be called more than once during render response. Fix it accordingly.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2090033/why-jsf-calls-getters-multiple-times/2090062#2090062">Why JSF calls getters multiple times</a></li>
</ul> |
8,046,643 | How to change a particular color in an image? | <p>My question is if I have a Lion image just I want to change the color of the lion alone not the background color. For that I referred this <a href="https://stackoverflow.com/questions/1223340/iphone-how-do-you-color-an-image">SO question</a> but it turns the color of whole image. Moreover the image is not looking great. I need the color change like photoshop. whether it is possible to do this in coregraphics or I have to use any other library.</p>
<p>EDIT : I need the color change to be like <a href="https://apps.apple.com/us/app/live-splash-free-selective-color-grayscale-effects/id359017259" rel="nofollow noreferrer">iQuikColor</a> app</p>
<p><img src="https://i.stack.imgur.com/NQXpA.jpg" alt="enter image description here" /></p> | 8,078,554 | 5 | 6 | null | 2011-11-08 06:18:33.29 UTC | 34 | 2021-02-20 11:38:15.873 UTC | 2021-02-20 11:38:15.873 UTC | null | 501,439 | null | 669,119 | null | 1 | 41 | iphone|objective-c|image-processing|core-graphics|pixel | 16,766 | <p><strong>See answers below instead. Mine doesn't provide a complete solution.</strong></p>
<hr>
<p>Here is the sketch of a possible solution using OpenCV:</p>
<ul>
<li>Convert the image from RGB to HSV using <code>cvCvtColor</code> (we only want to change the hue).</li>
<li>Isolate a color with <code>cvThreshold</code> specifying a certain tolerance (you want a range of colors, not one flat color).</li>
<li>Discard areas of color below a minimum size using a blob detection library like <a href="http://opencv.willowgarage.com/wiki/cvBlobsLib" rel="noreferrer">cvBlobsLib</a>. This will get rid of dots of the similar color in the scene.</li>
<li>Mask the color with <code>cvInRangeS</code> and use the resulting mask to apply the new hue.</li>
<li><code>cvMerge</code> the new image with the new hue with an image composed by the saturation and brightness channels that you saved in step one.</li>
</ul>
<p>There are several OpenCV iOS ports in the net, eg: <a href="http://www.eosgarden.com/en/opensource/opencv-ios/overview/" rel="noreferrer">http://www.eosgarden.com/en/opensource/opencv-ios/overview/</a> I haven't tried this myself, but seems a good research direction.</p> |
7,961,568 | Fill fields in webview automatically | <p>I have seen this question floating around the internet, but I haven't found a working solution yet. Basically, I want to load my app and press a button; the button action will then fill in a username and password in a website already loaded in the webview (or wait for onPageFinished). Finally, the submit button on the login page will be activated. </p>
<p>From what I understand this can be done by doing a java injection with the loadUrl(javascript), but I don't know what the java commands would be to fill in the fields. The same question was asked for <a href="https://stackoverflow.com/questions/7729473/can-i-use-username-and-password-information-from-uitextfields-to-log-onto-a-webs">iOS</a>, but the commands are slightly different.</p>
<p>Is it possible to do what I am asking with javascript in a webivew, or do I have to do a http-post without a webview like <a href="https://stackoverflow.com/questions/7186784/android-httppost-login-action">this</a> or <a href="https://stackoverflow.com/questions/6960909/how-to-autofill-gmail-form-from-a-webview-with-basicnamevaluepair">this</a>?</p>
<p>Thank you so much for any help you can give!</p> | 7,961,598 | 6 | 0 | null | 2011-11-01 01:20:32.567 UTC | 15 | 2019-01-06 15:22:41.723 UTC | 2017-05-23 12:34:54.2 UTC | null | -1 | null | 1,022,934 | null | 1 | 25 | java|android|webview|http-post|android-webview | 42,775 | <p>You don't need to use "java commands"... but instead JavaScript... for instance:</p>
<pre><code>String username = "cristian";
webview.loadUrl("javascript:document.getElementById('username').value = '"+username+"';");
</code></pre>
<p>So basically, what you have to do is a big string of JavaScript code that will get those fields and put values on them; also, you can enable/disable the submit button from JavaScript.</p> |
7,730,695 | What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields? | <p>I have read a bit on this, but I can't seem to find anything solid about how different browsers treat things.</p> | 7,730,719 | 7 | 1 | null | 2011-10-11 18:28:42.737 UTC | 146 | 2022-04-08 20:24:56.613 UTC | 2018-12-11 14:42:57.14 UTC | null | 1,709,587 | null | 493,807 | null | 1 | 512 | html|cross-browser | 284,210 | <p>A <code>readonly</code> element is just not editable, but gets sent when the according <code>form</code> submits. A <code>disabled</code> element isn't editable and isn't sent on submit. Another difference is that <code>readonly</code> elements can be focused (and getting focused when "tabbing" through a form) while <code>disabled</code> elements can't.</p>
<p>Read more about this in <a href="https://web.archive.org/web/20150913195206/https://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/" rel="noreferrer">this great article</a> or <a href="http://www.w3.org/TR/html4/interact/forms.html#h-17.12" rel="noreferrer">the definition by w3c</a>. To quote the important part:</p>
<blockquote>
<p><strong>Key Differences</strong></p>
<p><strong>The Disabled attribute</strong></p>
<ul>
<li>Values for disabled form elements are not passed to the processor method. The W3C calls this a successful element.(This works similar to
form check boxes that are not checked.)</li>
<li>Some browsers may override or provide default styling for disabled form elements. (Gray out or emboss text) Internet Explorer
5.5 is particularly nasty about this.</li>
<li>Disabled form elements do not receive focus.</li>
<li>Disabled form elements are skipped in tabbing navigation.</li>
</ul>
<p><strong>The Read Only Attribute</strong></p>
<ul>
<li>Not all form elements have a readonly attribute. Most notable, the <code><SELECT></code> , <code><OPTION></code> , and <code><BUTTON></code> elements do not have readonly
attributes (although they both have disabled attributes)</li>
<li>Browsers provide no default overridden visual feedback that the form element is read only. (This can be a problem… see below.)</li>
<li>Form elements with the readonly attribute set will get passed to the form processor.</li>
<li>Read only form elements can receive the focus</li>
<li>Read only form elements are included in tabbed navigation.</li>
</ul>
</blockquote> |
4,488,128 | How can I fetch data from a website inside a C++ program | <p>I want to write a program in C++ that helps to manage my hockey pool, and one of the key things i will need to do is read off the schedule for the week ahead. I was hoping to use the NHL website. is there any way to have the program download the HTML file for a given url, and then parse that? i suppose that once i have the file downloaded, Simple file I/O would do, but im not sure how to download the file. </p> | 4,488,201 | 3 | 1 | null | 2010-12-20 08:54:16.797 UTC | 4 | 2017-07-20 20:15:51.713 UTC | 2013-04-01 22:48:47.993 UTC | null | 350,511 | null | 350,511 | null | 1 | 10 | c++ | 53,906 | <p>I would use some library providing Http abstraction.</p>
<p>For example:</p>
<p><strong><a href="http://cpp-netlib.github.com/" rel="nofollow noreferrer">cpp-netlib</a></strong></p>
<pre><code>#include <boost/network/protocol/http/client.hpp>
#include <string>
#include <iostream>
int main()
{
boost::network::http::client client;
boost::network::http::client::request request("http://www.example.com");
request << boost::network::header("Connection", "close");
boost::network::http::client::response response = client.get(request);
std::cout << body(response);
}
</code></pre>
<p>I do not think it can get much easier than that</p>
<p>On GNU/Linux compile with:</p>
<pre><code>g++ -I. -I$BOOST_ROOT -L$BOOST_ROOT/stage/lib -lboost_system -pthread my_main.cpp
</code></pre>
<p><strong><a href="http://doc.qt.io/qt-4.8/qhttp.html" rel="nofollow noreferrer">QHttp</a></strong></p>
<p>Example for this could get quite long,
since QHttp can send only non-blocking requests (that means, that you have to catch some signals reporting that the request was finished, etc.).
But the documentation is superb, so it should not be a problem. :)</p> |
4,230,345 | Declaring vectors in a C++ header file | <p>I am having some trouble with vector declarations in the header file of a C++ class I am making. My entire header file looks like this:</p>
<pre><code>#ifndef PERSON_H
#define PERSON_H
#include "Message.h"
#include <string>
#include <vector>
class Person {
public:
Person() {};
Person(std::string emailAddress);
private:
vector<Message> inbox;
vector<std::string> contacts;
std::string emailAddress;
};
#endif PERSON_H
</code></pre>
<p>My error occurs on the lines following the "private" declaration (where I declare my vectors). The error I am getting is C4430 - missing type specifier and and C2238 - unexpected tokens preceding ';'</p>
<p>Thank you for any help.</p> | 4,230,356 | 3 | 3 | null | 2010-11-19 23:37:34.173 UTC | 8 | 2016-05-13 05:57:58.213 UTC | null | null | null | null | 514,111 | null | 1 | 23 | c++|vector | 70,514 | <p>You're missing the namespace:</p>
<pre><code>std::vector
</code></pre> |
4,158,286 | Storing images in Core Data or as file? | <p>I have set of data which contains images also. I want to cache this data. Should i store them on file system or on core data and why?</p> | 4,158,322 | 3 | 0 | null | 2010-11-11 19:11:27.23 UTC | 14 | 2019-02-25 10:16:27.403 UTC | 2013-10-02 11:31:19.707 UTC | null | 227,536 | null | 418,029 | null | 1 | 33 | core-data|ios|blob | 19,155 | <p>There are two main options:</p>
<ol>
<li>Store the file on disk, and then store the path to the image in core data</li>
<li>Store the binary data of the image in core data</li>
</ol>
<p>I personally prefer the 1st option, since it allows me to choose when I want to load the actual image in memory. It also means that I don't have to remember what format the raw data is in; I can just use the path to <code>alloc</code>/<code>init</code> a new <code>UIImage</code> object.</p> |
4,225,577 | Javascript replace regex wildcard | <p>I have a string which I need to run a replace.</p>
<pre><code>string = replace('/blogs/1/2/all-blogs/','');
</code></pre>
<p>The values 1, 2 and all-blogs can change. Is it possible to make them wildcards?</p>
<p>Thanks in advance,</p>
<p>Regards</p> | 4,225,595 | 4 | 0 | null | 2010-11-19 13:47:46.393 UTC | 1 | 2021-01-16 09:30:53.447 UTC | 2010-11-19 13:50:58.863 UTC | null | 53,114 | null | 356,816 | null | 1 | 14 | javascript|regex | 41,608 | <p>You can use <code>.*</code> as a placeholder for "zero or more of any character here" or <code>.+</code> for "one or more of any character here". I'm not 100% sure exactly what you're trying to do, but for instance:</p>
<pre><code>var str = "/blogs/1/2/all-blogs/";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "", the string is now blank
</code></pre>
<p>But if there's more after or before it:</p>
<pre><code>str = "foo/blogs/1/2/all-blogs/bar";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "foobar"
</code></pre>
<p><a href="http://jsbin.com/ucize3/2" rel="nofollow noreferrer">Live example</a></p>
<p>Note that in both of the above, only the <em>first</em> match will be replaced. If you wanted to replace <em>all</em> matches, add a <code>g</code> like this:</p>
<pre><code>str = str.replace(/\/blogs\/.+\/.+\/.+\//g, '');
// ^-- here
</code></pre>
<p>You can read up on JavaScript's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" rel="nofollow noreferrer">regular expressions on MDC</a>.</p> |
4,199,266 | How can I make a JSON POST request with LWP? | <p>If you try to login at <a href="https://orbit.theplanet.com/Login.aspx?url=/Default.aspx">https://orbit.theplanet.com/Login.aspx?url=/Default.aspx</a> (use any username/password combination), you can see that the login credentials are sent as a non-traditional set of POST data: just a lonesome JSON string and no normal key=value pair.</p>
<p>Specifically, instead of:</p>
<pre><code>username=foo&password=bar
</code></pre>
<p>or even something like:</p>
<pre><code>json={"username":"foo","password":"bar"}
</code></pre>
<p>There's simply:</p>
<pre><code>{"username":"foo","password":"bar"}
</code></pre>
<p>Is it possible to perform such a request with <code>LWP</code> or an alternative module? I am prepared to do so with <code>IO::Socket</code> but would prefer something more high-level if available.</p> | 4,199,354 | 4 | 0 | null | 2010-11-16 21:40:39.17 UTC | 18 | 2015-08-04 16:15:16.273 UTC | null | null | null | null | 91,768 | null | 1 | 32 | perl|json|http-post|lwp | 65,952 | <p>You'll need to construct the HTTP request manually and pass that to LWP. Something like the following should do it:</p>
<pre><code>my $uri = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
my $json = '{"username":"foo","password":"bar"}';
my $req = HTTP::Request->new( 'POST', $uri );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );
</code></pre>
<p>Then you can execute the request with LWP:</p>
<pre><code>my $lwp = LWP::UserAgent->new;
$lwp->request( $req );
</code></pre> |
4,283,933 | What is the clean way to unittest FileField in django? | <p>I have a model with a FileField. I want to unittest it. django test framework has great ways to manage database and emails. Is there something similar for FileFields?</p>
<p>How can I make sure that the unittests are not going to pollute the real application?</p>
<p>Thanks in advance</p>
<p>PS: My question is almost a duplicate of <a href="https://stackoverflow.com/questions/2266503/django-test-filefield-using-test-fixtures">Django test FileField using test fixtures</a> but it doesn't have an accepted answer. Just want to re-ask if something new on this topic.</p> | 4,547,203 | 5 | 1 | null | 2010-11-26 09:16:22.397 UTC | 22 | 2020-09-03 11:59:23.017 UTC | 2017-05-23 12:17:54.33 UTC | null | -1 | null | 117,092 | null | 1 | 73 | python|django|filefield|django-unittest | 26,602 | <p>There are several ways you could tackle this but they're all ugly since unit tests are supposed to be isolated but files are all about durable changes.</p>
<p>My unit tests don't run on a system with production data so it's been easy to simply reset the upload directory after each run with something like <code>git reset --hard</code>. This approach is in some ways the best simply because it involves no code changes and is guaranteed to work as long as you start with good test data. </p>
<p>If you don't actually need to do anything with that file after testing your model's save method, I'd recommend using python's excellent <a href="https://docs.python.org/3/library/unittest.mock.html" rel="noreferrer">Mock library</a> to completely fake the <code>File</code> instance (i.e. something like <code>mock_file = Mock(spec=django.core.files.File); mock_file.read.return_value = "fake file contents"</code>) so you can completely avoid changes to your file handling logic. The Mock library has a couple of ways to <a href="https://docs.python.org/3/library/unittest.mock.html#patch-object" rel="noreferrer">globally patch</a> Django's <a href="http://docs.djangoproject.com/en/dev/ref/files/file/" rel="noreferrer">File class</a> within a test method which is about as easy as this will get.</p>
<p>If you need to have a real file (i.e. for serving as part of a test, processing with an external script, etc.) you can use something similar to Mirko's example and create a <a href="http://docs.djangoproject.com/en/dev/ref/files/file/" rel="noreferrer">File object</a> after making sure it'll be stored somewhere appropriate - here are three ways to do that:</p>
<ul>
<li>Have your test <code>settings.MEDIA_ROOT</code> point to a temporary directory (see the Python <a href="http://docs.python.org/library/tempfile.html#tempfile.mkdtemp" rel="noreferrer">tempfile</a> module's <code>mkdtemp</code> function). This works fine as long as you have something like a separate <code>STATIC_ROOT</code> which you use for the media files which are part of your source code.</li>
<li>Use a custom <a href="http://docs.djangoproject.com/en/dev/ref/files/storage/" rel="noreferrer">storage manager</a></li>
<li>Set the file path manually on each File instance or have a custom <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to" rel="noreferrer">upload_to</a> function to point somewhere which your test setup/teardown process purges such as a test subdirectory under <code>MEDIA_ROOT</code>.</li>
</ul>
<p><strong>Edit:</strong> mock object library is new in python version 3.3. For older python versions check <a href="http://www.voidspace.org.uk/python/mock/" rel="noreferrer">Michael Foord's version</a></p> |
4,198,619 | SQL total row count | <p>I need to select the number of rows:</p>
<pre><code>select
int_re_usu as Qtd_Respostas
from
tb_questionario_voar_resposta
group by
int_re_usu
</code></pre>
<p>It returns:</p>
<pre><code>1- 687
2- 375076
3- 339012
4 -314083
5 -52741
6 -339977
7- 276041
8- 373304
9 - 339476
10- 51095
11- 270365
12 - 6
13 - 308670
14 -305232
15 - 85868
16 - 9893
17 -300598
18 - 300572
19 - 275889
20 - 6092
21 - 80092
22 - 307104
23 -273393
</code></pre>
<p>I want to select instead the number 23,which is the total row_count.</p>
<p>Any ideias?</p> | 4,198,649 | 6 | 0 | null | 2010-11-16 20:29:05.797 UTC | null | 2010-11-16 21:09:33.467 UTC | 2010-11-16 20:32:42.21 UTC | null | 119,477 | null | 257,234 | null | 1 | 4 | sql | 42,636 | <p>Use @@RowCount</p>
<pre><code>select int_re_usu as Qtd_Respostas from tb_questionario_voar_resposta group by int_re_usu
Select @@RowCount
</code></pre>
<p>OR
Use a Derived Table</p>
<pre><code>Select Count(*) from
(select int_re_usu as Qtd_Respostas from tb_questionario_voar_resposta group by int_re_usu) q1
</code></pre> |
4,239,666 | getting bytes from unicode string in python | <p>I have an 16bit big endian unicode string represented as <code>u'\u4132'</code>, </p>
<p>how can I split it into integers 41 and 32 in python ?</p> | 4,240,999 | 6 | 1 | null | 2010-11-21 19:01:36.237 UTC | 1 | 2019-08-24 13:40:06.677 UTC | 2019-08-24 13:40:06.677 UTC | null | 1,058,591 | null | 37,491 | null | 1 | 11 | python|unicode|byte | 52,120 | <p>Here are a variety of different ways you may want it.</p>
<p>Python 2:</p>
<pre><code>>>> chars = u'\u4132'.encode('utf-16be')
>>> chars
'A2'
>>> ord(chars[0])
65
>>> '%x' % ord(chars[0])
'41'
>>> hex(ord(chars[0]))
'0x41'
>>> ['%x' % ord(c) for c in chars]
['41', '32']
>>> [hex(ord(c)) for c in chars]
['0x41', '0x32']
</code></pre>
<p>Python 3:</p>
<pre><code>>>> chars = '\u4132'.encode('utf-16be')
>>> chars
b'A2'
>>> chars = bytes('\u4132', 'utf-16be')
>>> chars # Just the same.
b'A2'
>>> chars[0]
65
>>> '%x' % chars[0]
'41'
>>> hex(chars[0])
'0x41'
>>> ['%x' % c for c in chars]
['41', '32']
>>> [hex(c) for c in chars]
['0x41', '0x32']
</code></pre> |
4,372,176 | What is the SQL to change the field length of a table column in SQL Server | <p>What is the SQL to make a field go from <code>nvarchar(50)</code> to <code>nvarchar(250)</code>? </p>
<p>When I try to change it through the SQL Server Management Studio, it doesn't allow me to do it, so I figured I would try SQL directly instead of using the GUI.</p> | 4,372,182 | 6 | 0 | null | 2010-12-06 23:55:59.58 UTC | 6 | 2018-05-11 10:38:59.183 UTC | 2017-10-06 04:46:25.907 UTC | null | 243,373 | null | 4,653 | null | 1 | 26 | sql|sql-server | 110,234 | <pre><code>Alter table tblname ALTER Column colname nvarchar(250) [NOT] NULL
</code></pre>
<p>If <code>NULL</code> / <code>NOT NULL</code> is not specified the column will become Nullable irrespective of what ever the original specification was.</p> |
4,388,360 | Should I write equals() and hashCode() methods in JPA entities? | <p>I want to check if entity is in a Collection member (<code>@OneToMany</code> or <code>@ManyToMany</code>) of another entity:</p>
<pre><code>if (entity2.getEntities1().contains(entity1)) { }
</code></pre> | 4,388,453 | 6 | 2 | null | 2010-12-08 14:07:24.067 UTC | 41 | 2021-01-09 09:51:43.623 UTC | 2019-03-04 06:46:12.35 UTC | null | 1,025,118 | null | 535,072 | null | 1 | 70 | java|jpa|entity|equals|hashcode | 43,086 | <p>Not necessarily. There are three options:</p>
<ul>
<li><p>don't override - thus you will be working with instances. This is fine in cases when you are working with the collections with only entities that are attached to the session (and hence guaranteed to be the same instance). This is (for me) the preferred way in many cases, because it requires less code and less consideration when overriding</p></li>
<li><p>override <code>hashCode()</code> and <code>equals()</code> with a business key. That may be a subset of properties that identify the entity. For example, for a <code>User</code> a good business key might be the <code>username</code> or the <code>email</code>. This is considered good practice.</p></li>
<li><p>override <code>hashCode()</code> and <code>equals()</code> using the ID field only. This is fine in some cases, especially if you have a manually-assigned identifier (like an UUID). It is also fine if your entity will never go into a collection. But for transient entities (with no identifier) that go into collections, it causes problems, so careful with this option. As seanizer noted - you should avoid it. Generally, always, unless you are really aware of what you are doing (and perhaps documenting it)</p></li>
</ul>
<p><a href="http://community.jboss.org/wiki/EqualsandHashCode">See this article</a> for more details. Also note that <code>equals()</code>and <code>hashCode()</code> are tied and should be implemented both with exactly the same fields.</p> |
4,453,782 | Why set Autocommit to true? | <p>I have wondered for a long time why the JDBC API provides an autocommit mode (<code>java.sql.Connection.setAutocommit()</code>). It seems like an attractive nuisance that just lures people into trouble. My theory is it was only added to JDBC in order to simplify life for vendors who wanted to create tools for editing and running SQL using JDBC. Is there any other reason to turn on autocommit, or is it always a mistake?</p> | 4,454,419 | 7 | 0 | null | 2010-12-15 19:04:08.133 UTC | 8 | 2014-08-19 06:04:19.097 UTC | 2010-12-15 19:11:56.14 UTC | null | 157,882 | null | 217,324 | null | 1 | 35 | java|jdbc | 72,979 | <p>Unfortunately, using autocommit is database specific (as is transaction behavior). I think if you don't have a global, programmatic transaction strategy, autocommit is probably better than just hoping everyone properly closes/rolls back transactions.</p>
<p>Speaking for MySQL, you can leave autocommit=true on by default, and it will automatically turn that off when you BEGIN a transaction. The only reason to set autocommit=false is if you want to force an error if someone tries to start a transaction without a BEGIN.</p>
<p>For simplicity in a typical Java + MySQL application today, I would more or less ignore the auto-commit setting, use an open-session-in-view pattern and call it good.</p>
<p>I would strongly discourage explicit RDBMS row locks and use optimistic locks instead. Hibernate offers built-in support for optimistic locks, but it's an easy pattern to adopt even for hand-rolled code and offers better performance.</p> |
4,199,393 | Are Options and named default arguments like oil and water in a Scala API? | <p>I'm working on a Scala API (for Twilio, by the way) where operations have a pretty large amount of parameters and many of these have sensible default values. To reduce typing and increase usability, I've decided to use case classes with named and default arguments. For instance for the TwiML Gather verb:</p>
<pre><code>case class Gather(finishOnKey: Char = '#',
numDigits: Int = Integer.MAX_VALUE, // Infinite
callbackUrl: Option[String] = None,
timeout: Int = 5
) extends Verb
</code></pre>
<p>The parameter of interest here is <em>callbackUrl</em>. It is the only parameter which is <em>really</em> optional in the sense that if no value is supplied, no value will be applied (which is perfectly legal). </p>
<p>I've declared it as an option in order to do the monadic map routine with it on the implementation side of the API, but this puts some extra burden on the API user:</p>
<pre><code>Gather(numDigits = 4, callbackUrl = Some("http://xxx"))
// Should have been
Gather(numDigits = 4, callbackUrl = "http://xxx")
// Without the optional url, both cases are similar
Gather(numDigits = 4)
</code></pre>
<p>As far as I can make out, there are two options (no pun intended) to resolve this. Either make the API client import an implicit conversion into scope:</p>
<pre><code>implicit def string2Option(s: String) : Option[String] = Some(s)
</code></pre>
<p>Or I can redeclare the case class with a null default and convert it to an option on the implementation side:</p>
<pre><code>case class Gather(finishOnKey: Char = '#',
numDigits: Int = Integer.MAX_VALUE,
callbackUrl: String = null,
timeout: Int = 5
) extends Verb
</code></pre>
<p>My questions are as follows:</p>
<ol>
<li>Are there any more elegant ways to solve my particular case?</li>
<li>More generally: Named arguments is a new language feature (2.8). Could it turn out that Options and named default arguments are like oil and water? :)</li>
<li>Might using a null default value be the best choice in this case?</li>
</ol> | 4,200,762 | 7 | 1 | null | 2010-11-16 21:52:10.897 UTC | 16 | 2010-11-18 02:28:51.313 UTC | 2010-11-16 22:26:49.627 UTC | null | 259,661 | null | 259,661 | null | 1 | 42 | scala|optional-parameters|named-parameters | 19,244 | <p>Here's another solution, partly inspired by <a href="https://stackoverflow.com/questions/4199393/are-options-and-named-default-arguments-like-oil-and-water-in-a-scala-api/4199579#4199579">Chris' answer</a>. It also involves a wrapper, but the wrapper is transparent, you only have to define it once, and the user of the API doesn't need to import any conversions:</p>
<pre><code>class Opt[T] private (val option: Option[T])
object Opt {
implicit def any2opt[T](t: T): Opt[T] = new Opt(Option(t)) // NOT Some(t)
implicit def option2opt[T](o: Option[T]): Opt[T] = new Opt(o)
implicit def opt2option[T](o: Opt[T]): Option[T] = o.option
}
case class Gather(finishOnKey: Char = '#',
numDigits: Opt[Int] = None, // Infinite
callbackUrl: Opt[String] = None,
timeout: Int = 5
) extends Verb
// this works with no import
Gather(numDigits = 4, callbackUrl = "http://xxx")
// this works too
Gather(numDigits = 4, callbackUrl = Some("http://xxx"))
// you can even safely pass the return value of an unsafe Java method
Gather(callbackUrl = maybeNullString())
</code></pre>
<hr>
<p>To address the larger design issue, I don't think that the interaction between Options and named default parameters is as much oil-and-water as it might seem at first glance. There's a definite distinction between an optional field and one with a default value. An optional field (i.e. one of type <code>Option[T]</code>) might <em>never</em> have a value. A field with a default value, on the other hand, simply does not require its value to be supplied as an argument to the constructor. These two notions are thus orthogonal, and it's no surprise that a field may be optional and have a default value.</p>
<p>That said, I think a reasonable argument can be made for using <code>Opt</code> rather than <code>Option</code> for such fields, beyond just saving the client some typing. Doing so makes the API more flexible, in the sense that you can replace a <code>T</code> argument with an <code>Opt[T]</code> argument (or vice-versa) without breaking callers of the constructor[1].</p>
<p>As for using a <code>null</code> default value for a public field, I think this is a bad idea. "You" may know that you expect a <code>null</code>, but clients that access the field may not. Even if the field is private, using a <code>null</code> is asking for trouble down the road when other developers have to maintain your code. All the usual arguments about <code>null</code> values come into play here -- I don't think this use case is any special exception.</p>
<p>[1] Provided that you remove the option2opt conversion so that callers must pass a <code>T</code> whenever an <code>Opt[T]</code> is required.</p> |
4,454,209 | when is a spring bean instantiated | <pre><code>ApplicationContext ctx = new ClassPathXmlApplicationContext(
"com/springinaction/springidol/spring-idol.xml");
Performer performer = (Performer) ctx.getBean("duke");
performer.perform();
</code></pre>
<p>In the above, when are the beans instantiated, when the ApplicationContext is created or when the getBean() is called?</p> | 4,454,244 | 8 | 0 | null | 2010-12-15 19:50:08.197 UTC | 11 | 2022-09-09 05:05:30.13 UTC | 2010-12-15 19:55:30.677 UTC | null | 21,234 | null | 268,850 | null | 1 | 35 | java|spring | 44,756 | <p>Assuming the bean is a singleton, and isn't configured for lazy initialisation, then it's created when the context is started up. <code>getBean()</code> just fishes it out.</p>
<p>Lazy-init beans will only be initialised when first referenced, but this is not the default. Scoped beans (e.g. prototype-scoped) will also only be created when first referenced.</p> |
4,752,501 | Move the mouse pointer to a specific position? | <p>I'm building a HTML5 game and I am trying to put the mouse cursor over a certain control on a specific event so that moving in a specific direction always has the same result. Is this possible?</p> | 19,870,963 | 10 | 5 | null | 2011-01-20 20:56:51.14 UTC | 35 | 2020-08-15 16:12:21.747 UTC | 2012-04-25 03:06:50.483 UTC | null | 327,466 | null | 329,650 | null | 1 | 148 | javascript|mouse | 215,716 | <p>So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called <i>Mouse Lock</i>, and hitting escape will break it. From my <i>brief</i> read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.</p>
<p>Here's the release documentation:<br/>FireFox: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API</a><br/>Chrome: <a href="http://www.chromium.org/developers/design-documents/mouse-lock" rel="noreferrer">http://www.chromium.org/developers/design-documents/mouse-lock</a></p>
<p>And here's a pretty neat demonstration: <a href="http://media.tojicode.com/q3bsp/" rel="noreferrer">http://media.tojicode.com/q3bsp/</a></p> |
4,636,146 | When to use -retainCount? | <p>I would like to know in what situation did you use <code>-retainCount</code> so far, and eventually the problems that can happen using it.</p>
<p>Thanks.</p> | 4,636,477 | 11 | 2 | null | 2011-01-08 21:07:14.56 UTC | 44 | 2018-06-04 18:38:20.987 UTC | 2012-06-27 21:29:38.337 UTC | null | 231,684 | null | 560,491 | null | 1 | 112 | objective-c|memory-management|retaincount | 24,995 | <p>You should never use <code>-retainCount</code>, because it never tells you anything useful. The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.</p>
<p>For example:</p>
<ul>
<li>You'd think that <code>[NSNumber numberWithInt:1]</code> would have a <code>retainCount</code> of 1. It doesn't. It's 2.</li>
<li>You'd think that <code>@"Foo"</code> would have a <code>retainCount</code> of 1. It doesn't. It's 1152921504606846975.</li>
<li>You'd think that <code>[NSString stringWithString:@"Foo"]</code> would have a <code>retainCount</code> of 1. It doesn't. Again, it's 1152921504606846975.</li>
</ul>
<p>Basically, since anything can retain an object (and therefore alter its <code>retainCount</code>), and since you don't have the source to most of the code that runs an application, an object's <code>retainCount</code> is meaningless.</p>
<p>If you're trying to track down why an object isn't getting deallocated, use the Leaks tool in Instruments. If you're trying to track down why an object was deallocated too soon, use the Zombies tool in Instruments.</p>
<p>But don't use <code>-retainCount</code>. It's a truly worthless method.</p>
<p><strong>edit</strong></p>
<p>Please everyone go to <a href="http://bugreport.apple.com" rel="noreferrer">http://bugreport.apple.com</a> and request that <code>-retainCount</code> be deprecated. The more people that ask for it, the better.</p>
<p><strong>edit #2</strong></p>
<p>As an update,<code>[NSNumber numberWithInt:1]</code> now has a <code>retainCount</code> of 9223372036854775807. If your code was expecting it to be 2, your code has now broken.</p> |
4,562,587 | Shortest way to print current year in a website | <p>I need to update a few hundred static HTML pages that have the copyright date hard coded in the footer. I want to replace it with some JavaScript that will automatically update each year.</p>
<p>Currently I’m using:</p>
<pre><code><script type="text/javascript">var year = new Date();document.write(year.getFullYear());</script>
</code></pre>
<p>Is this as short as it gets?</p> | 4,562,604 | 17 | 1 | null | 2010-12-30 12:29:04.707 UTC | 88 | 2022-08-14 00:05:12.687 UTC | 2018-09-07 12:51:39.267 UTC | null | 4,642,212 | null | 462,307 | null | 1 | 299 | javascript|html|date | 342,102 | <p>Years later, when doing something else I was reminded that <code>Date()</code> (without <code>new</code>) returns a string, and a way that's <em>one</em> character shorter that my original below came to me:</p>
<pre><code><script>document.write(/\d{4}/.exec(Date())[0])</script>
</code></pre>
<p>The first sequence of four digits in the string from <code>Date()</code> is <a href="https://tc39.es/ecma262/#sec-datestring" rel="noreferrer">specified to be the year</a>. (That wasn't specified behavior — though it was common — when my original answer below was posted.)</p>
<p>Of course, this solution is only valid for another 7,979 years (as of this writing in 2021), since as of the year 10000 it'll show "1000" instead of "10000".</p>
<hr />
<p>You've asked for a JavaScript solution, so here's the shortest I can get it:</p>
<pre><code><script>document.write(new Date().getFullYear())</script>
</code></pre>
<p>That will work in all browsers I've run across.</p>
<p>How I got there:</p>
<ul>
<li>You can just call <code>getFullYear</code> directly on the newly-created <code>Date</code>, no need for a variable. <code>new Date().getFullYear()</code> may look a bit odd, but it's reliable: the <code>new Date()</code> part is done first, then the <code>.getFullYear()</code>.</li>
<li>You can drop the <code>type</code>, because JavaScript is the default; this is even documented as part of the <a href="http://www.w3.org/TR/html5/scripting-1.html#script" rel="noreferrer">HTML5 specification</a>, which is likely in this case to be writing up what browsers already do.</li>
<li>You can drop the semicolon at the end for one extra saved character, because JavaScript has "automatic semicolon insertion," a feature I normally <em>despise</em> and rail against, but in this specific use case it should be safe enough.</li>
</ul>
<p>It's important to note that this only works on browsers where JavaScript is enabled. Ideally, this would be better handled as an offline batch job (<code>sed</code> script on *nix, etc.) once a year, but if you want the JavaScript solution, I think that's as short as it gets. (Now I've gone and tempted fate.)</p>
<hr />
<p><strong>However</strong>, unless you're using a server that can <em>only</em> provide static files, you're probably better off doing this on the server with a templating engine and using caching headers to allow the resulting page to be cached until the date needs to change. That way, you don't require JavaScript on the client. Using a non-<code>defer</code>/<code>async</code> <code>script</code> tag in the content also briefly delays the parsing and presentation of the page (for exactly this reason: because the code in the script might use <code>document.write</code> to output HTML).</p> |
14,796,003 | Prevent image hotlinking in Google Image Search | <p>Just recently, Google has introduced a new interface of their Image Search. From January 25 2013 on, full size images are shown directly inside Google, without sending visitors to the source site. I came across a site, that apparently has developed a sophisticated approach to prevent users from grabbing images from Google by introducing some sort of watermark <strong>dynamically</strong>. To see this, please search on the new Google Image Search interface for images by "fansshare.com". This link should be working: <a href="https://www.google.com/search?hl=en&tbo=d&tbm=isch&q=jessica%20biel%20gq&oq=&gs_l=&biw=1183&bih=708&sei=3VkXUcLdFsnHswbd4oHIDQ#hl=en&tbo=d&tbm=isch&sa=1&q=site%3afansshare.com&oq=site%3afansshare.com&gs_l=img.3...0.0.2.10846.0.0.0.0.0.0.0.0..0.0...0.0...1c..2.img.AWfe_f3vWxE&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&bvm=bv.42080656,d.Yms&fp=da7d521736767550&biw=1183&bih=708">Google Image Search</a>. If not, simply enter "site:fansshare.com" in Google search input filed. Be sure to be on the new search interface, though.</p>
<p>How does fansshare.com achieve this? I couldn't figure it out ...</p>
<p><strong>Update:</strong></p>
<p>fansshare.com adds a GET param to all of their image URLs, like <em>?rnd=69</em>. Example image URL:
<a href="http://fansshare.com/media/content/570_Jessica-Biel-talks-Kate-Beckinsale-Total-Recall-fight-5423.jpg?rnd=62">http://fansshare.com/media/content/570_Jessica-Biel-talks-Kate-Beckinsale-Total-Recall-fight-5423.jpg?rnd=62</a></p>
<p>This image URL works for a few calls or seconds, after which a redirect takes place to a cached, watermarked image:
<a href="http://fansshare.com/cached/?version=media/content/570_Jessica-Biel-talks-Kate-Beckinsale-Total-Recall-fight-5423.jpg&rnd=5810">http://fansshare.com/cached/?version=media/content/570_Jessica-Biel-talks-Kate-Beckinsale-Total-Recall-fight-5423.jpg&rnd=5810</a></p>
<p><strong>Edit:</strong></p>
<p>We have finally managed to fully mimic FansShare's hotlink protection and we've published our findings in the following, extensive blog post:</p>
<p><strong><a href="http://pixabay.com/en/blog/posts/hotlinking-protection-and-watermarking-for-google-32/">http://pixabay.com/en/blog/posts/hotlinking-protection-and-watermarking-for-google-32/</a></strong></p> | 14,860,184 | 4 | 6 | null | 2013-02-10 08:31:27.303 UTC | 11 | 2017-03-23 07:55:04.647 UTC | 2013-02-22 16:15:19.977 UTC | null | 996,638 | null | 996,638 | null | 1 | 11 | redirect|search-engine|hotlinking | 12,639 | <p>There is a solution but just like other solutions it's up to Google to intepret it as cloaking and ban at their will. This is a long one and probably will need further tinkering to work for your case. (Sorry in advance for the length)</p>
<p><strong>Setup</strong></p>
<p>For the sake of the example, let's just say that:</p>
<ul>
<li>site: <code>www.thesite.com</code> and</li>
<li>ImageURL base: <code>images.thesite.com</code></li>
</ul>
<p>(but ImageURL base could easily be <code>www.thesites.com/wp-content/uploads</code>)</p>
<p><strong>Target</strong></p>
<p>Our target is to make it so, (1) the full-size image is shown only with a watermark/overlay if it's requested from google images search and (2) don't break previously working stuff.</p>
<p><strong>Solution</strong></p>
<p>So the theoretical solution is the following.</p>
<p><strong>1)</strong> Check the User-Agent and if it contains <code>Googlebot</code> then serve the "trap" URL. The trap URL is your current image URL but slightly changed so you can treat it differently, so instead of the current normal: </p>
<p><code>http://images.thesite.com/wallpapers/awesome.jpg</code></p>
<p>you should print for Googlebots:</p>
<p><code>http://cacheimages.thesite.com/wallpapers/awesome.jpg</code></p>
<p>(where <code>cacheimages</code> is anything you want)</p>
<p><strong>2)</strong> Now the main dish; you should be able to target the requests to <code>http://cacheimages.thesite.com/</code> and have a script that acts like following:</p>
<pre><code> If the request comes from a bot (check user-agent headers)
Then serve the normal image without watermark
Else (if the request seems to be from a normal user)
Then check the referer: If it's from google (but NOT http://www.google.com/blank.html)
Redirect to the Post of the image (Note 1.)
Else if the refer is your site
Show the raw normal image
Else (any other referer, including http://www.google.com/blank.html)
Show watermarked image (Note 2.)
</code></pre>
<p><em>Note 1</em>: This will happen when people click "View original image" or the image itself</p>
<p><em>Note 2</em>: This will happen when people try to see the full-size image from the google image search results (and if they somehow arrive to the trap url of an image)</p>
<p><strong>3)</strong> You could HTTP redirect the old images to the new ImageURL base if the user-agent is Googlebots so the overlay/watermark trick starts working on old images faster (or even use Google Webmaster Tools if you use subdomains for images) and you are sure to preserve the SEO juice.</p>
<p><strong>Further actions</strong></p>
<p>You could do more changes if you want to be serious.</p>
<ol>
<li>Instead of showing the watermarked image redirect to more dynamic url <code>http://cacheimages.thesite.com/preview?p=/wallpapers/awesome.jpg&r=23535</code>
or the more modern use of HTTP headers for no indexing:
<code>X-Robots-Tag: noindex</code></li>
<li>Of course cache the watermarked images</li>
<li>Check the <code>Accept</code> http headers for cases that I haven't thought and serve image or redirect image post accordingly.</li>
</ol>
<p><strong>Note</strong></p>
<p>You may also have to think about international traffic so instead of <code>google.com</code> you want to check for <code>google.[a-z-\.]+/</code></p>
<p><strong>Conclusion</strong></p>
<p>This could be adapted to any system, I made it for one that has images on a subdomain, so it probably won't be exactly the same for other systems like wordpress etc. Also, I am sure Google will do a change on their image search in the following couple months to fix this issue.</p>
<p>An untested sample implementation of the idea can be found on <a href="https://github.com/sevastos/google-image-trap" rel="noreferrer">Github</a>.</p>
<p><strong>Disclaimers</strong></p>
<p>This hasn't been tested thoroughly and you could get banned, it's merely provided for research and educational purposes. I cannot be held responsible for any damages etc.</p> |
14,452,465 | How to create TextArea as input in a Shiny webapp in R? | <p>I am trying to create simple webapp where I want to take in multiline input from user using HTML textarea control. Is there any out of the box way of creating such an input control in Shiny?</p>
<p>Help page of textInput doesn't show much options </p>
<pre><code>textInput {shiny} R Documentation
Create a text input control
Description
Create an input control for entry of unstructured text values
Usage
textInput(inputId, label, value = "")
Arguments
inputId
Input variable to assign the control's value to
label
Display label for the control
value
Initial value
Value
A text input control that can be added to a UI definition.
Examples
textInput("caption", "Caption:", "Data Summary")
</code></pre> | 14,452,837 | 6 | 0 | null | 2013-01-22 05:59:43.12 UTC | 15 | 2016-11-07 14:55:21.903 UTC | null | null | null | null | 1,709,728 | null | 1 | 31 | r|textarea|textinput|shiny | 18,458 | <p>You can add a textarea using <code>tags</code> and it should be picked up by Shiny automatically:</p>
<pre><code>tags$textarea(id="foo", rows=3, cols=40, "Default value")
</code></pre>
<p>Or if you're more comfortable with straight HTML you can also do</p>
<pre><code>HTML('<textarea id="foo" rows="3" cols="40">Default value</textarea>')
</code></pre>
<p>In either case, <code>input$foo</code> should reflect the textarea's value.</p> |
14,399,205 | In R, how to make the variables inside a function available to the lower level function inside this function?(with, attach, environment) | <p><strong>Update 2</strong>
@G. Grothendieck posted two approaches. The second one is changing the function environment inside a function. This solves my problem of too many coding replicates. I am not sure if this is a good method to pass through the CRAN check when making my scripts into a package. I will update again when I have some conclusions.</p>
<p><strong>Update</strong></p>
<p>I am trying to pass a lot of input argument variables to <code>f2</code> and do not want to index every variable inside the function as <code>env$c, env$d, env$calls</code>, that is why I tried to use <code>with</code> in <code>f5</code> and <code>f6</code>(a modified <code>f2</code>). However, <code>assign</code> does not work with <code>with</code> inside the <code>{}</code>, moving <code>assign</code> outside <code>with</code> will do the job but in my real case I have a few <code>assign</code>s inside the <code>with</code> expressions which I do not know how to move them out of the <code>with</code> function easily.</p>
<p>Here is an example:</p>
<pre><code>## In the <environment: R_GlobalEnv>
a <- 1
b <- 2
f1 <- function(){
c <- 3
d <- 4
f2 <- function(P){
assign("calls", calls+1, inherits=TRUE)
print(calls)
return(P+c+d)
}
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f2(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f1()
</code></pre>
<p>Function <code>f2</code> is inside <code>f1</code>, when <code>f2</code> is called, it looks for variables <code>calls,c,d</code> in the environment <code>environment(f1)</code>. This is what I wanted.</p>
<p>However, when I want to use <code>f2</code> also in the other functions, I will define this function in the Global environment instead, call it <code>f4</code>.</p>
<pre><code>f4 <- function(P){
assign("calls", calls+1, inherits=TRUE)
print(calls)
return(P+c+d)
}
</code></pre>
<p>This won't work, because it will look for <code>calls,c,d</code> in the Global environment instead of inside a function where the function is called. For example:</p>
<pre><code>f3 <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f4(P=0) ## or replace here with f5(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f3()
</code></pre>
<p>The safe way should be define <code>calls,c,d</code> in the input arguments of <code>f4</code> and then pass these parameters into <code>f4</code>. However, in my case, there are too many variables to be passed into this function <code>f4</code> and it would be better that I can pass it as an environment and tell <code>f4</code> do not look in the Global environment(<code>environment(f4)</code>), only look inside the <code>environment</code> when <code>f3</code> is called. </p>
<p>The way I solve it now is to use the environment as a list and use the <code>with</code> function. </p>
<pre><code>f5 <- function(P,liste){
with(liste,{
assign("calls", calls+1, inherits=TRUE)
print(calls)
return(P+c+d)
}
)
}
f3 <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f5(P=0,as.list(environment())) ## or replace here with f5(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f3()
</code></pre>
<p>However, now <code>assign("calls", calls+1, inherits=TRUE)</code> does not work as it should be since <code>assign</code> does not modify the original object. The variable <code>calls</code> is connected to an optimization function where the objective function is <code>f5</code>. That is the reason I use <code>assign</code> instead of passing <code>calls</code> as an input arguments. Using <code>attach</code> is also not clear to me. Here is my way to correct the <code>assign</code> issue:</p>
<pre><code>f7 <- function(P,calls,liste){
##calls <<- calls+1
##browser()
assign("calls", calls+1, inherits=TRUE,envir = sys.frame(-1))
print(calls)
with(liste,{
print(paste('with the listed envrionment, calls=',calls))
return(P+c+d)
}
)
}
########
##################
f8 <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
##browser()
##v[i] <- f4(P=0) ## or replace here with f5(P=0)
v[i] <- f7(P=0,calls,liste=as.list(environment()))
c <- c+1
d <- d+1
}
f7(P=0,calls,liste=as.list(environment()))
print(paste('final call number',calls))
return(v)
}
f8()
</code></pre>
<p>I am not sure how this should be done in R. Am I on the right direction, especially when passing through the CRAN check? Anyone has some hints on this?</p> | 14,401,168 | 4 | 0 | null | 2013-01-18 12:40:37.96 UTC | 23 | 2020-06-12 19:15:33.043 UTC | 2013-01-22 09:49:34.303 UTC | null | 833,661 | null | 833,661 | null | 1 | 31 | r|function|environment-variables|with-statement|assign | 29,173 | <p><strong>(1) Pass caller's environment.</strong> You can explicitly pass the parent environment and index into it. Try this:</p>
<pre><code>f2a <- function(P, env = parent.frame()) {
env$calls <- env$calls + 1
print(env$calls)
return(P + env$c + env$d)
}
a <- 1
b <- 2
# same as f1 except f2 removed and call to f2 replaced with call to f2a
f1a <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f2a(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f1a()
</code></pre>
<p><strong>(2) Reset called function's environment</strong> We can reset the environment of <code>f2b</code> in <code>f1b</code> as shown here:</p>
<pre><code>f2b <- function(P) {
calls <<- calls + 1
print(calls)
return(P + c + d)
}
a <- 1
b <- 2
# same as f1 except f2 removed, call to f2 replaced with call to f2b
# and line marked ## at the beginning is new
f1b <- function(){
environment(f2b) <- environment() ##
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f2b(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f1b()
</code></pre>
<p><strong>(3) Macro using eval.parent(substitute(...))</strong> Yet another approach is to define a macro-like construct which effectively injects the body of <code>f2c</code> inline into <code>f1c1</code>. Here <code>f2c</code> is the same as <code>f2b</code> except for the <code>calls <- calls + 1</code> line (no <code><<-</code> needed) and the wrapping of the entire body in <code>eval.parent(substitute({...}))</code>. <code>f1c</code> is the same as <code>f1a</code> except the call to <code>f2a</code> is replaced with a call to <code>f2c</code> . </p>
<pre><code>f2c <- function(P) eval.parent(substitute({
calls <- calls + 1
print(calls)
return(P + c + d)
}))
a <- 1
b <- 2
f1c <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f2c(P=0)
c <- c+1
d <- d+1
}
return(v)
}
f1c()
</code></pre>
<p><strong>(4) defmacro</strong> This is almost the same as the the last solution except it uses <code>defmacro</code> in the gtools package to define the macro rather than doing it ourself. (Also see the Rcmdr package for another defmacro version.) Because of the way <code>defmacro</code> works we must also pass <code>calls</code> but since it's a macro and not a function this just tells it to substitute <code>calls</code> in and is not the same as passing <code>calls</code> to a function. </p>
<pre><code>library(gtools)
f2d <- defmacro(P, calls, expr = {
calls <- calls + 1
print(calls)
return(P + c + d)
})
a <- 1
b <- 2
f1d <- function(){
c <- 3
d <- 4
calls <- 0
v <- vector()
for(i in 1:10){
v[i] <- f2d(P=0, calls)
c <- c+1
d <- d+1
}
return(v)
}
f1d()
</code></pre> |
14,526,033 | Object has no method 'live' - jQuery | <pre><code><script>
$(document).ready(function(){
$('.delete').live('click', function(e){
alert('delete');
e.preventDefault();
});
});
</script>
<a href='#' id='_1' class='delete'>Delete</a>
</code></pre>
<p>Gives me an error:</p>
<blockquote>
<p>Uncaught TypeError: Object [object Object] has no method 'live' </p>
</blockquote>
<p>I just don't see the problem?</p> | 14,526,055 | 7 | 6 | null | 2013-01-25 16:26:43.5 UTC | 3 | 2013-06-08 11:15:49.893 UTC | null | null | null | null | 426,266 | null | 1 | 44 | javascript|jquery|live | 52,844 | <p><code>.live()</code> is a deprecated function (from 1.7+) and removed completely from jQuery 1.9+.</p>
<p>You can instead use <code>.on()</code> or <code>.bind()</code> methods:</p>
<p><a href="http://api.jquery.com/on/" rel="noreferrer">http://api.jquery.com/on/</a> <br>
<a href="http://api.jquery.com/bind/" rel="noreferrer">http://api.jquery.com/bind/</a></p> |
2,370,742 | Convert rtsp video stream to http stream | <p>I have the rtsp URL for a live video stream which I would like to access as an HTTP stream. Can someone please tell me if there are any components out there which I can put on my server to do this?</p>
<p>I do not have any idea how I can implement this. Would appreciate a heads up.</p>
<p>Thanks.</p> | 2,855,772 | 2 | 0 | null | 2010-03-03 11:28:26.98 UTC | 11 | 2020-06-24 09:12:48.73 UTC | 2010-05-18 09:00:25.373 UTC | null | 21,234 | null | 46,297 | null | 1 | 16 | video|video-streaming|rtsp|live-video | 70,223 | <p>I would say that your best bet is to use either FFmpeg or VLC. Both are open source software and are widely used among hobbyists and also as a part of multiple different services. Also both can take in RTSP streams and create an HTTP stream (with live transcoding if needed).</p>
<p>FFmpeg's RTSP support has improved as of lately, but IMO VLC is way better at the moment (May 2010). Check the documentation on the web sites for experimenting with the command-line parameters for finding the required ones to match your needs. FFmpeg and VLC are very flexible and you can do a whole lot of stuff with them in addition to proxying from RTSP stream to HTTP.</p>
<p>FFmpeg: <a href="http://www.ffmpeg.org/" rel="noreferrer">http://www.ffmpeg.org/</a></p>
<p>VLC: <a href="http://www.videolan.org/vlc/" rel="noreferrer">http://www.videolan.org/vlc/</a></p> |
3,204,349 | jQuery - get the index of a element with a certain class | <p>I have a list like this one:</p>
<pre><code><li> .... </li>
<li> .... </li>
<li> .... </li>
<li class="active"> .... </li>
<li> .... </li>
</code></pre>
<p>I want to find out the index (number in the list) of the item with the "active" class element.
in this case the index would be 4 (or 3 if we're starting from 0)
How can I do that?</p> | 3,204,375 | 2 | 0 | null | 2010-07-08 14:01:55.643 UTC | 3 | 2010-07-08 14:15:49.513 UTC | null | null | null | null | 376,947 | null | 1 | 39 | javascript|jquery | 63,504 | <p>With the <a href="http://api.jquery.com/index/" rel="noreferrer">.index()</a> :</p>
<pre><code>$('li.active').index()
</code></pre>
<p>Working example here:</p>
<p><a href="http://jsfiddle.net/EcZZL/" rel="noreferrer">http://jsfiddle.net/EcZZL/</a></p>
<p>Edit - added link to the api for <code>.index()</code> per Nick's advice</p> |
41,395,566 | how to export html data to pdf in angularjs | <p>this is my html code where i rendered all <code>json</code> data from <code>.js</code> file but getting </p>
<blockquote>
<p>TypeError: Cannot convert undefined or null to object
at Function.keys ()
at DocMeasure.measureNode (pdfmake.js:15647)
at DocMeasure.measureDocument (pdfmake.js:15635)
at LayoutBuilder.tryLayoutDocument (pdfmake.js:15088)
at LayoutBuilder.layoutDocument (pdfmake.js:15076)
at PdfPrinter.createPdfKitDocument (pdfmake.js:2130)
at Document._createDoc (pdfmake.js:82)
at Document.getDataUrl (pdfmake.js:177)
at Document.open (pdfmake.js:109)
at l.$scope.openPdf (app.js:29)
</p>
</blockquote>
<pre><code><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="pdfmake.js"></script>
<script type="text/javascript" src="vfs_fonts.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="raj.js"></script>
<script type="text/javascript" src="jspdf.js"></script>
</head>
<body ng-app="pdfDemo">
<div ng-controller="pdfCtrl">
<div id="pdfContent">
<table id="example-table">
<thead>
<th>firstName</th>
<th>lastName</th>
<th>Gender</th>
<th>Mobile</th>
</thead>
<tbody>
<tr ng-repeat="emp in employees">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.gender}}</td>
<td>{{emp.mobile}}</td>
</tr>
</tbody>
</table>
</div>
<button ng-click="openPdf()">Open Pdf</button>
<button ng-click="downloadPdf()">Download Pdf</button>
</div>
</body>
</html>
</code></pre> | 41,395,618 | 5 | 0 | null | 2016-12-30 11:31:26.56 UTC | 10 | 2019-05-24 11:27:16.733 UTC | 2016-12-30 12:13:07.233 UTC | null | 2,042,251 | null | 7,357,730 | null | 1 | 13 | angularjs | 70,009 | <p>You can use <a href="http://pdfmake.org/#/" rel="noreferrer"><code>pdfmake</code></a>, to export the pdf </p>
<p><strong>DEMO</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module("app", []);
app.controller("listController", ["$scope",
function($scope) {
$scope.data= [{"agence":"CTM","secteur":"Safi","statutImp":"operationnel"}];
$scope.export = function(){
html2canvas(document.getElementById('exportthis'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500,
}]
};
pdfMake.createPdf(docDefinition).download("test.pdf");
}
});
}
}
]);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.22/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="listController">
<div id="exportthis">
{{data}}
</div>
<button ng-click="export()">export</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p> |
40,111,236 | how to reset the filters in a datatable | <p>I am unable to clear the filters using the fnFilter().</p>
<p>Here is my HTML code :</p>
<pre><code><table id="todays _table>
<thead>
<tr id="todays_search_input_feilds">
<td class="input_filter">
<input type="text" id="type" class="form-control search_events">
</td>
<td class="input_filter">
<input type="text" id="vendor " class="form-control search_events">
</td>
</tr>
</thead>
</table>
</code></pre>
<p>And Here is my JQuery Code</p>
<pre><code>$('#todays_table').dataTable().fnFilter('');
oTable.fnClearTable();
</code></pre>
<p>I tried clearing using the following approach:</p>
<pre><code>$('input[class="form-control search_events"]').val('');
</code></pre>
<p>But the problem with this is that, it is clearing the value but the data is not loading in the dataTable. It is loading only after i click on any of the filters</p> | 40,111,707 | 6 | 0 | null | 2016-10-18 14:40:37.967 UTC | 3 | 2019-07-12 16:29:57.223 UTC | 2016-10-18 15:24:15.847 UTC | null | 6,462,896 | null | 6,462,896 | null | 1 | 11 | jquery|datatables | 50,022 | <p><strong>To reset custom filters</strong></p>
<p>If you're using custom filtering function as in <a href="http://legacy.datatables.net/release-datatables/examples/plug-ins/range_filtering.html" rel="noreferrer">this example</a>, you need to clear controls involved before filtering and redrawing the table.</p>
<pre><code>$('input.search_events').val('');
$('#todays_table').dataTable().fnDraw();
</code></pre>
<p><strong>To reset global search</strong></p>
<ul>
<li><p>jQuery DataTables 1.9+</p>
<p>Call <code>fnFilter()</code> API method with empty string as a first argument to reset the global search and redraw the table.</p>
<p>For example:</p>
<pre><code>$('#example').dataTable().fnFilter('');
</code></pre></li>
<li><p>jQuery DataTables 1.10</p>
<p>Call <a href="https://datatables.net/reference/api/search()" rel="noreferrer"><code>search()</code></a> API method with empty string as a first argument followed by call to <a href="https://datatables.net/reference/api/draw()" rel="noreferrer"><code>draw()</code></a> API method to reset the global search and redraw the table.</p>
<p>For example:</p>
<pre><code>$('#example').DataTable().search('').draw();
</code></pre></li>
</ul> |
40,690,202 | Previous route name in Laravel 5.1-5.8 | <p>I try to find name of previous route in Laravel 5.1.
With:</p>
<pre><code>{!! URL::previous() !!}
</code></pre>
<p>I get the route url, but I try to get route name like I get for current page:</p>
<pre><code>{!! Route::current()->getName() !!}
</code></pre>
<p>My client wont a different text for <em>Thank you page</em>, depends on from page (<em>Register page</em> or <em>Contact page</em>) user go to <em>Thank you page</em>. I try with:</p>
<pre><code>{!! Route::previous()->getName() !!}
</code></pre>
<p>But that didn't work. I try to get something like:</p>
<pre><code>@if(previous-route == 'contact')
some text
@else
other text
@endif
</code></pre> | 40,690,569 | 4 | 0 | null | 2016-11-19 07:10:26.193 UTC | 2 | 2020-05-05 17:59:28.84 UTC | 2019-05-22 12:39:17.19 UTC | null | 2,807,381 | null | 2,807,381 | null | 1 | 21 | laravel|laravel-routing | 38,577 | <p>Here what work for me. I find this answer and this question and modify it to work in my case: <a href="https://stackoverflow.com/a/36476224/2807381">https://stackoverflow.com/a/36476224/2807381</a></p>
<pre><code>@if(app('router')->getRoutes()->match(app('request')->create(URL::previous()))->getName() == 'public.contact')
Some text
@endif
</code></pre>
<p><strong>Update for 5.8 version</strong> by <a href="https://stackoverflow.com/users/2134999/robert">Robert</a></p>
<pre><code>app('router')->getRoutes()->match(app('request')->create(url()->previous()))->getName()
</code></pre> |
27,470,885 | How does DMA work with PCI Express devices? | <p>Let's suppose a CPU wants to make a DMA read transfer from a PCI Express device. Communication to PCI Express devices is provided by transaction layer packets (TLP). Theoretically, the maximum payload size is 1024 doubleword for TLP. So how does a DMA controller act when a CPU gives a DMA read command to PCI Express device in size of 4 megabyte?</p> | 27,475,617 | 4 | 0 | null | 2014-12-14 15:37:26.087 UTC | 16 | 2022-04-14 00:06:02.7 UTC | 2017-04-21 19:14:58.223 UTC | null | 4,694,621 | null | 3,583,084 | null | 1 | 23 | dma|pci-e | 32,350 | <p>In the PCIe enumeration phase, the maximum allowed payload size is determined (it can be lower then the device's max payload size: e.g. a intermediate PCIe switch has a lower max. payload size).</p>
<p>Most PCIe devices are DMA masters, so the driver transfers the command to the device. The device will send several write packets to transmit 4 MiB in xx max sized TLP chunks.</p>
<h2>Edit 1 in reply to comment 1:</h2>
<p>A PCI based bus has no "DMA Controller" in form of a chip or a sub circuit in the chipset. Every device on the bus can become a bus master. The main memory is always a slave.</p>
<p>Let's assume you have build your own PCIe device card, which can act as an PCI master and your program (running on CPU) wants to send data from that card to main memory (4 MiB).</p>
<p>The device driver knows the memory mapping for that particular memory region from operating system (some keywords: memory mapped I/O, PCI bus enumeration, PCI BARs, ).</p>
<p>The driver transfers the command (write), source-address, destination-address and length to the device. This can be done by sending bytes to a special address inside an pre-defined BAR or by writing into the PCI config space. The DMA master on the cards checks these special regions for new tasks (scatter-gather lists). If so, theses tasks get enqueued.</p>
<p>Now the DMA master knows where to send, how many data. He will read the data from local memory and wrap it into 512 byte TLPs of max payload size (the max payload size on path device <---> main memory is known from enumeration) and send it to the destination address. The PCI address-based routing mechanisms direct these TLPs to the main memory.</p> |
30,073,065 | Laravel: How do I parse this json data in view blade? | <p>Currently this is my view</p>
<pre><code>{{ $leads }}
</code></pre>
<p>And this is the output</p>
<pre><code>{"error":false,"member":[{"id":"1","firstName":"first","lastName":"last","phoneNumber":"0987654321","email":"[email protected]","owner":{
"id":"10","firstName":"first","lastName":"last"}}]}
</code></pre>
<p>I wanted to display something like this</p>
<pre><code>Member ID: 1
Firstname: First
Lastname: Last
Phone: 0987654321
Owner ID: 10
Firstname: First
Lastname: Last
</code></pre> | 30,073,428 | 9 | 0 | null | 2015-05-06 09:44:22.027 UTC | 14 | 2022-08-04 13:05:33.447 UTC | null | null | null | null | 4,348,178 | null | 1 | 30 | json|laravel|laravel-blade | 167,778 | <p>It's pretty easy.
First of all send to the view decoded variable (see <a href="http://laravel.com/docs/5.0/views">Laravel Views</a>):</p>
<pre><code>view('your-view')->with('leads', json_decode($leads, true));
</code></pre>
<p>Then just use common blade constructions (see <a href="http://laravel.com/docs/5.0/templates">Laravel Templating)</a>:</p>
<pre><code>@foreach($leads['member'] as $member)
Member ID: {{ $member['id'] }}
Firstname: {{ $member['firstName'] }}
Lastname: {{ $member['lastName'] }}
Phone: {{ $member['phoneNumber'] }}
Owner ID: {{ $member['owner']['id'] }}
Firstname: {{ $member['owner']['firstName'] }}
Lastname: {{ $member['owner']['lastName'] }}
@endforeach
</code></pre> |
34,523,679 | Aggregate multiple columns at once | <p>I have a data-frame likeso:</p>
<pre><code>x <-
id1 id2 val1 val2 val3 val4
1 a x 1 9
2 a x 2 4
3 a y 3 5
4 a y 4 9
5 b x 1 7
6 b y 4 4
7 b x 3 9
8 b y 2 8
</code></pre>
<p>I wish to aggregate the above by id1 & id2. I want to be able to get the means for val1, val2, val3, val4 at the same time.</p>
<p>How do i do this?</p>
<p>This is what i currently have but it works just for 1 column:</p>
<pre><code>agg <- aggregate(x$val1, list(id11 = x$id1, id2= x$id2), mean)
names(agg)[3] <- c("val1") # Rename the column
</code></pre>
<p>Also, how do i rename the columns which are outputted as means in the same statement given above</p> | 34,523,783 | 2 | 0 | null | 2015-12-30 05:50:17.243 UTC | 15 | 2020-01-05 21:41:16.237 UTC | null | null | null | null | 1,770,221 | null | 1 | 51 | r|aggregate | 173,340 | <p>We can use the formula method of <code>aggregate</code>. The variables on the 'rhs' of <code>~</code> are the grouping variables while the <code>.</code> represents all other variables in the 'df1' (from the example, we assume that we need the <code>mean</code> for all the columns except the grouping), specify the dataset and the function (<code>mean</code>).</p>
<pre><code>aggregate(.~id1+id2, df1, mean)
</code></pre>
<hr>
<p>Or we can use <code>summarise_each</code> from <code>dplyr</code> after grouping (<code>group_by</code>)</p>
<pre><code>library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
</code></pre>
<p>Or using <code>summarise</code> with <code>across</code> (<code>dplyr</code> devel version - <code>‘0.8.99.9000’</code>)</p>
<pre><code>df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
</code></pre>
<hr>
<p>Or another option is <code>data.table</code>. We convert the 'data.frame' to 'data.table' (<code>setDT(df1)</code>, grouped by 'id1' and 'id2', we loop through the subset of data.table (<code>.SD</code>) and get the <code>mean</code>.</p>
<pre><code>library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
</code></pre>
<h3>data</h3>
<pre><code>df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
</code></pre> |
36,657,299 | How can I Populate a ListView in JavaFX using Custom Objects? | <p>I'm a bit new to Java, JavaFX, and programming in general, and I have an issue that is breaking my brain.</p>
<p>In most of the tutorials I have looked up regarding populating a ListView (Using an ObservableArrayList, more specifically) the simplest way to do it is to make it from an ObservableList of Strings, like so:</p>
<pre><code>ObservableList<String> wordsList = FXCollections.observableArrayList("First word","Second word", "Third word", "Etc.");
ListView<String> listViewOfStrings = new ListView<>(wordsList);
</code></pre>
<p>But I don't want to use Strings. I would like to use a custom object I made called Words:</p>
<pre><code>ObservableList<Word> wordsList = FXCollections.observableArrayList();
wordsList.add(new Word("First Word", "Definition of First Word");
wordsList.add(new Word("Second Word", "Definition of Second Word");
wordsList.add(new Word("Third Word", "Definition of Third Word");
ListView<Word> listViewOfWords = new ListView<>(wordsList);
</code></pre>
<p>Each Word object only has 2 properties: wordString (A string of the word), and definition (Another string that is the word's definition). I have getters and setters for both.</p>
<p>You can see where this is going- the code compiles and works, but when I display it in my application, rather than displaying the titles of every word in the ListView, it displays the Word object itself as a String!</p>
<p><a href="https://i.stack.imgur.com/GJnH9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GJnH9.png" alt="Image showing my application and its ListView"></a></p>
<p>My question here is, specifically, is there a simple way to rewrite this:</p>
<pre><code>ListView<Word> listViewOfWords = new ListView<>(wordsList);
</code></pre>
<p>In such a way that, rather than taking Words directly from wordsList, it accesses the wordString property in each Word of my observableArrayList? </p>
<p>Just to be clear, this isn't for android, and the list of words will be changed, saved, and loaded eventually, so I can't just make another array to hold the wordStrings. I have done a bit of research on the web and there seems to be a thing called 'Cell Factories', but it seems unnecessarily complicated for what seems to be such a simple problem, and as I stated before, I'm a bit of a newbie when it comes to programming. </p>
<p>Can anyone help? This is my first time here, so I'm sorry if I haven't included enough of my code or I've done something wrong.</p> | 36,657,553 | 2 | 0 | null | 2016-04-15 21:42:26.4 UTC | 12 | 2022-06-24 19:47:02.137 UTC | 2019-10-13 07:06:47.61 UTC | null | 2,991,525 | null | 6,211,213 | null | 1 | 40 | java|listview|javafx | 37,727 | <p><em>Solution Approach</em></p>
<p>I advise using a <a href="https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ListView.html#setCellFactory-javafx.util.Callback-" rel="nofollow noreferrer">cell factory</a> to solve this problem.</p>
<pre><code>listViewOfWords.setCellFactory(param -> new ListCell<Word>() {
@Override
protected void updateItem(Word item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.getWord() == null) {
setText(null);
} else {
setText(item.getWord());
}
}
});
</code></pre>
<p><em>Sample Application</em></p>
<p><a href="https://i.stack.imgur.com/JjiXX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JjiXX.png" alt="add image" /></a></p>
<pre><code>import javafx.application.Application;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class CellFactories extends Application {
@Override
public void start(Stage stage) {
ObservableList<Word> wordsList = FXCollections.observableArrayList();
wordsList.add(new Word("First Word", "Definition of First Word"));
wordsList.add(new Word("Second Word", "Definition of Second Word"));
wordsList.add(new Word("Third Word", "Definition of Third Word"));
ListView<Word> listViewOfWords = new ListView<>(wordsList);
listViewOfWords.setCellFactory(param -> new ListCell<Word>() {
@Override
protected void updateItem(Word item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null || item.getWord() == null) {
setText(null);
} else {
setText(item.getWord());
}
}
});
stage.setScene(new Scene(listViewOfWords));
stage.show();
}
public static class Word {
private final String word;
private final String definition;
public Word(String word, String definition) {
this.word = word;
this.definition = definition;
}
public String getWord() {
return word;
}
public String getDefinition() {
return definition;
}
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p><em>Implementation Notes</em></p>
<p>Although you could override toString in your Word class to provide a string representation of the word aimed at representation in your ListView, I would recommend providing a cell factory in the ListView for extraction of the view data from the word object and representation of it in your ListView. Using this approach you get separation of concerns as you don't tie a the graphical view of your Word object with it's textual toString method; so toString could continue to have different output (for example full information on Word fields with a word name and a description for debugging purposes). Also, a cell factory is more flexible as you can apply various graphical nodes to create a visual representation of your data beyond just a straight text string (if you wish to do that).</p>
<p>Also, as an aside, I recommend making your Word objects <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html" rel="nofollow noreferrer">immutable objects</a>, by removing their setters. If you really need to modify the word objects themselves, then the best way to handle that is to have exposed observable properties for the object fields. If you also want your UI to update as the observable properties of your objects change, then you need to make your list cells aware of the changes to the associated items, by listening for changes to them (which is quite a bit more complex in this case, an <a href="https://stackoverflow.com/questions/31687642/callback-and-extractors-for-javafx-observablelist">extractor</a> can help). Note that, the list containing the words is already observable and ListView will take care of handling changes to that list, but if you modified the word definition for instance within a displayed word object, then your list view wouldn't pick up changes to the definition without appropriate listener logic in the ListView cell factory (or, preferably, an extractor).</p> |
31,803,817 | How to add second x-axis at the bottom of the first one in matplotlib.? | <p>I am refering to the question already asked <a href="https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib" title="How to add a second x-axis in matplotlib">here</a>.<br>
In this example the users have solved the second axis problem by adding it to the upper part of the graph where it coincide with the title. </p>
<p>Question:
Is it possible to add the second x-axis at the bottom of the first one?</p>
<p>Code: </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
X = np.linspace(0,1,1000)
Y = np.cos(X*20)
ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")
new_tick_locations = np.array([.2, .5, .9])
def tick_function(X):
V = 1/(1+X)
return ["%.3f" % z for z in V]
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()
</code></pre> | 31,808,931 | 2 | 0 | null | 2015-08-04 08:02:41.56 UTC | 8 | 2020-05-04 11:51:29.543 UTC | 2017-10-06 08:18:42.06 UTC | null | 4,720,935 | null | 5,175,708 | null | 1 | 14 | python|matplotlib | 26,131 | <p>As an alternative to the answer from @DizietAsahi, you can use <code>spines</code> in a similar way to the <code>matplotlib</code> example posted <a href="http://matplotlib.org/examples/pylab_examples/multiple_yaxis_with_spines.html" rel="noreferrer">here</a>.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
# Add some extra space for the second axis at the bottom
fig.subplots_adjust(bottom=0.2)
X = np.linspace(0,1,1000)
Y = np.cos(X*20)
ax1.plot(X,Y)
ax1.set_xlabel(r"Original x-axis: $X$")
new_tick_locations = np.array([.2, .5, .9])
def tick_function(X):
V = 1/(1+X)
return ["%.3f" % z for z in V]
# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")
# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes", -0.15))
# Turn on the frame for the twin axis, but then hide all
# but the bottom spine
ax2.set_frame_on(True)
ax2.patch.set_visible(False)
# as @ali14 pointed out, for python3, use this
# for sp in ax2.spines.values():
# and for python2, use this
for sp in ax2.spines.itervalues():
sp.set_visible(False)
ax2.spines["bottom"].set_visible(True)
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(tick_function(new_tick_locations))
ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$")
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/hXE3f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hXE3f.png" alt="enter image description here"></a></p> |
44,489,804 | How to show/hide widgets programmatically in Flutter | <p>In Android, every single <code>View</code> subclass has a <code>setVisibility()</code> method that allows you modify the visibility of a <code>View</code> object</p>
<p>There are 3 options of setting the visibility:</p>
<ul>
<li>Visible: Renders the <code>View</code> visible inside the layout</li>
<li>Invisible: Hides the <code>View</code>, but leaves a gap that is equivalent to what the <code>View</code> would occupy if it were visible</li>
<li>Gone: Hides the <code>View</code>, and removes it entirely from the layout. It's as if its <code>height</code> and <code>width</code> were <code>0dp</code></li>
</ul>
<p>Is there something equivalent to the above for Widgets in Flutter?</p>
<p>For a quick reference:
<a href="https://developer.android.com/reference/android/view/View.html#attr_android:visibility" rel="noreferrer">https://developer.android.com/reference/android/view/View.html#attr_android:visibility</a></p> | 44,489,903 | 16 | 0 | null | 2017-06-11 23:59:41.043 UTC | 53 | 2022-01-14 08:08:10.22 UTC | 2022-01-02 20:29:31.69 UTC | null | 6,618,622 | null | 3,217,522 | null | 1 | 266 | flutter|dart|flutter-layout|flutter-widget | 292,987 | <p>UPDATE: Since this answer was written, <a href="https://api.flutter.dev/flutter/widgets/Visibility-class.html" rel="noreferrer"><code>Visibility</code></a> was introduced and provides the best solution to this problem.</p>
<hr>
<p>You can use <code>Opacity</code> with an <code>opacity:</code> of <code>0.0</code> to draw make an element hidden but still occupy space.</p>
<p>To make it not occupy space, replace it with an empty <code>Container()</code>.</p>
<p>EDIT:
To wrap it in an Opacity object, do the following:</p>
<pre><code> new Opacity(opacity: 0.0, child: new Padding(
padding: const EdgeInsets.only(
left: 16.0,
),
child: new Icon(pencil, color: CupertinoColors.activeBlue),
))
</code></pre>
<p>Google Developers quick tutorial on Opacity: <a href="https://youtu.be/9hltevOHQBw" rel="noreferrer">https://youtu.be/9hltevOHQBw</a></p> |
22,751,035 | golang distinguish IPv4 IPv6 | <p>For a program I'm working on, I have to check whether an IP (the IP which connects me to the Internet) is public or private. For that, I need to distinguish if an IP is IPv4 or IPv6. </p>
<p>I wanted to check it by the length of the IP: </p>
<pre><code>conn, err := net.Dial("udp", "8.9.10.11:2342")
if err != nil {
fmt.Println("Error", err)
}
localaddr := conn.LocalAddr()
addr, _ := net.ResolveUDPAddr("udp", localaddr.String())
ip := addr.IP
fmt.Println(ip)
fmt.Println(len(ip))
</code></pre>
<p>Well, my IP is 192.168.2.100, so IPv4, but len(ip) tells me that the length is 16 which would be IPv6.
What is my mistake? Does any other method exist to distinguish between IPv4 and IPv6 which works always?</p> | 22,752,227 | 6 | 0 | null | 2014-03-30 22:58:20.053 UTC | 7 | 2022-03-01 02:26:43.78 UTC | null | null | null | null | 3,479,275 | null | 1 | 41 | go|ip | 33,064 | <p>jimt's answer is correct, but fairly complicated. I would simply check <code>ip.To4() != nil</code>. Since the documentation says "if ip is not an IPv4 address, To4 returns nil" this condition should return <code>true</code> if and only if the address is an IPv4 address.</p> |
22,626,117 | How can I re-download the pem file in AWS EC2? | <p>I made a key pair pem file called "test.pem", and I downloaded to my PC.</p>
<p>I made a new instance with this pem file.</p>
<p>Now I am in a different pc, and I don't have this pem file in my local, and my previous pc is in the middle of the sea (shipping).</p>
<p>How can I re-download the "test.pem" file again?</p> | 22,626,677 | 6 | 0 | null | 2014-03-25 05:29:25.68 UTC | 6 | 2022-08-27 20:47:50.56 UTC | 2020-12-27 16:38:57.123 UTC | null | 1,783,163 | null | 2,673,893 | null | 1 | 50 | amazon-web-services|amazon-ec2 | 83,035 | <p>No, you cannot download .pem file again. You can download the .pem file <strong>ONLY</strong> once and that is when you create a new key-pair.</p> |
27,356,776 | how to update form data in codeigniter | <p>I am new in codeigniter.</p>
<p>I am using codeigniter for this project. I have not getting how to update form data in the database. I have inserting,showing data in the databse is done. But I cant understand, how to update data in the database.</p>
<p>My controller:</p>
<pre><code> class User extends CI_Controller {
public function __construct() {
// Call the Model constructor
parent::__construct();
$this->load->model('usermodel');
}
public function insert() {
$this->load->view('userview');
if ($this->input->post('submit')) {
$this->usermodel->save();
}
}
public function display() {
$data = array();
$data['result'] = $this->usermodel->get_contents();
$this->load->view('usergrid', $data);
}
public function edit() {
$data = array();
$get = $this->uri->uri_to_assoc();
$data['result'] = $this->usermodel->entry_update( $get['id'] );
$this->load->view('useredit', $data);
if ($this->input->post('submit')) {
$this->usermodel->entry_update1($get['id']);
}
}
}
</code></pre>
<p>model:</p>
<pre><code> <?php
class Usermodel extends CI_Model {
public function __construct() {
// Call the Model constructor
parent::__construct();
}
public function save() {
//print_r($this->input->post('name'));
$data = array(
'name' => $this->input->post('name'),
'age' => $this->input->post('age'),
'address' => $this->input->post('address')
);
//var_dump($this->db);
$this->db->insert('user', $data);
}
public function get_contents() {
$this->db->select('*');
$this->db->from('user');
$query = $this->db->get();
return $result = $query->result();
}
public function entry_update( $id ) {
$this->db->select('*');
$this->db->from('user');
$this->db->where('id',$id );
$query = $this->db->get();
return $result = $query->row_array();
}
public function entry_update1($id) {
$data = array(
'name' => $this->input->post('name'),
'age' => $this->input->post('age'),
'address' => $this->input->post('address')
);
$this->db->where('id', $id);
$this->db->update('user', $data);
}
}
?>
</code></pre>
<p>view:</p>
<pre><code> <html>
<head>
<title>user registration</title>
</head>
<body>
<form action="edit" method="POST" name="myform">
<input type="hidden" name="id" value="<?php echo $result['id']; ?>">
username :<input type="text" name="name" value="<?php echo $result['name'] ?>"></br>
age :<input type="text" name="age" value="<?php echo $result['age'] ?>"></br>
Address :<input type="text" name="address" value="<?php echo $result['address'] ?>"></br>
<input type="submit" value="update" name="submit">
</form>
</body>
</html>
</code></pre>
<p>Thank you in advance for your help.</p> | 27,356,953 | 3 | 0 | null | 2014-12-08 11:15:27.07 UTC | 2 | 2020-11-26 07:34:41.08 UTC | 2020-11-26 07:34:41.08 UTC | null | 1,783,163 | null | 2,746,947 | null | 1 | 3 | php|codeigniter | 55,880 | <p>You are only passing $id in</p>
<p><code>$this->usermodel->entry_update1($get['id']);</code></p>
<p>and in function u did </p>
<pre><code>public function entry_update1($id) {
$this->db->where('id', $id);
$this->db->update('user', $data);
}
</code></pre>
<p>so you have to pass $data also in you function call</p>
<p><code>$this->usermodel->entry_update1($get['id'], $data);</code></p>
<pre><code>public function entry_update1($id, $data) {
$this->db->where('id', $id);
$this->db->update('user', $data);
}
</code></pre> |
34,078,497 | ESP8266 WiFiClient simple HTTP GET | <p>I'm working on simple problem of reading a webpage using ESP8266 and <a href="https://github.com/sandeepmistry/esp8266-Arduino/tree/master/esp8266com/esp8266/libraries/ESP8266WiFi" rel="nofollow noreferrer">ESP8266WiFi library</a>.</p>
<p>I changed only a few lines in example and don't know whats the problem. Thats my code:</p>
<pre class="lang-c prettyprint-override"><code>include <ESP8266WiFi.h>
const char* ssid = "WiwoNET";
const char* password = "xxxxxxx";
const char* host = "https://pure-caverns-1350.herokuapp.com";
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/stan";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
// Read all the lines of the reply from server and print them to Serial
Serial.println("Respond:");
while(client.available()){
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
</code></pre>
<p>And what I see in serial monitor is:</p>
<pre><code>Connecting to WiwoNET
.......
WiFi connected
IP address:
192.168.0.111
connecting to https://pure-caverns-1350.herokuapp.com
Requesting URL: /stan
Informacja zwrotna:
HTTP/1.1 400 Bad Request
Connection: close
Server: Cowboy
Date: Thu, 03 Dec 2015 23:38:59 GMT
Content-Length: 0
closing connection
</code></pre>
<p>I was looking at heroku's logs and nothing is showing there.
Thank you in advance for any kind of help.</p> | 34,096,104 | 1 | 0 | null | 2015-12-03 23:50:07.783 UTC | 6 | 2021-03-12 15:57:51.583 UTC | 2021-03-12 15:57:51.583 UTC | null | 920,173 | null | 3,184,237 | null | 1 | 8 | http|arduino|esp8266 | 77,407 | <p>You must have been following the example at <a href="https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino</a></p>
<p>There's one crucial piece you missed, though. The <code>host</code> value must not be prepended with a scheme in URI-style such as <code>http://</code> or <code>https://</code>. Look at the example again and use</p>
<pre><code>const char* host = "pure-caverns-1350.herokuapp.com";
</code></pre>
<p>instead.</p>
<p>You can see very well what's going on under the hood of HTTP if run <code>curl -v http://pure-caverns-1350.herokuapp.com/stan</code> in your console.</p> |
47,060,534 | how do POST request in puppeteer? | <pre><code>(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://www.example.com/search');
const data = await page.content();
browser.close();
res.send(data);
})();
</code></pre>
<p>I do this code for send <code>get</code> request. I don't understand how I should send <code>post</code> request?</p> | 49,385,769 | 3 | 0 | null | 2017-11-01 17:31:20.103 UTC | 7 | 2020-06-17 23:26:33.193 UTC | null | null | null | null | 6,704,419 | null | 1 | 23 | google-chrome|http|https|google-chrome-headless|puppeteer | 52,746 | <p>Getting the "order" right can be a bit of a challenge. Documentation doesn't have that many examples... there are some juicy items in the repository in the example folder that you should definitely take a look at. </p>
<p><a href="https://github.com/GoogleChrome/puppeteer/tree/master/examples" rel="noreferrer">https://github.com/GoogleChrome/puppeteer/tree/master/examples</a></p>
<p>Here is the example; place the following into an async block: </p>
<pre class="lang-js prettyprint-override"><code> // Create browser instance, and give it a first tab
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Allows you to intercept a request; must appear before
// your first page.goto()
await page.setRequestInterception(true);
// Request intercept handler... will be triggered with
// each page.goto() statement
page.on('request', interceptedRequest => {
// Here, is where you change the request method and
// add your post data
var data = {
'method': 'POST',
'postData': 'paramFoo=valueBar&paramThis=valueThat'
};
// Request modified... finish sending!
interceptedRequest.continue(data);
});
// Navigate, trigger the intercept, and resolve the response
const response = await page.goto('https://www.example.com/search');
const responseBody = await response.text();
console.log(responseBody);
// Close the browser - done!
await browser.close();
</code></pre> |
38,951,345 | How to get rid of multilevel index after using pivot table pandas? | <p>I had following data frame (the real data frame is much more larger than this one ) :</p>
<pre><code>sale_user_id sale_product_id count
1 1 1
1 8 1
1 52 1
1 312 5
1 315 1
</code></pre>
<p>Then reshaped it to move the values in sale_product_id as column headers using the following code:</p>
<pre><code>reshaped_df=id_product_count.pivot(index='sale_user_id',columns='sale_product_id',values='count')
</code></pre>
<p>and the resulting data frame is:</p>
<pre><code>sale_product_id -1057 1 2 3 4 5 6 8 9 10 ... 98 980 981 982 983 984 985 986 987 99
sale_user_id
1 NaN 1.0 NaN NaN NaN NaN NaN 1.0 NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
3 NaN 1.0 NaN NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
4 NaN NaN 1.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
</code></pre>
<p>as you can see we have a multililevel index , what i need is to have sale_user_is in the first column without multilevel indexing:</p>
<p>i take the following approach :</p>
<pre><code>reshaped_df.reset_index()
</code></pre>
<p>the the result would be like this i still have the sale_product_id column , but i do not need it anymore:</p>
<pre><code>sale_product_id sale_user_id -1057 1 2 3 4 5 6 8 9 ... 98 980 981 982 983 984 985 986 987 99
0 1 NaN 1.0 NaN NaN NaN NaN NaN 1.0 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 3 NaN 1.0 NaN NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 4 NaN NaN 1.0 NaN NaN NaN NaN NaN NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN
</code></pre>
<p>i can subset this data frame to get rid of <code>sale_product_id</code> but i don't think it would be efficient.I am looking for an efficient way to get rid of multilevel indexing while reshaping the original data frame</p> | 38,951,373 | 6 | 1 | null | 2016-08-15 07:59:27.917 UTC | 13 | 2022-07-12 04:57:46.037 UTC | 2021-11-29 15:56:15.38 UTC | null | 8,410,477 | null | 5,698,888 | null | 1 | 42 | python|pandas|dataframe|pivot-table|data-analysis | 52,452 | <p>You need remove only <code>index name</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="noreferrer"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p>
<pre><code>print (reshaped_df)
sale_product_id 1 8 52 312 315
sale_user_id
1 1 1 1 5 1
print (reshaped_df.index.name)
sale_user_id
print (reshaped_df.rename_axis(None))
sale_product_id 1 8 52 312 315
1 1 1 1 5 1
</code></pre>
<p>Another solution working in pandas below <code>0.18.0</code>:</p>
<pre><code>reshaped_df.index.name = None
print (reshaped_df)
sale_product_id 1 8 52 312 315
1 1 1 1 5 1
</code></pre>
<hr>
<p>If need remove <code>columns name</code> also:</p>
<pre><code>print (reshaped_df.columns.name)
sale_product_id
print (reshaped_df.rename_axis(None).rename_axis(None, axis=1))
1 8 52 312 315
1 1 1 1 5 1
</code></pre>
<p>Another solution:</p>
<pre><code>reshaped_df.columns.name = None
reshaped_df.index.name = None
print (reshaped_df)
1 8 52 312 315
1 1 1 1 5 1
</code></pre>
<p>EDIT by comment:</p>
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>reset_index</code></a> with parameter <code>drop=True</code>:</p>
<pre><code>reshaped_df = reshaped_df.reset_index(drop=True)
print (reshaped_df)
sale_product_id 1 8 52 312 315
0 1 1 1 5 1
#if need reset index nad remove column name
reshaped_df = reshaped_df.reset_index(drop=True).rename_axis(None, axis=1)
print (reshaped_df)
1 8 52 312 315
0 1 1 1 5 1
</code></pre>
<p>Of if need remove only column name:</p>
<pre><code>reshaped_df = reshaped_df.rename_axis(None, axis=1)
print (reshaped_df)
1 8 52 312 315
sale_user_id
1 1 1 1 5 1
</code></pre>
<p>Edit1:</p>
<p>So if need create new column from <code>index</code> and remove <code>columns names</code>:</p>
<pre><code>reshaped_df = reshaped_df.rename_axis(None, axis=1).reset_index()
print (reshaped_df)
sale_user_id 1 8 52 312 315
0 1 1 1 1 5 1
</code></pre> |
41,978,408 | Changing style of a button on click | <p>Is it possible to change <code>background-color</code> of my button <code>onClick</code> function?</p>
<p>ex. click <code>background-color: black</code>, another click <code>background-color: white</code> </p>
<p>I've tried something like <code>this.style</code>, no result.</p>
<p>I've managed to get overlay working and insert needed data inside of it.
But didn't managed to find any post that could help me.
I am using react-bootstrap.
This is my code.</p>
<pre><code> const metaDataOverlay = (
<div>
<style type="text/css">{`
.btn-overlay {
background-color: white;
margin-right: -15px;
margin-left: -15px;
padding-bottom: -20px;
padding: 0;
}
`}</style>
<ButtonToolbar>
<ButtonGroup>
<OverlayTrigger trigger={['hover', 'focus']} placement="left" overlay={popoverHoverFocus}>
<Button bsStyle="overlay" onClick={ clicked } onKeyPress={ keypress }>
<div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
<a href={url} onClick={(e)=>{e.preventDefault(); console.log("123")}}>
<div>
<img data-qa="poster" className={bemBlocks.item("poster")} src={result._source.poster} width="240" height="240"/>
</div>
</a>
</div>
</Button>
</OverlayTrigger>
</ButtonGroup>
</ButtonToolbar>
</div>
)
</code></pre> | 41,978,912 | 6 | 0 | null | 2017-02-01 11:15:41.867 UTC | 13 | 2021-03-18 15:18:21.45 UTC | null | null | null | null | 3,350,597 | null | 1 | 39 | reactjs|react-bootstrap | 169,831 | <p>You can try to use state to store the color. Maybe this would give you the idea how to solve the problem :</p>
<pre><code>class Test extends React.Component {
constructor(){
super();
this.state = {
black: true
}
}
changeColor(){
this.setState({black: !this.state.black})
}
render(){
let btn_class = this.state.black ? "blackButton" : "whiteButton";
return (
<button className={btn_class} onClick={this.changeColor.bind(this)}>
Button
</button>
)
}
}
React.render(<Test />, document.getElementById('container'));
</code></pre>
<p><a href="https://jsfiddle.net/tkkqx2y2/" rel="noreferrer">Here is a fiddle.</a></p> |
5,769,081 | Connecting to DB from a Chrome Extension? | <p>I am building a chrome extension which will only be available for people within the company I work for.
The extension needs input - which can be generated with a simple query to a shared MySQL DB server (to which all employees can access with read only permissions).</p>
<p>The question is - since the extension is all client side (mainly Javascript) - what's the simplest way to access the DB and run the query? Do I have to create a php/java(/...) service which does that for the extension?</p> | 5,769,121 | 1 | 0 | null | 2011-04-24 06:34:20.87 UTC | 18 | 2022-05-29 14:58:03.693 UTC | null | null | null | null | 610,995 | null | 1 | 28 | javascript|mysql|google-chrome | 28,623 | <p>You'll have to create an intermediary web app that will interface with the Database. Then you can make AJAX calls from the extension to your web app's API, which will in turn query the database and return results.</p>
<p>Chrome Extension → Web App API → MySQL</p>
<p><a href="https://developer.chrome.com/docs/extensions/mv2/xhr" rel="noreferrer">More info on Chrome AJAX API here</a></p> |
23,507,589 | Is it possible to set a fact of a list in Ansible? | <p>Is it possible to set a fact containing a list in Ansible using <code>set_fact</code>? What's the correct syntax for it?</p> | 23,522,774 | 6 | 0 | null | 2014-05-07 02:16:18.737 UTC | 15 | 2022-02-12 20:58:54.803 UTC | 2022-02-12 20:56:05.347 UTC | null | 2,123,530 | null | 335,918 | null | 1 | 40 | ansible | 69,643 | <p>Indeed it is. You need to quote the entire list though:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: set fact
set_fact: foo="[ 'one', 'two', 'three' ]"
- name: debug
debug: msg={{ item }}
with_items: foo
</code></pre>
<p>The above tasks should generate the following output:</p>
<pre class="lang-none prettyprint-override"><code>TASK: [set fact] **************************************************************
ok: [localhost]
TASK: [debug] *****************************************************************
ok: [localhost] => (item=one) => {
"item": "one",
"msg": "one"
}
ok: [localhost] => (item=two) => {
"item": "two",
"msg": "two"
}
ok: [localhost] => (item=three) => {
"item": "three",
"msg": "three"
}
</code></pre> |
44,674,532 | How to filter a list in-place with Kotlin? | <p>In Java I can remove items from a list with this code:</p>
<pre><code>private void filterList(List<Item> items) {
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
if (checkItem(iterator.next())) {
iterator.remove();
}
}
}
</code></pre>
<p>How to make the same in Kotlin (i.e. remove some items in a <code>List</code> without re-creation)? </p> | 44,674,612 | 3 | 1 | null | 2017-06-21 11:14:02.497 UTC | 9 | 2019-05-14 15:49:35.023 UTC | 2019-05-14 15:49:35.023 UTC | null | 1,000,551 | null | 1,393,280 | null | 1 | 38 | list|kotlin|filtering | 22,585 | <p>Just use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/retain-all.html" rel="noreferrer"><code>.retainAll { ... }</code></a> or <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/remove-all.html" rel="noreferrer"><code>.removeAll { ... }</code></a>, both accepting a predicate, to filter it in-place:</p>
<pre><code>items.retainAll { shouldRetain(it) }
</code></pre>
<p><sup></p>
<pre><code>items.removeAll { shouldRemove(it) }
</code></pre>
<p>Note that <code>items</code> should be a <code>MutableList<T></code> for that, not just <code>List<T></code>, which is a read-only list in Kotlin and thus does not expose any mutating functions (see: <a href="https://kotlinlang.org/docs/reference/collections.html#collections" rel="noreferrer"><em>Collections</em></a> in the language reference).</p>
<p><sub>By the way, these two function are implemented efficiently for lists that support random access: then the list is not compacted after each item is removed (<em>O(n<sup>2</sup>)</em> time worst-case), and instead the items are moved within the list as it is processed, giving <em>O(n)</em> time.</sub></p>
<hr>
<p>And if you don't want to modify the original list, you can produce a separate collection with only the items you want to retain using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter.html" rel="noreferrer"><code>.filter { ... }</code></a> or <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-not.html" rel="noreferrer"><code>.filterNot { ... }</code></a>, this will work for read-only <code>List<T></code> as well:</p>
<pre><code>val filtered = items.filter { shouldRetain(it) }
</code></pre>
<p></sup></p>
<pre><code>val filtered = items.filterNot { shouldRemove(it) }
</code></pre> |
21,098,350 | Python iterate over two lists simultaneously | <p>Is there a way in python to forloop over two or more lists simultaneously?</p>
<p>Something like</p>
<pre><code>a = [1,2,3]
b = [4,5,6]
for x,y in a,b:
print x,y
</code></pre>
<p>to output</p>
<pre><code>1 4
2 5
3 6
</code></pre>
<p>I know that I can do it with tuples like</p>
<pre><code>l = [(1,4), (2,5), (3,6)]
for x,y in l:
print x,y
</code></pre> | 21,098,360 | 1 | 0 | null | 2014-01-13 18:11:27.783 UTC | 7 | 2021-05-23 13:34:30.073 UTC | 2014-01-13 18:15:00.95 UTC | null | 100,297 | null | 2,694,385 | null | 1 | 26 | python|list|python-2.7|foreach|iteration | 63,904 | <p>You can use the <a href="http://docs.python.org/2/library/functions.html#zip" rel="noreferrer"><code>zip()</code> function</a> to pair up lists:</p>
<pre><code>for x, y in zip(a, b):
</code></pre>
<p>Demo:</p>
<pre><code>>>> a = [1,2,3]
>>> b = [4,5,6]
>>> for x, y in zip(a, b):
... print x, y
...
1 4
2 5
3 6
</code></pre> |
21,360,519 | jQuery .fadeIn() on page load? | <p>I'm trying to set up some code so that I have a that is hidden at first but then fades in after the page is loaded.</p>
<p>I have the following HTML code:</p>
<pre><code><div class="hidden">
<p>This is some text.</p>
</div>
</code></pre>
<p>Then I also have this CSS code, which hides the <code><div></code>.</p>
<pre><code>div.hidden
{
display: none
}
</code></pre>
<p>Finally, I have my jQuery:</p>
<pre><code>$(document).ready(function() {
$('div').fadeOut(1);
$('div').removeClass('hidden');
$('div').fadeIn(1000);
});
</code></pre>
<p>What I was hoping would happen was that the first .fadeOut() would fade out the , the removeClass would stop the CSS from hiding it, and the final .fadeIn() would fade it back onto the page. Unfortunately, this did not work.</p>
<p>You can view the code here:<a href="http://jsfiddle.net/Bm62Y/" rel="noreferrer">Fiddle</a></p>
<p>So can someone please tell me how to keep a <code><div></code> hidden until a page loads, and then fade it in using jQuery?</p>
<p>Thanks!</p> | 21,360,534 | 4 | 0 | null | 2014-01-26 06:32:54.5 UTC | 2 | 2017-02-03 14:22:16.207 UTC | 2014-01-26 16:29:16.147 UTC | null | 87,015 | null | 2,962,388 | null | 1 | 13 | javascript|jquery|html|css|fadein | 70,346 | <p>The problem is <code>fadeIn</code> works on hidden elements, when you remove the hidden class before the <code>fadeIn()</code> is called the element is fully displayed so there is nothing to to <code>fadeIn()</code></p>
<p>It should be</p>
<pre><code>$(document).ready(function () {
$('div.hidden').fadeIn(1000).removeClass('hidden');
});
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/arunpjohny/2nzHT/" rel="noreferrer">Fiddle</a></p> |
21,278,995 | Remove :focus with jquery | <p>I have an input field. When a user focuses on this field, the background of this field will change.</p>
<p>I have a link on my page, too. I want to remove <code>:focus</code> when the mouse hovers on this link and the user is on that input field. </p>
<p>I use <code>removeClass(':focus')</code> but this code does not work!</p>
<p><strong>HTML:</strong></p>
<pre><code><form>
<input type="text" name="email" />
</form>
<a href="#" id="link">Sample Link</a>
</code></pre>
<p><strong>Javascript:</strong></p>
<pre><code>$(document).ready(function () {
$('#link').hover(function (){
$('form input[name=email]').removeClass(':focus');
}, function (){
$('form input[name=email]').addClass(':focus');
});
});
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>form input[name=email]:focus {
background-color: yellow;
}
</code></pre>
<p><a href="http://jsfiddle.net/dbC2u/">Here is a fiddle</a> for the above</p>
<p>What should I do?</p> | 21,279,028 | 3 | 0 | null | 2014-01-22 09:31:41.83 UTC | 2 | 2015-09-02 21:57:47.603 UTC | 2015-09-02 21:57:47.603 UTC | null | 266,531 | null | 1,337,149 | null | 1 | 20 | jquery|html|css | 72,671 | <p>You need to use the in-built <a href="http://api.jquery.com/blur/" rel="noreferrer">blur</a> and <a href="http://api.jquery.com/focus/" rel="noreferrer">focus</a> methods:</p>
<pre><code>$(document).ready(function () {
$('#link').hover(function (){
$('form input[name=email]').blur();
}, function (){
$('form input[name=email]').focus();
});
});
</code></pre> |
38,792,005 | How to change the bootstrap primary color? | <p>Is it possible to change the bootstrap primary color to match to the brand color? I am using bootswatch's paper theme in my case. </p> | 50,253,707 | 17 | 3 | null | 2016-08-05 14:44:19.32 UTC | 34 | 2022-05-14 06:41:48.243 UTC | 2018-05-18 12:26:04.47 UTC | null | 171,456 | null | 644,518 | null | 1 | 140 | css|twitter-bootstrap|twitter-bootstrap-3|bootstrap-4 | 280,047 | <p><strong>Bootstrap 5 (update 2021)</strong></p>
<p>The method is still the same for Bootstrap 5.</p>
<p><a href="https://codeply.com/p/iauLPArGqE" rel="noreferrer">https://codeply.com/p/iauLPArGqE</a></p>
<p><em><strong>Bootstrap 4</strong></em></p>
<p>To change the <strong>primary</strong>, or <em>any</em> of the <strong>theme colors</strong> in Bootstrap 4 SASS, set the appropriate variables <em>before</em> importing <code>bootstrap.scss</code>. This allows your custom scss to override the !default values...</p>
<pre><code>$primary: purple;
$danger: red;
@import "bootstrap";
</code></pre>
<p>Demo: <a href="https://codeply.com/go/f5OmhIdre3" rel="noreferrer">https://codeply.com/go/f5OmhIdre3</a></p>
<hr>
<p>In some cases, you may want to set a new color from another <em>existing</em> Bootstrap variable. For this @import the functions and variables first so they can be referenced in the customizations...</p>
<pre><code>/* import the necessary Bootstrap files */
@import "bootstrap/functions";
@import "bootstrap/variables";
$theme-colors: (
primary: $purple
);
/* finally, import Bootstrap */
@import "bootstrap";
</code></pre>
<p>Demo: <a href="https://codeply.com/go/lobGxGgfZE" rel="noreferrer">https://codeply.com/go/lobGxGgfZE</a></p>
<hr>
<p>Also see: <a href="https://stackoverflow.com/a/50410667/171456">this answer</a>, <a href="https://stackoverflow.com/questions/8596794/customizing-bootstrap-css-template/50410667#50410667">this answer</a> or <a href="https://stackoverflow.com/a/50973207/171456">changing the button color in (CSS or SASS)</a></p>
<hr>
<p>It's also possible to change the primary color with <strong>CSS only</strong> but it requires a lot of additional CSS since there are many <code>-primary</code> variations (btn-primary, alert-primary, bg-primary, text-primary, table-primary, border-primary, etc...) and some of these classes have slight colors variations on borders, hover, and active states. Therefore, if you must use CSS it's better to use target one component such as changing the <a href="https://stackoverflow.com/a/50973207/171456">primary button color</a>.</p> |
24,857,822 | how to redirect one html page to another using button click event in angularjs | <p>i am using angularjs directive to redirect another html page.i am writing click function inside directive but i am getting page name in alert box not redirect to another html page.</p>
<p>sample.html:</p>
<pre><code><test1>
<button data-ng-click="click('/page.html')">Click</button>
</test1>
</code></pre>
<p>sample.js:</p>
<pre><code>app.directive('test1',['$location', function(location) {
function compile(scope, element, attributes,$location) {
return{
post:function(scope, element, iAttrs,$location) {
scope.click=function(path)
{
alert("click"+path);
$location.path('/path');
};
}
};
}
return({
compile: compile,
restrict: 'AE',
});
}]);
</code></pre>
<p>i want to redirect page.html how to do this please suggest me.
Thanks.</p> | 24,858,007 | 4 | 0 | null | 2014-07-21 04:35:25.113 UTC | 1 | 2017-10-26 06:28:47.813 UTC | 2014-07-21 04:50:29.043 UTC | null | 3,819,122 | null | 3,819,122 | null | 1 | 5 | angularjs|angularjs-directive | 74,912 | <p>In html,</p>
<pre><code><button ng-click="redirect()">Click</button>
</code></pre>
<p>In JS,</p>
<pre><code>$scope.redirect = function(){
window.location = "#/page.html";
}
</code></pre>
<p>Hope it helps.....</p> |
49,840,152 | Angular - "has no exported member 'Observable'" | <p><a href="https://i.stack.imgur.com/BAqe4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BAqe4.png" alt="code"></a></p>
<p><a href="https://i.stack.imgur.com/XLYOx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XLYOx.png" alt="error info"></a></p>
<p><strong>Typescript code:</strong></p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
@Injectable({
providedIn: 'root'
})
export class HeroService {
constructor() { }
getHeroes(): Observable<Hero[]> {
return of(HEROES);
}
}
</code></pre>
<p><strong>error info:</strong></p>
<blockquote>
<p>error TS2307: Cannot find module 'rxjs-compat/Observable'.
node_modules/rxjs/observable/of.d.ts(1,15): error TS2307: Cannot find
module 'rxjs-compat/observable/of'. src/app/hero.service.ts(2,10):
error TS2305: Module
'"F:/angular-tour-of-heroes/node_modules/rxjs/Observable"' has no
exported member 'Observable'. src/app/hero.service.ts(15,12): error
TS2304: Cannot find name 'of'.</p>
</blockquote>
<p><strong><code>package.json</code> file with Angular version:</strong></p>
<p><a href="https://i.stack.imgur.com/58sa4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/58sa4.png" alt="version"></a></p> | 49,840,448 | 16 | 4 | null | 2018-04-15 08:49:31.387 UTC | 39 | 2022-06-03 00:08:31.027 UTC | 2019-02-14 09:14:43.197 UTC | null | 8,718,377 | null | 7,361,800 | null | 1 | 179 | angular|typescript|rxjs|angular6|rxjs6 | 216,258 | <p>I replaced the original code with <code>import { Observable, of } from 'rxjs'</code>, and the problem is solved.</p>
<p><a href="https://i.stack.imgur.com/wwizL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wwizL.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/HKf9Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HKf9Q.png" alt="enter image description here"></a></p> |
2,793,379 | How to declare a variable in SQL Server and use it in the same Stored Procedure | <p>Im trying to get the value from BrandID in one table and add it to another table. But I can't get it to work. Anybody know how to do it right?</p>
<pre><code>CREATE PROCEDURE AddBrand
AS
DECLARE
@BrandName nvarchar(50),
@CategoryID int,
@BrandID int
SELECT @BrandID = BrandID FROM tblBrand
WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID)
VALUES (@CategoryID, @BrandID)
RETURN
</code></pre> | 2,793,388 | 4 | 0 | null | 2010-05-08 08:10:29.93 UTC | 7 | 2021-04-16 06:40:48.967 UTC | 2010-05-09 20:26:37.12 UTC | null | 164,901 | null | 336,065 | null | 1 | 51 | sql-server|stored-procedures|local-variables | 328,650 | <p>I can see the following issues with that SP, which may or may not relate to your problem:</p>
<ul>
<li>You have an extraneous <code>)</code> after <code>@BrandName</code> in your <code>SELECT</code> (at the end)</li>
<li>You're not setting <code>@CategoryID</code> or <code>@BrandName</code> to anything anywhere (they're local variables, but you don't assign values to them)</li>
</ul>
<p>In a comment you've said that after fixing the <code>)</code> you get the error:</p>
<blockquote>
<p>Procedure AddBrand has no parameters and arguments were supplied.</p>
</blockquote>
<p>That's telling you that you haven't declared any <em>parameters</em> for the SP, but you called it with parameters. Based on your reply about <code>@CategoryID</code>, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:</p>
<pre><code>CREATE PROCEDURE AddBrand
@BrandName nvarchar(50), -- These are the
@CategoryID int -- parameter declarations
AS
BEGIN
DECLARE @BrandID int
SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END
</code></pre>
<p>You would then call this like this:</p>
<pre><code>EXEC AddBrand 'Gucci', 23
</code></pre>
<p>or this:</p>
<pre><code>EXEC AddBrand @BrandName = 'Gucci', @CategoryID = 23
</code></pre>
<p>...assuming the brand name was 'Gucci' and category ID was 23.</p> |
37,941,780 | What is the REST (or CLI) API for logging in to Amazon Cognito user pools | <p><strong><em>How do i make logins happen via Amazon Cognito REST APIs (for user pools) on platforms for which there is no official SDK?</em></strong> - Note that i am asking for user pools - not identity pools. </p>
<hr>
<h1>Synopsis</h1>
<hr>
<p>Amazon cognito provides 3 kinds of logins:</p>
<ul>
<li>federated logins (creates <strong><em>identity pools</em></strong>) - using social connects like FB, Twitter, G+ etc</li>
<li>AWS managed logins (creates <strong><em>user pools</em></strong>) - using Amazon's own managed signup, signin, forgot password, reset password services</li>
<li>developer provided logins (my custom designed authentication service managed by myself)</li>
</ul>
<p><strong><em>I am using the second one (with User Pools)</em></strong></p>
<hr>
<p>Amazon cognito has several SDKs for android, iOS, javascript, Xamarin etc. Cognito also provides REST APIs for building on platforms other than those supported by official SDKs. <strong><em>I am building an app for a different platform</em></strong> and, hence, REST API is my only way as there is no official SDK for my platform. </p>
<p>The Cognito REST API provides various endpoints for '<em>sign up</em>', '<em>forgot password</em>', '<em>confirm verification</em>' etc, but surprisingly, <strong><em>the REST API does not have any endpoint for simple signin / login</em></strong>.</p>
<hr>
<p>From <a href="http://docs.aws.amazon.com/cli/latest/reference/cognito-idp/index.html#cli-aws-cognito-idp" rel="noreferrer">Cognito CLI API docs</a> I have all the OFFICIAL CLI APIs necessary to "<em>signup users</em>", "<em>confirm signups</em>", "<em>change passwords</em>", "<em>verify phone numbers</em>", "<em>forgot passwords</em>" etc. <strong><em>Surprisingly there is no CLI API mentioned for LOGINs.</em></strong> I was hoping there should be some CLI API like "<strong><em><code>$ aws cognito-idp log-in</code></em></strong>" just like there is for "<strong><em><code>$ aws cognito-idp sign-up</code></em></strong>" or for "<strong><em><code>$ aws cognito-idp forgot-password</code></em></strong>" etc.</p>
<hr>
<p>Also from <a href="http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html" rel="noreferrer">this getting started tutorial</a> it talks about "*what should be done with tokens received <strong><em>AFTER</em></strong> successful authentication of a user*". However, it doesn't talk about <strong><em>HOW TO</em></strong> make the successful authentication happen on the first place with Cognito User Pool APIs. Examples are available only for Android, iOS, javascript SDKs. There are no authentication examples available for platforms which do not have SDKs.</p>
<hr>
<p>Hence, <strong><em>How do i make logins happen via Amazon Cognito REST APIs (for user pools) on platforms for which there is no official SDK?</em></strong></p> | 39,050,866 | 8 | 0 | null | 2016-06-21 10:20:37.977 UTC | 14 | 2022-04-11 03:57:40.27 UTC | 2016-06-22 04:39:42.177 UTC | null | 636,762 | null | 636,762 | null | 1 | 44 | api|rest|amazon-web-services|command-line-interface|amazon-cognito | 28,608 | <p><strong><em>Update:</em></strong></p>
<p>As you pointed out in the comments below, the authentication flow is documented here: <a href="http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html" rel="noreferrer">http://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html</a>. This might help to clarify the authentication flow</p>
<p>It is somewhat counter-intuitive, but it does make sense for mobile apps where you don't want to have the user explicitly sign in, but instead carry tokens around for the user. Note that there is an explicit signin (login) API in the AWS Userpools SDK for iOS. I have not used it, but I suppose it is just an alternate client side API to get through the same <code>InitiateAuth()</code> followed by a <code>RespondToAuthChallenge()</code> flow. The iOS signin example is documented here - <a href="http://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-ios-sdk.html#using-amazon-cognito-user-identity-pools-ios-sdk-user-sign-in" rel="noreferrer">IOS SDK Example: Sign in a User</a></p>
<p><strong><em>Original Post:</em></strong></p>
<p>The Cognito User Pools API documentation for initiating auth is <a href="http://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html" rel="noreferrer">available here</a></p>
<p>The way it works becomes clearer if you implement a user pools application in one of the SDK's (I did one in Swift for iOS, it is clarified because the logging of the JSON responses is verbose and you can kind of see what is going on if you look through the log).</p>
<p>But assuming I understand your question: In summary you should <code>InitiateAuth()</code> and the response to that (from the Cognito User Pools server) is a challenge. Then you do <code>RespondToAuthChallenge()</code> (also documented in that API doc) and the response to that is an authentication result - assuming that the password / session / token were accepted. </p>
<p>The combination of those two things is, I believe, what you are calling LOGIN, and it works like a login. In the API's, the way it is set up is that attempts to get user information when the user is unauthenticated kicks off that <code>InitiateAuth()</code> and (in iOS anyway) the API does a callback to the code you write to ask for passwords, and send a <code>RespondToAuthChallenge()</code> request etc.</p> |
28,573,635 | DestinationViewController Segue and UINavigationController swift | <p>So I have a prepareForSegue method like this:</p>
<pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "fromEventTableToAddEvent" {
let addEventViewController: AddEventViewController = segue.destinationViewController as! AddEventViewController
addEventViewController.newTagArray = newTagArray
}
}
</code></pre>
<p>However, at runtime the app crashes and logs spit out this message: </p>
<blockquote>
<p>Could not cast value of type 'UINavigationController'</p>
</blockquote>
<p>The error comes because the addEventController is embedded in a navigation controller, however I'm not sure how I would set up the segue so that the destinationViewController is set to the NavigationController, but also allow me to pass variables in the prepareForSegue method to the addEventController</p>
<p>So how would I do this using Swift?</p>
<p>I extremely appreciate your help and time you may offer in response. It helps alot</p> | 28,573,905 | 2 | 0 | null | 2015-02-18 00:07:59.81 UTC | 11 | 2022-04-27 12:40:40.757 UTC | 2015-06-15 01:09:46.65 UTC | null | 2,792,531 | null | 3,786,510 | null | 1 | 29 | ios|swift|segue | 32,214 | <p>You only need to access the navigation controller's topViewController, which will be the AddEventViewController. Here is the code:</p>
<pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "fromEventTableToAddEvent" {
let nav = segue.destinationViewController as! UINavigationController
let addEventViewController = nav.topViewController as! AddEventViewController
addEventViewController.newTagArray = newTagArray
}
}
</code></pre> |
51,317,371 | React Context API and avoiding re-renders | <p><em>I have updated this with an update at the bottom</em></p>
<p>Is there a way to maintain a monolithic root state (like Redux) with multiple Context API Consumers working on their own part of their Provider value without triggering a re-render on every isolated change?</p>
<p>Having already <a href="https://stackoverflow.com/questions/50817672/does-new-react-context-api-trigger-re-renders">read through this related question</a> and tried some variations to test out some of the insights provided there, I am still confused about how to avoid re-renders.</p>
<p>Complete code is below and online here: <a href="https://codesandbox.io/s/504qzw02nl" rel="noreferrer">https://codesandbox.io/s/504qzw02nl</a></p>
<p>The issue is that according to devtools, every component sees an "update" (a re-render), even though <code>SectionB</code> is the only component that sees any render changes and even though <code>b</code> is the only part of the state tree that changes. I've tried this with functional components and with <code>PureComponent</code> and see the same render thrashing.</p>
<p>Because nothing is being passed as props (at the component level) I can't see how to detect or prevent this. In this case, I am passing the entire app state into the provider, but I've also tried passing in fragments of the state tree and see the same problem. Clearly, I am doing something very wrong.</p>
<pre><code>import React, { Component, createContext } from 'react';
const defaultState = {
a: { x: 1, y: 2, z: 3 },
b: { x: 4, y: 5, z: 6 },
incrementBX: () => { }
};
let Context = createContext(defaultState);
class App extends Component {
constructor(...args) {
super(...args);
this.state = {
...defaultState,
incrementBX: this.incrementBX.bind(this)
}
}
incrementBX() {
let { b } = this.state;
let newB = { ...b, x: b.x + 1 };
this.setState({ b: newB });
}
render() {
return (
<Context.Provider value={this.state}>
<SectionA />
<SectionB />
<SectionC />
</Context.Provider>
);
}
}
export default App;
class SectionA extends Component {
render() {
return (<Context.Consumer>{
({ a }) => <div>{a.x}</div>
}</Context.Consumer>);
}
}
class SectionB extends Component {
render() {
return (<Context.Consumer>{
({ b }) => <div>{b.x}</div>
}</Context.Consumer>);
}
}
class SectionC extends Component {
render() {
return (<Context.Consumer>{
({ incrementBX }) => <button onClick={incrementBX}>Increment a x</button>
}</Context.Consumer>);
}
}
</code></pre>
<hr>
<p>Edit: I understand that there may be <a href="https://github.com/facebook/react-devtools/issues/988" rel="noreferrer">a bug in the way react-devtools</a> detects or displays re-renders. I've <a href="https://codesandbox.io/s/504qzw02nl" rel="noreferrer">expanded on my code above</a> in a way that displays the problem. I now cannot tell if what I am doing is actually causing re-renders or not. Based on what I've read from Dan Abramov, <em>I think</em> I'm using Provider and Consumer correctly, but I cannot definitively tell if that's true. I welcome any insights.</p> | 51,317,400 | 3 | 0 | null | 2018-07-13 03:49:35.1 UTC | 10 | 2021-06-28 07:40:27.183 UTC | 2018-07-14 05:43:31.677 UTC | null | 279,608 | null | 279,608 | null | 1 | 23 | javascript|reactjs|react-redux | 17,318 | <p>To my understanding, the context API is not meant to avoid re-render but is more like Redux. If you wish to avoid re-render, perhaps looks into <code>PureComponent</code> or lifecycle hook <code>shouldComponentUpdate</code>.</p>
<p>Here is a great <a href="http://somebody32.github.io/high-performance-redux/" rel="nofollow noreferrer">link</a> to improve performance, you can apply the same to the context API too</p> |
1,130,351 | GridView bound with Properties of nested class | <p>I have an object map similar to what's listed below. When I try to bind the properties of NestedClass in a GridView I get the error:</p>
<blockquote>
<p>"A field or property with the name 'NestedClass.Name' was not found on the selected data source."</p>
</blockquote>
<p>The GridView is bound to an ObjectDataSource and the ObjectDataSource is bound to a fully populated instance of BoundClass.</p>
<p>Is there any way around this?</p>
<p>Sample classes:</p>
<pre><code>public class BoundClass
{
public string Name { get; set; }
public NestedClass NestedClass { get; set; }
}
public class NestedClass
{
public string Name { get; set; }
}
</code></pre> | 1,195,119 | 2 | 1 | null | 2009-07-15 09:28:37.877 UTC | 2 | 2015-01-11 05:46:25.777 UTC | 2015-01-11 05:46:25.777 UTC | null | 2,895,667 | null | 99,297 | null | 1 | 35 | c#|asp.net|gridview|objectdatasource | 22,621 | <p>Only immediate properties of an instance can be displayed in a BoundField column.</p>
<p>One must instead use DataBinder.Eval in an itemtemplate to access the nested property instead of assigning it to a boundfield.</p>
<p>Example:</p>
<pre><code><asp:TemplateField>
<itemtemplate>
<p><%#DataBinder.Eval(Container.DataItem, "NestedClass.Name")%></p>
</itemtemplate>
</asp:TemplateField>
</code></pre>
<p>Alternatively, you can create a custom class which inherits BoundField and overrides GetValue to use DataBinder.Eval, as described in this blog post:</p>
<p><a href="http://web.archive.org/web/20120121123301/http://iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx" rel="noreferrer">http://web.archive.org/web/20120121123301/http://iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx</a></p> |
2,658,601 | Do cryptographic hash functions reach each possible values, i.e., are they surjective? | <p>Take a commonly used binary hash function - for example, SHA-256. As the name implies, it outputs a 256 bit value.</p>
<p>Let <em>A</em> be the set of all possible 256 bit binary values. <em>A</em> is extremely large, but finite.</p>
<p>Let <em>B</em> be the set of all possible binary values. <em>B</em> is infinite.</p>
<p>Let <em>C</em> be the set of values obtained by running SHA-256 on every member of <em>B</em>. Obviously this can't be done in practice, but I'm guessing we can still do mathematical analysis of it.</p>
<p><strong>My Question:</strong> By necessity, <em>C</em> ⊆ <em>A</em>. But does <em>C</em> = <em>A</em>?</p>
<p>EDIT: As was pointed out by some answers, this is wholly dependent on the has function in question. So, if you know the answer for any particular hash function, please say so!</p> | 2,659,174 | 5 | 6 | null | 2010-04-17 14:06:36.463 UTC | 12 | 2020-02-14 13:17:50.333 UTC | 2020-02-14 13:17:50.333 UTC | null | 1,672,429 | null | 3,044 | null | 1 | 31 | math|hash|cryptography | 4,593 | <p>First, let's point out that SHA-256 does not accept all possible binary strings as input. As defined by <a href="http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf" rel="noreferrer">FIPS 180-3</a>, SHA-256 accepts as input any sequence of bits of length lower than <em>2^64</em> bits (i.e. no more than 18446744073709551615 bits). This is very common; all hash functions are somehow limited in formal input length. One reason is that the notion of security is defined with regards to computational cost; there is a threshold about computational power that any attacker may muster. Inputs beyond a given length would require more than that maximum computational power to simply evaluate the function. In brief, cryptographers are very wary of infinites, because infinites tend to prevent security from being even defined, let alone quantified. So your input set <em>C</em> should be restricted to sequences up to <em>2^64-1</em> bits.</p>
<p>That being said, let's see what is known about hash function surjectivity.</p>
<p>Hash functions try to emulate a <em>random oracle</em>, a conceptual object which selects outputs at random under the only constraint that it "remembers" previous inputs and outputs, and, if given an already seen input, it returns the same output than previously. By definition, a random oracle can be proven surjective only by trying inputs and exhausting the output space. If the output has size <em>n</em> bits, then it is expected that about <em>2^(2n)</em> distinct inputs will be needed to exhaust the output space of size <em>2^n</em>. For <em>n = 256</em>, this means that hashing about <em>2^512</em> messages (e.g. all messages of 512 bits) ought to be enough (on average). SHA-256 accepts inputs very much longer than 512 bits (indeed, it accepts inputs up to 18446744073709551615 bits), so it seems <em>highly plausible</em> that SHA-256 is surjective.</p>
<p><strong>However</strong>, it has not been proven that SHA-256 is surjective, and that is <strong>expected</strong>. As shown above, a surjectivity proof for a random oracle requires an awful lot of computing power, substantially more than mere attacks such as preimages (<em>2^n</em>) and collisions (<em>2^(n/2)</em>). Consequently, a good hash function "should not" allow a property such as surjectivity to be actually proven. It would be very suspicious: security of hash function stems from the intractability of their internal structure, and such an intractability should firmly oppose to any attempt at mathematical analysis.</p>
<p>As a consequence, surjectivity is not formally proven for any decent hash function, and not even for "broken" hash functions such as MD4. It is only "highly suspected" (a random oracle with inputs much longer than the output should be surjective).</p> |
2,732,863 | Check if a method exists | <p>Is there any way I can test if a method exists in Objective-C?</p>
<p>I'm trying to add a guard to see if my object has the method before calling it.</p> | 2,732,882 | 5 | 1 | null | 2010-04-28 20:24:37.983 UTC | 14 | 2016-08-09 09:10:23.37 UTC | 2016-08-09 09:10:23.37 UTC | null | 1,402,846 | null | 166,940 | null | 1 | 115 | objective-c | 49,197 | <pre><code>if ([obj respondsToSelector:@selector(methodName:withEtc:)]) {
[obj methodName:123 withEtc:456];
}
</code></pre> |
2,446,936 | How to select all anchor tags with specific text | <p>Given multiple anchor tags:</p>
<pre><code><a class="myclass" href="...">My Text</a>
</code></pre>
<p>How do I select the anchors matching the class and with some specific text. eg Select all anchors with the class:'myclass' and text:'My Text'</p> | 2,446,947 | 6 | 0 | null | 2010-03-15 12:13:53.517 UTC | 18 | 2016-09-15 15:22:21.433 UTC | 2010-03-15 17:51:09.873 UTC | null | 172,188 | null | 7,793 | null | 1 | 75 | jquery|html|css-selectors | 66,935 | <pre><code>$("a.myclass:contains('My Text')")
</code></pre> |
3,124,844 | What are your favorite global key bindings in emacs ? | <p>Mine are:</p>
<pre><code>(global-set-key [f6] 'compile-buffer)
(global-set-key [f7] 'kmacro-start-macro-or-insert-counter)
(global-set-key [f8] 'kmacro-end-and-call-macro)
(global-set-key [f9] 'call-last-kbd-macro)
(global-set-key [f10] 'name-and-insert-last-kbd-macro)
(global-set-key [f12] 'menu-bar-open) ; originally bound to F10
(global-set-key "\C-cR" 'rename-current-file-or-buffer)
(global-set-key "\C-cD" 'Delete-current-file-or-buffer)
</code></pre>
<p>The <code>name-and-insert-last-keyboard-macro</code> is from <a href="https://stackoverflow.com/questions/3121274/emacs-keystroke-representation-confusion">another Stack Overflow question</a>.</p> | 3,125,243 | 13 | 0 | null | 2010-06-26 17:36:21.63 UTC | 35 | 2013-10-19 02:15:44.133 UTC | 2017-05-23 11:47:14.583 UTC | null | -1 | null | 124,802 | null | 1 | 25 | emacs | 11,640 | <p>I happen to have quite a lot of these:</p>
<pre><code>;; You know, like Readline.
(global-set-key (kbd "C-M-h") 'backward-kill-word)
;; Align your code in a pretty way.
(global-set-key (kbd "C-x \\") 'align-regexp)
;; Perform general cleanup.
(global-set-key (kbd "C-c n") 'cleanup-buffer)
;; Font size
(define-key global-map (kbd "C-+") 'text-scale-increase)
(define-key global-map (kbd "C--") 'text-scale-decrease)
;; Use regex searches by default.
(global-set-key (kbd "C-s") 'isearch-forward-regexp)
(global-set-key (kbd "\C-r") 'isearch-backward-regexp)
(global-set-key (kbd "C-M-s") 'isearch-forward)
(global-set-key (kbd "C-M-r") 'isearch-backward)
;; Jump to a definition in the current file. (This is awesome.)
(global-set-key (kbd "C-x C-i") 'ido-imenu)
;; File finding
(global-set-key (kbd "C-x M-f") 'ido-find-file-other-window)
(global-set-key (kbd "C-x C-M-f") 'find-file-in-project)
(global-set-key (kbd "C-x f") 'recentf-ido-find-file)
(global-set-key (kbd "C-c r") 'bury-buffer)
(global-set-key (kbd "M-`") 'file-cache-minibuffer-complete)
;; Window switching. (C-x o goes to the next window)
(global-set-key (kbd "C-x O") (lambda ()
(interactive)
(other-window -1))) ;; back one
(global-set-key (kbd "C-x C-o") (lambda ()
(interactive)
(other-window 2))) ;; forward two
;; Indentation help
(global-set-key (kbd "C-x ^") 'join-line)
(global-set-key (kbd "C-M-\\") 'indent-region-or-buffer)
;; Start proced in a similar manner to dired
(global-set-key (kbd "C-x p") 'proced)
;; Start eshell or switch to it if it's active.
(global-set-key (kbd "C-x m") 'eshell)
;; Start a new eshell even if one is active.
(global-set-key (kbd "C-x M") (lambda () (interactive) (eshell t)))
;; Start a regular shell if you prefer that.
(global-set-key (kbd "C-x M-m") 'shell)
;; If you want to be able to M-x without meta
(global-set-key (kbd "C-x C-m") 'execute-extended-command)
;; Fetch the contents at a URL, display it raw.
(global-set-key (kbd "C-x C-h") 'view-url)
;; Help should search more than just commands
(global-set-key (kbd "C-h a") 'apropos)
;; Should be able to eval-and-replace anywhere.
(global-set-key (kbd "C-c e") 'eval-and-replace)
;; Magit rules!
(global-set-key (kbd "C-x g") 'magit-status)
;; This is a little hacky since VC doesn't support git add internally
(eval-after-load 'vc
(define-key vc-prefix-map "i" '(lambda () (interactive)
(if (not (eq 'Git (vc-backend buffer-file-name)))
(vc-register)
(shell-command (format "git add %s" buffer-file-name))
(message "Staged changes.")))))
;; Activate occur easily inside isearch
(define-key isearch-mode-map (kbd "C-o")
(lambda () (interactive)
(let ((case-fold-search isearch-case-fold-search))
(occur (if isearch-regexp isearch-string (regexp-quote isearch-string))))))
;; Org
(define-key global-map "\C-cl" 'org-store-link)
(define-key global-map "\C-ca" 'org-agenda)
;; program shortcuts - s stands for windows key(super)
(global-set-key (kbd "s-b") 'browse-url) ;; Browse (W3M)
(global-set-key (kbd "s-f") 'browse-url-firefox) ;; Firefox...
(global-set-key (kbd "s-l") 'linum-mode) ;; show line numbers in buffer
(global-set-key (kbd "s-r") 're-builder) ;; build regular expressions
;; Super + uppercase letter signifies a buffer/file
(global-set-key (kbd "s-S") ;; scratch
(lambda()(interactive)(switch-to-buffer "*scratch*")))
(global-set-key (kbd "s-E") ;; .emacs
(lambda()(interactive)(find-file "~/emacs/dot-emacs.el")))
;; cycle through buffers
(global-set-key (kbd "<C-tab>") 'bury-buffer)
;; use hippie-expand instead of dabbrev
(global-set-key (kbd "M-/") 'hippie-expand)
;; spell check Bulgarian text
(global-set-key (kbd "C-c B")
(lambda()(interactive)
(ispell-change-dictionary "bulgarian")
(flyspell-buffer)))
;; replace buffer-menu with ibuffer
(global-set-key (kbd "C-x C-b") 'ibuffer)
;; interactive text replacement
(global-set-key (kbd "C-c C-r") 'iedit-mode)
;; swap windows
(global-set-key (kbd "C-c s") 'swap-windows)
;; duplicate the current line or region
(global-set-key (kbd "C-c d") 'duplicate-current-line-or-region)
;; rename buffer & visited file
(global-set-key (kbd "C-c r") 'rename-file-and-buffer)
;; open an ansi-term buffer
(global-set-key (kbd "C-x t") 'visit-term-buffer)
;; macros
(global-set-key [f10] 'start-kbd-macro)
(global-set-key [f11] 'end-kbd-macro)
(global-set-key [f12] 'call-last-kbd-macro)
(provide 'bindings-config)
</code></pre>
<p>I actually have an entire Emacs Lisp file dedicated to global keybindings :-)</p> |
25,207,879 | Configuring response timeout in Apache JMeter | <p>I am trying to check if a particular HTTP request's response time is over 30 seconds, and if it is, then mark it as failed and stop the thread. Sometimes I can see response times close to 80 seconds, an no browser is waiting that long for a response from the server.</p>
<p>I found the following three ways to set a timeout value in JMeter, however this confuses me, because there is multiple options and I don't know which one to use, or if there is any difference at all between them.</p>
<p>So here are the options I found that are related to response timeout:</p>
<ol>
<li>Setting Response timeout value in the sampler
<img src="https://i.stack.imgur.com/Ud9dC.png" alt="Method 1" /></li>
<li>Add a Duration assertion</li>
</ol>
<p><img src="https://i.stack.imgur.com/v8FWO.png" alt="Method 2" /><br />
3. Setting timeout in <em>jmeter.properties</em> configuration file. Options I found here:</p>
<ol>
<li><em>os_sampler.poll_for_timeout=x</em></li>
<li><em>http.socket.timeout=x</em></li>
<li><em>httpclient.timeout=x</em></li>
</ol>
<p>So, the problem is that I don't know where to set the response timeout from the listed options. Is there any difference at all between these options?
<strong>So what I would like to see as a result: If a particular HTTP request takes more than 30 seconds to get a response from the server, stop waiting for a response and mark it as a failed request.</strong></p> | 25,210,857 | 2 | 0 | null | 2014-08-08 16:19:51.263 UTC | 8 | 2021-05-28 09:42:04.627 UTC | 2021-05-17 14:04:20.667 UTC | null | 342,862 | null | 342,862 | null | 1 | 30 | timeout|jmeter|httpresponse|load-testing|performance-testing | 56,695 | <p>For your need, an assertion is not the right solution as it will only mark the request as failed but it will wait.</p>
<p>The right option is a response timeout.</p>
<p>Regarding the 3rd point </p>
<ol>
<li><p>os_sampler.poll_for_timeout=x => not for http, see:</p>
<ul>
<li><a href="https://github.com/apache/jmeter/blob/master/bin/jmeter.properties" rel="noreferrer">https://github.com/apache/jmeter/blob/master/bin/jmeter.properties</a> </li>
</ul></li>
<li><p>http.socket.timeout=x => applies to all requests using HttpClient4 or 3, see:</p>
<ul>
<li><a href="https://github.com/apache/jmeter/blob/master/bin/hc.parameters" rel="noreferrer">https://github.com/apache/jmeter/blob/master/bin/hc.parameters</a></li>
</ul></li>
<li><p>httpclient.timeout=x => Same, see:</p>
<ul>
<li><a href="https://github.com/apache/jmeter/blob/master/bin/jmeter.properties" rel="noreferrer">https://github.com/apache/jmeter/blob/master/bin/jmeter.properties</a></li>
</ul></li>
</ol>
<p>I think the best option is to use 1. , if you want those values to apply to all requests, just use Http Request Defaults element:</p>
<ul>
<li><a href="https://jmeter.apache.org/usermanual/component_reference.html#HTTP_Request_Defaults" rel="noreferrer">https://jmeter.apache.org/usermanual/component_reference.html#HTTP_Request_Defaults</a></li>
</ul>
<p><a href="https://i.stack.imgur.com/FlvNr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FlvNr.png" alt="HTTP Request Defaults"></a></p>
<p>If you're looking to learn jmeter correctly, this <a href="https://leanpub.com/master-jmeter-from-load-test-to-devops" rel="noreferrer">book</a> will help you.</p> |
42,468,245 | Driver [] is not supported. - Laravel 5.3 | <p>I'm using <a href="https://backpackforlaravel.com/" rel="noreferrer">backpackforlaravel</a> to set up the backend area of my website. I've added an image field in my <strong>ProjectCrudController</strong>:</p>
<pre><code>$this->crud->addField([
'label' => "Project Image",
'name' => "image",
'type' => 'image',
'upload' => true,
], 'both');
</code></pre>
<p>In my Model <strong>Project</strong> I have a <strong>mutator</strong> like this:</p>
<pre><code>public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "public_folder";
$destination_path = "uploads/images";
// if the image was erased
if ($value==null) {
// delete the image from disk
\Storage::disk($disk)->delete($this->image);
// set null in the database column
$this->attributes[$attribute_name] = null;
}
// if a base64 was sent, store it in the db
if (starts_with($value, 'data:image'))
{
// 0. Make the image
$image = \Image::make($value);
// 1. Generate a filename.
$filename = md5($value.time()).'.jpg';
// 2. Store the image on disk.
\Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
// 3. Save the path to the database
$this->attributes[$attribute_name] = $destination_path.'/'.$filename;
}
}
</code></pre>
<p>In my <strong>public</strong> folder I have <strong>/uploads/images/</strong> folder.</p>
<p>But when I want to save a Project I'm getting the following error:</p>
<blockquote>
<p>InvalidArgumentException in FilesystemManager.php line 121:</p>
<p>Driver [] is not supported.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/ae2gF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ae2gF.png" alt="enter image description here" /></a></p>
<p>My <strong>filesystems.php file</strong> in my <strong>config</strong> folder looks like this:</p>
<pre><code><?php
return [
'default' => 'local',
'cloud' => 's3',
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => 'your-key',
'secret' => 'your-secret',
'region' => 'your-region',
'bucket' => 'your-bucket',
],
'uploads' => [
'driver' => 'local',
'root' => public_path('uploads'),
],
],
'storage' => [
'driver' => 'local',
'root' => storage_path(),
],
];
</code></pre>
<p>What could be the problem here? I'm using <strong>Laravel Homestead version 2.2.2</strong>.</p> | 42,468,355 | 1 | 0 | null | 2017-02-26 12:05:09.803 UTC | 1 | 2017-12-26 12:56:12.517 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,775,531 | null | 1 | 17 | php|image|laravel|laravel-5.3|laravel-backpack | 51,152 | <p>Here you defined the <code>$disk</code> as <code>public_folder</code>:</p>
<pre><code>public function setImageAttribute($value)
{
$attribute_name = "image";
$disk = "public_folder";
$destination_path = "uploads/images";
</code></pre>
<p>But in your filesystem.php you don't have the public_folder disk</p>
<p>You need to create a new "public_folder" disk</p>
<pre><code>'disks' => [
'public_folder' => [
'driver' => 'local',
'root' => public_path('uploads'),
],
</code></pre>
<p>or rename your <code>$disk</code> variable to another disk:</p>
<pre><code>public function setImageAttribute($value)
{
$attribute_name = "image";
//Uploads disk for example
$disk = "uploads";
</code></pre> |
40,256,658 | Getting an object array from an Angular service | <p>I am new to Angular (and Javascript for that matter). I've written an Angular service which returns an array of users. The data is retrieved from an HTTP call which returns the data in JSON format. When logging the JSON data returned from the HTTP call, I can see that this call is successful and the correct data is returned. I have a component which calls the service to get the users and an HTML page which displays the users. I cannot get the data from the service to the component. I suspect I am using the Observable incorrectly. Maybe I'm using subscribe incorrectly as well. If I comment out the getUsers call in the ngInit function and uncomment the getUsersMock call, everything works fine and I see the data displayed in the listbox in the HTML page. I'd like to convert the JSON data to an array or list of Users in the service, rather then returning JSON from the service and having the component convert it.</p>
<p>Data returned from HTTP call to get users:</p>
<pre><code>[
{
"firstName": "Jane",
"lastName": "Doe"
},
{
"firstName": "John",
"lastName": "Doe"
}
]
</code></pre>
<p>user.ts</p>
<pre><code>export class User {
firstName: string;
lastName: string;
}
</code></pre>
<p>user-service.ts</p>
<pre><code>...
@Injectable
export class UserService {
private USERS: User[] = [
{
firstName: 'Jane',
lastName: 'Doe'
},
{
firstName: 'John',
lastName: 'Doe'
}
];
constructor (private http: Http) {}
getUsersMock(): User[] {
return this.USERS;
}
getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
...
</code></pre>
<p>user.component.ts</p>
<pre><code>...
export class UserComponent implements OnInit {
users: User[] = {};
constructor(private userService: UserService) {}
ngOnInit(): void {
this.getUsers();
//this.getUsersMock();
}
getUsers(): void {
var userObservable = this.userService.getUsers();
this.userObservable.subscribe(users => { this.users = users });
}
getUsersMock(): void {
this.users = this.userService.getUsersMock();
}
}
...
</code></pre>
<p>user.component.html</p>
<pre><code>...
<select disabled="disabled" name="Users" size="20">
<option *ngFor="let user of users">
{{user.firstName}}, {{user.lastName}}
</option>
</select>
...
</code></pre>
<p>!!! UPDATE !!!</p>
<p>I had been reading the "heroes" tutorial, but wasn't working for me so I went off and tried other things. I've re-implemented my code the way the heroes tutorial describes. However, when I log the value of this.users, it reports undefined.</p>
<p>Here is my revised user-service.ts</p>
<pre><code>...
@Injectable
export class UserService {
private USERS: User[] = [
{
firstName: 'Jane',
lastName: 'Doe'
},
{
firstName: 'John',
lastName: 'Doe'
}
];
constructor (private http: Http) {}
getUsersMock(): User[] {
return this.USERS;
}
getUsers(): Promise<User[]> {
return this.http.get('http://users.org')
.toPromise()
.then(response => response.json().data as User[])
.catch(this.handleError);
}
...
</code></pre>
<p>Here is my revised user.component.ts</p>
<pre><code>...
export class UserComponent implements OnInit {
users: User[] = {};
constructor(private userService: UserService) {}
ngOnInit(): void {
this.getUsers();
//this.getUsersMock();
}
getUsers(): void {
this.userService.getUsers()
.then(users => this.users = users);
console.log('this.users=' + this.users); // logs undefined
}
getUsersMock(): void {
this.users = this.userService.getUsersMock();
}
}
...
</code></pre>
<p>!!!!!!!!!! FINAL WORKING SOLUTION !!!!!!!!!!
This is all the files for the final working solution:</p>
<p>user.ts</p>
<pre><code>export class User {
public firstName: string;
}
</code></pre>
<p>user.service.ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { User } from './user';
@Injectable()
export class UserService {
// Returns this JSON data:
// [{"firstName":"Jane"},{"firstName":"John"}]
private URL = 'http://users.org';
constructor (private http: Http) {}
getUsers(): Observable<User[]> {
return this.http.get(this.URL)
.map((response:Response) => response.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}
</code></pre>
<p>user.component.ts</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from './user';
import { UserService } from './user.service';
@Component({
moduleId: module.id,
selector: 'users-list',
template: `
<select size="5">
<option *ngFor="let user of users">{{user.firstName}}</option>
</select>
`
})
export class UserComponent implements OnInit{
users: User[];
title = 'List Users';
constructor(private userService: UserService) {}
getUsers(): void {
this.userService.getUsers()
.subscribe(
users => {
this.users = users;
console.log('this.users=' + this.users);
console.log('this.users.length=' + this.users.length);
console.log('this.users[0].firstName=' + this.users[0].firstName);
}, //Bind to view
err => {
// Log errors if any
console.log(err);
})
}
ngOnInit(): void {
this.getUsers();
}
}
</code></pre> | 40,256,746 | 1 | 0 | null | 2016-10-26 07:54:19.39 UTC | 16 | 2019-05-26 08:07:39.73 UTC | 2018-02-06 12:31:49.283 UTC | null | 5,394,220 | null | 3,182,914 | null | 1 | 26 | arrays|json|angular|rxjs|angular2-http | 158,891 | <p>Take a look at your code :</p>
<pre><code> getUsers(): Observable<User[]> {
return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json();
})
}
</code></pre>
<p>and code from <a href="https://angular.io/docs/ts/latest/tutorial/toh-pt6.html" rel="noreferrer">https://angular.io/docs/ts/latest/tutorial/toh-pt6.html</a>
(BTW. really good tutorial, you should check it out)</p>
<pre><code> getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
</code></pre>
<p>The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:</p>
<pre><code> return Observable.create(observer => {
this.http.get('http://users.org').map(response => response.json()
</code></pre>
<p>Try to follow the guide in link that I provided. You should be just fine when you study it carefully.</p>
<p>---EDIT----</p>
<p>First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!</p>
<p>Try to do it like this: </p>
<pre><code> getUsers(): void {
this.userService.getUsers()
.then(users => {
this.users = users
console.log('this.users=' + this.users);
});
}
</code></pre>
<p><strong>See where the console.log(...) is!</strong></p>
<p>Try to resign from toPromise() it's seems to be just for ppl with no RxJs background. </p>
<p>Catch another link: <a href="https://scotch.io/tutorials/angular-2-http-requests-with-observables" rel="noreferrer">https://scotch.io/tutorials/angular-2-http-requests-with-observables</a> Build your service once again with RxJs observables.</p> |
40,036,374 | How to use / include fabricjs in Angular2 | <p>I want use fabricjs in my project. I installed fabricjs using bower and linked in index.html. but it is not working. Please see the below code.</p>
<p>index.html</p>
<pre><code><html>
<head>
<script>document.write('<base href="' + document.location + '" />'); </script>
<title>Image Editor</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap/dist/css/bootstrap.min.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="libs/core-js/client/shim.min.js"></script>
<script src="libs/zone.js/dist/zone.js"></script>
<script src="libs/reflect-metadata/Reflect.js"></script>
<script src="libs/systemjs/dist/system.src.js"></script>
<script src="css/jquery/dist/jquery.min.js"></script>
<script src="css/bootstrap/dist/js/bootstrap.min.js"></script>
// incuding fabricjs here
<script src="../../bower_components/fabric.js/dist/fabric.min.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
</code></pre>
<p>This is component file "stage.component.ts"</p>
<pre><code>import {Component, OnInit} from '@angular/core';
import { ActivatedRoute, Router} from '@angular/router';
import { fabric } from 'fabric';
import { ImageService } from '../services/image.service';
declare var fabric:any;
@Component({
selector:'my-stage',
styleUrls: ['./app/stage/stage.component.css'],
templateUrl: './app/stage/stage.component.html',
})
export class StageComponent implements OnInit {
title:string = 'Image Editor';
imgpath: string = '';
canvas:any = null;
// fabric:any = null;
constructor(
private route: ActivatedRoute,
) {
// this.fabric = new fabric();
}
ngOnInit() {
this.canvas = new fabric.Canvas('fstage', {
isDrawingMode: true,
selection: true
});
}
}
</code></pre>
<p>I have search many reference but couldn't find out what is wrong with my. Please advice, thank you.</p> | 40,750,232 | 5 | 0 | null | 2016-10-14 06:29:47.873 UTC | 13 | 2018-03-25 22:45:11.817 UTC | null | null | null | null | 2,024,758 | null | 1 | 11 | javascript|angular|typescript|fabricjs | 10,189 | <p>I can use fabric.js without the line </p>
<blockquote>
<p>import { fabric } from 'fabric';</p>
</blockquote>
<p>loading the script on index.html and declaring the library on the ts file:</p>
<pre><code>import { Component } from '@angular/core';
declare var fabric: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
printValue() {
console.log(fabric.version);
};
}
</code></pre>
<p>Out on browser console:</p>
<pre><code>1.6.7 app.component.ts:13
</code></pre> |
10,356,005 | Is BDD really applicable at the UI layer? | <p>BDD is an <strong>"outside-in"</strong> methodology, which as I understand it, means you start with what you know. You write your stories and scenarios, and then implement the outermost domain objects, moving "inwards" and "deliberately" discovering collaborators as you go--down through service layers, domain layers, etc. For a collaborator that doesn't exist yet, you mock it (or "fake it") until you make it. (I'm stealing some of these terms straight from Dan North and Kent Beck).</p>
<p>So, how does a UI fit into this?</p>
<p>Borrowing from one of North's <a href="http://dannorth.net/2011/01/31/whose-domain-is-it-anyway/" rel="noreferrer">blog entries</a>, he rewrites this:</p>
<pre><code>Given an unauthenticated user
When the user tries to navigate to the welcome page
Then they should be redirected to the login page
When the user enters a valid name in the Name field
And the user enters the corresponding password in the Password field
And the user presses the Login button
Then they should be directed to the welcome page
</code></pre>
<p>into this:</p>
<pre><code>Given an unauthenticated user
When the user tries to access a restricted asset
Then they should be directed to a login page
When the user submits valid credentials
Then they should be redirected back to the restricted content
</code></pre>
<p>He does this to eliminate language from non-relevant domains, one of which is the UI (<em>"Name field", "Password field", "Login button"</em>). Now the UI can change and the story (or rather, the story's <em>intent</em>) doesn't break.</p>
<p>So when I write the implementation for this story, do I use the UI or not? Is it better to fire up a browser and execute "the user submits valid credentials" via a Selenium test, or to connect to the underlying implementation directly (such as an authentication service)? BTW, I'm using <a href="http://jbehave.org/" rel="noreferrer">jBehave</a> as my BDD framework, but it could just as easily be Cucumber, rSpec, or a number of others.</p>
<p>I tend not to test UI in an automated fashion, and I'm cautious of GUI automation tools like Selenium because I think the tests (1) can be overly brittle and (2) get run where the cost of execution is the greatest. So my inclination is to manually test the UI for aesthetics and usability and leave the business logic to lower, more easily automatible layers. (And possibly layers less likely to change.)</p>
<p>But I'm open to being converted on this. So, is BDD for UI or not?</p>
<p>PS. I have read all the posts on SO I could find on this topic, and none really address my question. <a href="https://stackoverflow.com/questions/7899731/should-your-bdd-specifications-be-separated-from-your-ui-tests">This one</a> gets closest, but I'm not talking about separating the UI into a separate story; rather, I'm talking about ignoring it entirely for the purposes of BDD.</p> | 10,356,139 | 3 | 0 | null | 2012-04-27 18:35:09.947 UTC | 18 | 2019-01-21 08:10:50.997 UTC | 2017-05-23 12:31:55.553 UTC | null | -1 | null | 1,272,885 | null | 1 | 24 | testing|bdd | 8,589 | <p>Most people who use automated BDD tools use it at the UI layer. I've seen a few teams take it to the next layer down - the controller or presenter layer - because their UI changes too frequently. One team automated from the UI on their customer-facing site and from the controller on the admin site, since if something was broken they could easily fix it.</p>
<p>Mostly BDD is designed to help you have clear, unambiguous conversations with your stakeholders (or to help you discover the places where ambiguity still exists!) and carry the language into the code. The conversations are much more important than the tools.</p>
<p>If you use the language that the business use when writing your steps, and keep them at a high level as Dan suggests, they should be far less brittle and more easily maintainable. These scenarios aren't really tests; they're examples of how you're going to use the system, which you can use in conversation, and which give you tests as a nice by-product. Having the conversations around the examples is more important than the automation, whichever level you do it at.</p>
<p>I'd say, if your UI is stable, give automation a try, and if it doesn't work for you, either drop to a lower level or ensure you've got sufficient manual testing. If you're testing aesthetics anyway that will help (and never, ever use automation to test aesthetics!) If your UI is not stable, don't automate it - you're just adding commitment to something that you know is probably going to change, and automation in that case will make it harder.</p> |
10,825,879 | How can a variable-height sticky footer be defined in pure CSS? | <p>The key to note here is the height of the footer is not going to be fixed, but will vary with its content.</p>
<p>When I say “sticky footer,” I use it in what I understand to be the common definition of “a footer that is never higher than the bottom of the viewport, but if there is enough content, it will be hidden until the user scrolls down far enough to see it.”</p>
<p>Note also I don’t need to support legacy browsers. If CSS <code>display: table</code> & related properties help here, they are fair game.</p> | 26,558,049 | 3 | 0 | null | 2012-05-31 00:04:14.063 UTC | 23 | 2019-09-08 16:35:44.657 UTC | null | null | null | null | 211,327 | null | 1 | 48 | css | 26,219 | <p>All other solutions here are out of date and either use JavaScript, or <code>table</code> hacks.</p>
<p>With the advent of the <a href="http://philipwalton.github.io/solved-by-flexbox/" rel="noreferrer">CSS flex model</a>, solving the variable-height sticky footer problem becomes very, very easy: while mostly known for laying out content in the horizontal direction, Flexbox actually works just as well for vertical layout problems. All you have to do is wrap the vertical sections in a flex container and choose which ones you want to expand. They'll automatically take up all the available space in their container.</p>
<p>Note how simple the markup and the CSS are. No table hacks or anything.</p>
<p>The flex model is <a href="http://caniuse.com/#search=flex" rel="noreferrer">supported by 96%+ of the browsers</a> in use today.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
height: 100%;
margin: 0; padding: 0; /* to avoid scrollbars */
}
#wrapper {
display: flex; /* use the flex model */
min-height: 100%;
flex-direction: column; /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}
#header {
background: yellow;
height: 100px; /* can be variable as well */
}
#body {
flex: 1;
border: 1px solid red;
}
#footer{
background: lime;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wrapper">
<div id="header">Title</div>
<div id="body">Body</div>
<div id="footer">
Footer<br/>
of<br/>
variable<br/>
height<br/>
</div>
</div></code></pre>
</div>
</div>
</p> |
10,390,041 | Node.js - Using the async lib - async.foreach with object | <p>I am using the <em>node async</em> lib - <a href="https://github.com/caolan/async#forEach" rel="noreferrer">https://github.com/caolan/async#forEach</a> and would like to iterate through an object and print out its index key. Once complete I would like execute a callback.</p>
<p>Here is what I have so far but the <code>'iterating done'</code> is never seen: </p>
<pre><code> async.forEach(Object.keys(dataObj), function (err, callback){
console.log('*****');
}, function() {
console.log('iterating done');
});
</code></pre>
<ol>
<li><p>Why does the final function not get called?</p></li>
<li><p>How can I print the object index key?</p></li>
</ol> | 10,390,318 | 2 | 0 | null | 2012-04-30 20:19:53.833 UTC | 19 | 2017-04-23 18:32:32.983 UTC | 2015-03-10 13:19:10.68 UTC | null | 526,704 | null | 702,644 | null | 1 | 53 | node.js|loops|object|asynchronous|node-async | 75,634 | <p>The final function does not get called because <code>async.forEach</code> requires that you call the <code>callback</code> function for every element.</p>
<p>Use something like this:</p>
<pre><code>async.forEach(Object.keys(dataObj), function (item, callback){
console.log(item); // print the key
// tell async that that particular element of the iterator is done
callback();
}, function(err) {
console.log('iterating done');
});
</code></pre> |
10,854,156 | How to create variables for use in Xcode build settings values? | <p>XCode has a number of built-in variables that are used for convenience in Build Settings, for example <code>"$(PRODUCT_NAME)"</code> or <code>"$(CURRENT_ARCH)"</code>.</p>
<p>Can I define my own variables? How / where?</p> | 18,472,235 | 4 | 0 | null | 2012-06-01 16:34:06.293 UTC | 16 | 2019-04-21 10:01:03.783 UTC | 2013-11-12 16:24:50.64 UTC | null | 449,161 | null | 449,161 | null | 1 | 55 | xcode4|xcode5 | 40,224 | <p>In XCode 5 this has changed slightly.</p>
<ol>
<li>Select the project or target in the left side of the editor</li>
<li>Go to the Editor menu in the top menu bar</li>
<li>Select "Add Build Setting" and then "Add User-Defined Build Setting"</li>
</ol>
<p><img src="https://i.stack.imgur.com/FsVcm.png" alt="enter image description here"></p> |
30,764,266 | Generate the JPA metamodel files using maven-processor-plugin - What is a convenient way for re-generation? | <p>I am trying to use maven-processor-plugin for generating JPA metamodel java files and I set up my pom.xml as belows. </p>
<pre><code><plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<!-- source output directory -->
<outputDirectory>${basedir}/src/main/java</outputDirectory>
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
</plugin>
</code></pre>
<p>Actually, I want to generate metamodel files (Entity_.java) to the same packages of their corresponding entities (Entity.java). Hence, I set up outputDirectory in the plugin as </p>
<pre><code><outputDirectory>${basedir}/src/main/java</outputDirectory>
</code></pre>
<p>The first time of running is ok, but from later times when performing the metamodel java files re-generation, the plugin always turns out an error about file duplication.</p>
<p>My Question is
- Is there any way to config the plugin so that it could overwrite the existing files during re-generation?</p>
<p>In fact, to work around</p>
<ol>
<li>I must delete all generated files before any re-generation.</li>
<li>I could point the outputDirectory to a different folder in /target, this location will be clean everytime Maven run, but this
leads to manually copy generated metamodel files to source folder
for update after re-generation.</li>
</ol>
<p>Both of these are very inconvenient and I hope you guys could show me a proper solution.</p> | 30,773,569 | 4 | 0 | null | 2015-06-10 18:17:54.51 UTC | 9 | 2021-01-18 11:47:08.51 UTC | null | null | null | null | 3,946,410 | null | 1 | 10 | hibernate|maven|jpa | 19,353 | <p>The proper solution is that generated sources should be in the target folder and shouldn't be put into the source-folders nor your SCM system. </p>
<p>Of course, by putting your generated sources into target, you would face the problem within your IDE because the related code can't be found. Therefore you can add the build-helper-maven-plugin to dynamically add the folder from the target directory. </p>
<pre><code><plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<!-- source output directory -->
<outputDirectory>${project.build.directory}/generated-sources/java/jpametamodel</outputDirectory>
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
<overwrite>true</overwrite>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/java/jpametamodel</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</code></pre> |
21,329,662 | Explanation of Red-Black tree based implementation of TreeMap in JAVA | <p>I was going through the source code of <strong>TreeMap</strong> in <strong>JAVA</strong>.
As per JAVA doc:</p>
<blockquote>
<p>A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.</p>
<p>This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.</p>
</blockquote>
<p>In the source code I found that an Inner Class <strong>Entry</strong> was used as a <strong>node</strong>.</p>
<pre><code>static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left = null;
Entry<K,V> right = null;
Entry<K,V> parent;
boolean color = BLACK;
....
</code></pre>
<p>As for the defination of <strong>Red-Black tree</strong>. From Wikipedia I found:</p>
<blockquote>
<p>A red–black tree is a type of self-balancing binary search tree, a data structure used in computer science.</p>
<p>The self-balancing is provided by painting each node with one of two colors (these are typically called 'red' and 'black', hence the name of the trees) in such a way that the resulting painted tree satisfies certain properties that don't allow it to become significantly unbalanced. When the tree is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The properties are designed in such a way that this rearranging and recoloring can be performed efficiently.</p>
</blockquote>
<p>I tried to analyse the souce code but couldn't understand the following:</p>
<ol>
<li><p>Suppose I am already having two keys "C" and "E" in the Tree and then I am adding "D". How the nodes will be arranged (Using natural ordering).</p>
</li>
<li><p>How is self-balancing of Tree is implemented in the java source code.</p>
</li>
</ol>
<p>I tried searching for detail implementationof TreeMap but was unable to find any article such as the <a href="http://howtodoinjava.com/2012/10/09/how-hashmap-works-in-java/" rel="noreferrer">following article</a> I have found for HashMap</p>
<p>Since yesterday I am hanging on this Tree :( Can someone please help me get down...</p> | 21,331,561 | 1 | 1 | null | 2014-01-24 10:01:28.157 UTC | 14 | 2016-02-08 18:07:23.77 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,032,823 | null | 1 | 31 | java|treemap|red-black-tree | 22,631 | <ol>
<li><p>The goal of the <code>TreeMap</code> is to have a tree of keys where keys that are lower than the parent's key are to the left and keys higher than the parent's key are to the right. So, if you add <code>C</code>, then <code>E</code>, you will have this tree:</p>
<pre><code>C
\
E
</code></pre>
<p>If you then add <code>D</code>, initially you will have:</p>
<pre><code>C
\
E
/
D
</code></pre>
<p>But this tree is unbalanced and therefore searches would be slower. So, the tree is rebalanced. After balancing, the tree now becomes much more efficient:</p>
<pre><code>C C
\ rotate \ rotate D
E --- right ---> D --- left ---> / \
/ around \ around C E
D E E D
</code></pre></li>
<li><p>Rebalancing takes place inside the <code>fixAfterInsertion()</code> method, which checks whether the <em>red-black properties</em> of the tree are still maintained after insertion. And, if it doesn't, then it rebalances the tree performing either <code>rotateLeft()</code> or <code>rotateRight()</code> on the offending branch to restore the balance. Then it moves up the tree and checks the balance and so on until it reaches the root node.</p></li>
</ol>
<p>There are several resources around the internet that explain Red-Black Trees in depth. But, I think the best way of understanding the process is following an animated tutorial like this: <a href="http://www.csanimated.com/animation.php?t=Red-black_tree">http://www.csanimated.com/animation.php?t=Red-black_tree</a></p>
<p>There is nothing peculiar in the <code>TreeMap</code> implementation of RBT. It closely follows the pseudocode given in CLRS's (Cormen, Leiserson, Rivest and Stein) book, which is what 99% of the implementations around do.</p> |
21,750,804 | Bower calls blocked by corporate proxy | <p>I'm trying to use Bower for a web app, but find myself hitting some sort of proxy issues:</p>
<pre><code>D:\>bower search jquery
bower retry Request to https://bower.herokuapp.com/packages/search/jquery failed with ECONNRESET, retrying in 1.2s
bower retry Request to https://bower.herokuapp.com/packages/search/jquery failed with ECONNRESET, retrying in 2.5s
bower retry Request to https://bower.herokuapp.com/packages/search/jquery failed with ECONNRESET, retrying in 6.8s
bower retry Request to https://bower.herokuapp.com/packages/search/jquery failed with ECONNRESET, retrying in 15.1s
bower retry Request to https://bower.herokuapp.com/packages/search/jquery failed with ECONNRESET, retrying in 20.3s
bower ECONNRESET Request to https://bower.herokuapp.com/packages/search/jquery failed: tunneling socket could not be established, cause=Parse Error
</code></pre>
<p>Relevant points:</p>
<ul>
<li>I can browse to <a href="https://bower.herokuapp.com/packages/search/jquery">https://bower.herokuapp.com/packages/search/jquery</a> and it returns a full json response.</li>
<li>I can use git to clone, both using the git:// protocol and http(s).</li>
<li>I can use NPM directly without these issues</li>
<li>I've tried using Fiddler to determine what's being blocked, but it doesn't detect any calls from the Bower command. I can see calls from NPM commands in Fiddler.</li>
<li>I've searched the Bower issues list, seen similar issues, but they either have no solution or it doesn't seem quite the same as mine.</li>
</ul>
<p>Any ideas?</p> | 23,288,312 | 16 | 0 | null | 2014-02-13 09:58:06.47 UTC | 25 | 2018-10-31 14:29:03.91 UTC | 2015-04-01 07:57:09.413 UTC | null | 377,369 | null | 96,521 | null | 1 | 78 | proxy|bower | 86,676 | <p>Thanks @user3259967</p>
<p>This did the job.</p>
<p>I would like to add that if you are behind a proxy that needs to be authenticated, you can add the username/password to your <strong>.bowerrc</strong> file.</p>
<pre><code>{
"directory": "library",
"registry": "http://bower.herokuapp.com",
"proxy":"http://<USERNAME>:<PASSWORD>@<PROXY_IP>:<PROXY_PORT>/",
"https-proxy":"http://<USERNAME>:<PASSWORD>@<PROXY_IP>:<PROXY_PORT>/"
}
</code></pre>
<p>NOTICE the use of <strong>http://</strong> in <strong>https-proxy</strong> </p> |
55,861,077 | Hackerrank Lists Problem ~ Standard test case works but others don't | <p>Consider a list (list = []). You can perform the following commands:</p>
<pre><code>insert i e: Insert integer e at position .
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
</code></pre>
<p>Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.</p>
<p>Sample Input:</p>
<pre><code>12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
</code></pre>
<p>My Code:</p>
<pre><code>import sys
if __name__ == '__main__':
N = int(input())
my_list = []
inputs = []
for line in sys.stdin:
inputs.append(line)
for item in inputs:
if item[0:5] == 'print':
print(my_list)
elif item[0:2] == 'in':
inserts = [s for s in item.split()][1:3]
inserts = list(map(int, inserts))
my_list.insert(inserts[0], inserts[1])
elif item[0:3] == 'rem':
inserts = list(map(int, [s for s in item.split()][1]))
my_list.remove(inserts[0])
elif item[0:2] == 'ap':
inserts = list(map(int, [s for s in item.split()][1]))
my_list.append(inserts[0])
elif item[0:4] == 'sort':
my_list.sort()
elif item[0:3] == 'pop':
my_list.pop()
elif item[0:7] == 'reverse':
my_list.reverse()
</code></pre>
<p>I'm not sure as to why my code is not getting approved upon submission. In this test case they provided, my code passes.
The expected output is the following:</p>
<pre><code>[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
</code></pre>
<p>Thanks so much for the help!</p> | 55,876,454 | 12 | 2 | null | 2019-04-26 05:03:14.483 UTC | 2 | 2021-06-20 17:43:45.223 UTC | null | null | null | null | 11,235,813 | null | 1 | 2 | python-3.x|list | 39,915 | <p>Your problem is that your append code has a bug when the number to be appended has more than one digit. In your code here</p>
<pre><code>inserts = list(map(int, [s for s in item.split()][1]))
my_list.append(inserts[0])
</code></pre>
<p>for example if the "item" command was "append 12", <code>[s for s in item.split()][1]</code> would be the string "12", so <code>list(map(int, [s for s in item.split()][1]))</code> is mapping each character in that string to an integer, giving you [1, 2] rather than [12], and therefore <code>my_list.append(inserts[0])</code> would be appending the number 1 instead of 12. So fix that and you will fix your problem.</p> |
25,701,979 | Xcode 6 beta 7: storyboard adds extra space on right and left sides | <p>When I add subview to root ViewController's view, and with auto layout setup leadingSpace,trailingSpace,topSpace and bottomSpace to zero, there are appear some extra spaces on left and right sides (so if I print subview's frame its origin will be 16 and size less on 32 than should be).
So actually we get that leading and trailing spaces are not zeros...</p>
<p><img src="https://i.stack.imgur.com/zp0T3.png" alt="enter image description here"></p>
<p>As you can see on picture leading space - zero, but origin.x = 16</p>
<p>Earlier I wasn't working hard with auto layout, so my question is:
Is it a bug of new Xcode or a feature?</p>
<p>P.S. All frames and constraints updated.</p> | 25,702,356 | 1 | 0 | null | 2014-09-06 15:50:37.357 UTC | 16 | 2019-12-26 17:10:55.533 UTC | 2019-12-26 17:10:55.533 UTC | null | 1,033,581 | null | 1,585,840 | null | 1 | 43 | ios|storyboard|autolayout|uistoryboard|xcode6 | 11,934 | <p>iOS 8 adds the concept of <a href="https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/doc/uid/TP40006816-CH3-SW236">“content margins”</a> to <code>UIView</code>. The <a href="https://developer.apple.com/videos/wwdc/2014/?id=202">“What's New in Cocoa Touch” video from WWDC 2014</a> discusses content margins (under the title “Adaptive Margins”) starting at about 12m30s.</p>
<p>The default margins are 8 points on each side. Each end of a layout constraint can be relative to a view's margin instead of to the view's true edge (use File > Open Quickly to go to the definition of <code>NSLayoutAttribute</code> to see the possibilities).</p>
<p>Your constraint is “relative to margin”. When you create the constraint with the “Add New Constraints” popover, you can choose whether it's margin-relative or not:</p>
<p><img src="https://i.stack.imgur.com/WBtbS.gif" alt="constraint-popover"></p>
<p>It always defaults to margin-relative; you have to turn the checkbox off every time you add constraints if you don't want them to be margin-relative.</p>
<p>You can't change whether a constraint is margin-relative in the quick-edit popover of your screen shot. Instead, double-click the constraint to bring up its full Attributes inspector. There, you can use the popup menus to select, for each end of the constraint, whether it's margin-relative or not:</p>
<p><img src="https://i.stack.imgur.com/23ole.gif" alt="constraint-attributes"></p> |
48,466,959 | Query for list of attribute instead of tuples in SQLAlchemy | <p>I'm querying for the ids of a model, and get a list of <code>(int,)</code> tuples back instead of a list of ids. Is there a way to query for the attribute directly?</p>
<pre><code>result = session.query(MyModel.id).all()
</code></pre>
<p>I realize it's possible to do </p>
<pre><code>results = [r for (r,) in results]
</code></pre>
<p>Is it possible for the query to return that form directly, instead of having to process it myself?</p> | 48,467,116 | 3 | 2 | null | 2018-01-26 17:57:28.383 UTC | 7 | 2020-09-30 14:18:21.947 UTC | 2018-01-26 21:19:45.22 UTC | null | 400,617 | null | 7,684,175 | null | 1 | 48 | python|sqlalchemy | 28,704 | <p>When passing in ORM-instrumented descriptors such as a column, each result is a <em>named tuple</em>, even for just one column. You could use the column name in a list comprehension to 'flatten' the list (you can drop the <code>.all()</code> call, iteration retrieves the objects too):</p>
<pre><code>result = [r.id for r in session.query(MyModel.id)]
</code></pre>
<p>or use the fact that it's a tuple when looping a <code>for</code> loop and unpack it to a single-element tuple of targets:</p>
<pre><code>result = session.query(MyModel.id)
for id, in result:
# do something with the id
</code></pre>
<p>The latter could also be used in a list comprehension:</p>
<pre><code>[id for id, in session.query(MyModel.id)]
</code></pre>
<p>You don't really have any options to force the row results to be <em>just</em> the single <code>id</code> value.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.