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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
15,878,810 | How to execute command on cmd from C# | <p>I want to run commands on the cmd from my C# app.</p>
<p>I tried: </p>
<pre><code>string strCmdText = "ipconfig";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
</code></pre>
<p><strong>result:</strong> </p>
<p>the cmd window pop but the command didn't do nothing.</p>
<p>why?</p> | 15,878,831 | 2 | 2 | null | 2013-04-08 12:16:14.137 UTC | 4 | 2019-10-22 04:58:17.133 UTC | 2019-10-22 04:58:17.133 UTC | null | 1,033,581 | null | 2,257,505 | null | 1 | 7 | c#|cmd | 49,596 | <p>Use </p>
<pre><code>System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig");
</code></pre>
<p>If you want to have cmd still opened use: </p>
<pre><code>System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig");
</code></pre> |
15,892,290 | How to change\set background image of a button in C# WPF code? | <p>I'm trying to change background image of my button to some other image and I encountered some errors.
This is the code I have on my xaml: </p>
<pre><code> <Button x:Name="Button1" Width="200" Height="200" Content="Button1" Margin="0,0,0,400">
<Button.Background>
<ImageBrush **ImageSource ="Images/AERO.png"** ></ImageBrush>
</Button.Background>
</Button>
</code></pre>
<p>and my cs:</p>
<pre><code> private void Button1_Click_1(object sender, RoutedEventArgs e)
{
var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Images/AERO.png"));
Button1.Background = brush;
}
</code></pre>
<p>The error I have on my xaml is " The file 'Images\logo.png' is not part of the project or its 'Build Action' property is not set to 'Resource'.
Can anyone help me explain, thanks</p> | 15,894,267 | 3 | 6 | null | 2013-04-09 02:29:39.707 UTC | 5 | 2016-11-02 13:58:22.653 UTC | 2016-11-02 13:58:22.653 UTC | null | 3,244,341 | null | 2,243,794 | null | 1 | 9 | c#|wpf|image|button | 75,332 | <p>In the build action, you can mark the image file as content or as resource. The syntax to use the image in an ImageBrush is different depending on which one you choose.</p>
<p>Here is a image file marked as <strong>content</strong>.</p>
<p><img src="https://i.stack.imgur.com/Ku2fG.png" alt="Image, marked as content"></p>
<p>To set the button background to this image use the following code.</p>
<pre><code> var brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Images/ContentImage.png",UriKind.Relative));
button1.Background = brush;
</code></pre>
<p>Here is an image file marked as <strong>resource</strong>.</p>
<p><img src="https://i.stack.imgur.com/zyuMW.png" alt="Image, marked as resource"></p>
<p>To set the button background to the resource image use the following code.</p>
<pre><code> Uri resourceUri = new Uri("Images/ResourceImage.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
button1.Background = brush;
</code></pre> |
19,038,458 | bash curl command not found on OS X. Where can I find it? | <p>I have no idea what I am getting myself into, I am very new to programming and trying to learn on my own. I am trying to install homebrew with <code>ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)</code> and this the outcome is <em>"-bash: curl: command not found"</em></p>
<p>I have been searching Google but can't seem to find anything to help me. when I type <code>which curl</code> it just goes to the next line of terminal as if I just opened terminal...<br>
I have xcode installed with command line tools installed, and even downloaded reinstalled it in case something was wrong with it.
Not that it matters but the reason I am attempting to install homebrew is it is needed for libsodium which is needed for dnscrypt.</p>
<p>When I type <code>curl-config</code> it gives me available values for OPTION include:</p>
<pre><code> --built-shared says 'yes' if libcurl was built shared
--ca ca bundle install path
--cc compiler
--cflags pre-processor and compiler flags
--checkfor [version] check for (lib)curl of the specified version
--configure the arguments given to configure when building curl
--features newline separated list of enabled features
--help display this help and exit
--libs library linking information
--prefix curl install prefix
--protocols newline separated list of enabled protocols
--static-libs static libcurl library linking information
--version output version information
--vernum output the version information as a number (hexadecimal)
</code></pre>
<p>Then I try any of of those like <code>curl --version</code> and it does the same curl command not found</p> | 19,039,149 | 3 | 2 | null | 2013-09-26 20:50:30.373 UTC | 2 | 2018-07-02 21:10:37.373 UTC | 2018-07-02 21:10:37.373 UTC | null | 814,752 | null | 2,821,160 | null | 1 | 26 | bash|macos|curl|homebrew | 100,046 | <p>As an alternative you can use <code>wget</code>:</p>
<pre><code>ruby -e "$(wget -qO - 'https://raw.github.com/mxcl/homebrew/go')"
</code></pre> |
5,154,529 | In Java, what is the default location for newly created files? | <p>In Java, what is the default location for newly created files?</p> | 5,154,592 | 2 | 3 | null | 2011-03-01 12:29:49.17 UTC | 5 | 2017-08-31 07:07:54.133 UTC | 2011-03-01 12:48:31.223 UTC | null | 331,515 | null | 526,443 | null | 1 | 23 | java|file-io|io | 56,671 | <p>If the current directory of the application. If e.g. you create a File by using </p>
<pre><code>new FileOutputStream("myfile")
</code></pre>
<p>then it is created in the "current" directory, which can be retrieved by calling </p>
<pre><code>System.getProperty("user.dir");
</code></pre>
<p>However if you change the current directory by calling native methods (very unlikely!), the property is not updated. It can be seen as the initial current directory of the application.</p>
<p>If you start your Java app in a batch file, and doubleclick on the link to it, the current directory will be the directory where the batch file resided, but this can be changed in the link.</p>
<p>If you start your Java app from the command line, you already know the directory you are in.</p>
<p>If you start your Java app from the IDE, the current directory is usually the project root, but this can usually be configured in the launch configuration.</p>
<p><strong>UPDATE 2017-08:</strong></p>
<p>You could also always find the current correct location with <code>new File(".").getAbsolutePath()</code>.</p> |
5,269,634 | ADDRESS WIDTH from RAM DEPTH | <p>I am implementing a configurable DPRAM where RAM DEPTH is the parameter.</p>
<p>How to determine ADDRESS WIDTH from RAM DEPTH?</p>
<p>I know the relation RAM DEPTH = 2 ^ (ADDRESS WIDTH)</p>
<p>i.e ADDRESS WIDTH = log (base 2) RAM DEPTH.</p>
<p>How to implement the log (base 2) function in Verilog?</p> | 5,276,596 | 2 | 0 | null | 2011-03-11 06:20:58.057 UTC | 13 | 2020-06-20 17:59:30.32 UTC | 2011-03-11 18:02:00.62 UTC | null | 197,758 | null | 654,855 | null | 1 | 26 | verilog|system-verilog | 63,488 | <p>The <code>$clog2</code> system task was added to the SystemVerilog extension to Verilog (IEEE Std 1800-2005). This returns an integer which has the value of the ceiling of the log base 2. The DEPTH need not be a power of 2. </p>
<pre><code>module tb;
parameter DEPTH = 5;
parameter WIDTH = $clog2(DEPTH);
initial begin
$display("d=%0d, w=%0d", DEPTH, WIDTH);
#5 $finish;
end
endmodule
</code></pre>
<p>Running a simulation will display this:</p>
<pre><code>d=5, w=3
</code></pre>
<p>However, I do not know of a synthesis tool which supports <code>$clog2</code>. If you need to synthesize your code, you can use a <code>function</code>. This was copied from the IEEE 1364-2001 Std, but there are other versions floating around the web:</p>
<pre><code>function integer clogb2;
input [31:0] value;
begin
value = value - 1;
for (clogb2 = 0; value > 0; clogb2 = clogb2 + 1) begin
value = value >> 1;
end
end
endfunction
</code></pre>
<p>My experience has been that using the <code>function</code> is more trouble than it's worth for synthesizable code. It has caused problems for other tools in the design flow (linters, equivalence checkers, etc.).</p> |
678,771 | How to calculate MIPS for an algorithm for ARM processor | <p>I have been asked recently to produced the MIPS (million of instructions per second) for an algorithm we have developed. The algorithm is exposed by a set of C-style functions. We have exercise the code on a Dell Axim to benchmark the performance under different input.</p>
<p>This question came from our hardware vendor, but I am mostly a HL software developer so I am not sure how to respond to the request. Maybe someone with similar HW/SW background can help...</p>
<ol>
<li><p>Since our algorithm is not real time, I don't think we need to quantify it as MIPS. Is it possible to simply quote the total number of assembly instructions?</p></li>
<li><p>If 1 is true, how do you do this (ie. how to measure the number of assembly instructions) either in general or specifically for ARM/XScale?</p></li>
<li><p>Can 2 be performed on a WM device or via the Device Emulator provided in VS2005?</p></li>
<li><p>Can 3 be automated?</p></li>
</ol>
<p>Thanks a lot for your help.
Charles</p>
<hr>
<p>Thanks for all your help. I think S.Lott hit the nail. And as a follow up, I now have more questions.</p>
<p>5 Any suggestion on how to go about measuring MIPS? I heard some one suggest running our algorithm and comparing it against Dhrystone/Whetstone benchmark to calculate MIS.</p>
<p>6 Since the algorithm does not need to be run in real time, is MIPS really a useful measure? (eg. factorial(N)) What are other ways to quantity the processing requirements? (I have already measured the runtime performance but it was not a satisfactory answer.)</p>
<p>7 Finally, I assume MIPS is a crude estimate and would be dep. on compiler, optimization settings, etc? </p> | 678,871 | 7 | 3 | null | 2009-03-24 19:03:32.707 UTC | 9 | 2014-06-16 00:00:05.263 UTC | 2014-06-16 00:00:05.263 UTC | null | 96,982 | null | 82,180 | null | 1 | 12 | arm|benchmarking | 25,610 | <p>I'll bet that your hardware vendor is asking how many MIPS you need. </p>
<p>As in "Do you need a 1,000 MIPS processor or a 2,000 MIPS processor?"</p>
<p>Which gets translated by management into "How many MIPS?" </p>
<p>Hardware offers MIPS. Software consumes MIPS.</p>
<p>You have two degrees of freedom.</p>
<ul>
<li><p>The processor's inherent MIPS offering.</p></li>
<li><p>The number of seconds during which you consume that many MIPS.</p></li>
</ul>
<p>If the processor doesn't have enough MIPS, your algorithm will be "slow".</p>
<p>if the processor has enough MIPS, your algorithm will be "fast".</p>
<p>I put "fast" and "slow" in quotes because you need to have a performance requirement to determine "fast enough to meet the performance requirement" or "too slow to meet the performance requirement."</p>
<p>On a 2,000 MIPS processor, you might take an acceptable 2 seconds. But on a 1,000 MIPS processor this explodes to an unacceptable 4 seconds.</p>
<hr>
<p>How many MIPS do you need?</p>
<ol>
<li><p>Get the official MIPS for your processor. See <a href="http://en.wikipedia.org/wiki/Instructions_per_second" rel="noreferrer">http://en.wikipedia.org/wiki/Instructions_per_second</a></p></li>
<li><p>Run your algorithm on some data.</p></li>
<li><p>Measure the exact run time. Average a bunch of samples to reduce uncertainty.</p></li>
<li><p>Report. 3 seconds on a 750 MIPS processor is -- well -- 3 seconds at 750 MIPS. MIPS is a rate. Time is time. Distance is the product of rate * time. 3 seconds at 750 MIPS is 750*3 million instructions. </p></li>
</ol>
<p>Remember Rate (in Instructions per second) * Time (in seconds) gives you Instructions.</p>
<p>Don't say that it's 3*750 MIPS. It isn't; it's 2250 Million Instructions.</p> |
394,853 | SQL INNER JOIN syntax | <p>the two bits of SQL below get the same result</p>
<pre><code>SELECT c.name, o.product
FROM customer c, order o
WHERE c.id = o.cust_id
AND o.value = 150
SELECT c.name, o.product
FROM customer c
INNER JOIN order o on c.id = o.cust_id
WHERE o.value = 150
</code></pre>
<p>I've seen both styles used as standard at different companies. From what I've seen, the 2nd one is what most people recommend online. Is there any real reason for this other than style? Does using an Inner Join sometimes have better performance?</p>
<p>I've noticed Ingres and Oracle developers tend to use the first style, whereas Microsoft SQL Server users have tended to use the second, but that might just be a coincidence.</p>
<p>Thanks for any insight, I've wondered about this for a while.</p>
<p>Edit: I've changed the title from 'SQL Inner Join versus Cartesian Product' as I was using the incorrect terminlogy. Thanks for all the responses so far.</p> | 394,876 | 7 | 0 | null | 2008-12-27 10:14:14.943 UTC | 11 | 2021-01-08 22:34:56.067 UTC | 2020-04-07 19:07:35.277 UTC | Dean Madden | 1,025,118 | Dean Madden | 49,171 | null | 1 | 29 | sql|syntax|inner-join|cross-join | 29,700 | <p>Both queries are an inner joins and equivalent. The first is the older method of doing things, whereas the use of the JOIN syntax only became common after the introduction of the SQL-92 standard (I believe it's in the older definitions, just wasn't particularly widely used before then).</p>
<p>The use of the JOIN syntax is strongly preferred as it separates the join logic from the filtering logic in the WHERE clause. Whilst the JOIN syntax is really syntactic sugar for inner joins it's strength lies with outer joins where the old * syntax can produce situations where it is impossible to unambiguously describe the join and the interpretation is implementation-dependent. The [LEFT | RIGHT] JOIN syntax avoids these pitfalls, and hence for consistency the use of the JOIN clause is preferable in all circumstances.</p>
<p>Note that neither of these two examples are Cartesian products. For that you'd use either</p>
<pre><code>SELECT c.name, o.product
FROM customer c, order o
WHERE o.value = 150
</code></pre>
<p>or</p>
<pre><code>SELECT c.name, o.product
FROM customer c CROSS JOIN order o
WHERE o.value = 150
</code></pre> |
54,989 | Change windows hostname from command line | <p>Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?</p> | 55,212 | 8 | 2 | null | 2008-09-10 18:45:04.097 UTC | 13 | 2019-10-07 03:53:46.82 UTC | 2008-09-24 15:15:52.16 UTC | Oli | 12,870 | dmo | 1,807 | null | 1 | 34 | windows|command-line | 193,203 | <p>The netdom.exe command line program can be used. This is available from the Windows XP Support Tools or Server 2003 Support Tools (both on the installation CD).</p>
<p>Usage guidelines <a href="https://web.archive.org/web/20170928171940/https://support.microsoft.com/en-us/help/298593/how-to-use-the-netdom-exe-utility-to-rename-a-computer-in-windows-xp" rel="nofollow noreferrer">here</a></p> |
270,309 | Can I use a function for a default value in MySql? | <p>I want to do something like this:</p>
<pre>
<code>
create table app_users
(
app_user_id smallint(6) not null auto_increment primary key,
api_key char(36) not null default uuid()
);
</code>
</pre>
<p>However this results in a error, is there a way to call a function for a default value in mysql?</p>
<p>thanks.</p> | 270,338 | 9 | 0 | null | 2008-11-06 21:16:00.8 UTC | 20 | 2021-11-11 15:05:38.24 UTC | null | null | null | mmattax | 1,638 | null | 1 | 101 | mysql | 90,519 | <p>No, you can't.</p>
<p>However, you could easily create a trigger to do this, such as:</p>
<pre>
CREATE TRIGGER before_insert_app_users
BEFORE INSERT ON app_users
FOR EACH ROW
SET new.api_key = uuid();
</pre> |
522,828 | Is Code For Computers or for People? | <p>Ultimately, code compiles down (eventually) into instructions for a CPU. Code, however, (in my humble opinion) is for human beings to read, update, and interact with. This leads me to the following observation:</p>
<p><em>Code that is unreadable by other engineers, even if it's functional, is bad code.</em></p>
<p>With that in mind, what can this programmer do to make code more easily read by humans?</p>
<ul>
<li><p>Naming Conventions? (Joel has a fair amount to say on that one)</p></li>
<li><p>Code Structure/Layout? (please, for the love of god, don't get into the <code>{</code> placement debate)</p></li>
<li><p>Phrasing? (Is it possible to write code that looks more like the English language)</p></li>
</ul>
<p>Are there good articles out there beyond <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="noreferrer">Joel's</a>.</p> | 522,907 | 10 | 1 | null | 2009-02-07 00:55:01.993 UTC | 15 | 2017-10-16 15:17:53.573 UTC | 2012-08-28 08:34:11 UTC | null | 623,518 | null | 62,516 | null | 1 | 31 | code-readability | 8,695 | <blockquote>
<p>“Any fool can write code that a
computer can understand. Good
programmers write code that humans can
understand.” <em>-- Martin Fowler, "Refactoring: Improving the Design of Existing Code"</em></p>
</blockquote>
<p>But since you've already reached that conclusion on your own, suffice to say that this is a huge topic. It's not something you'll be able to get a single answer on. Making your code maintainable is not limited to coding style, but also involves your overall design as well as your construction process. Here's some tags on this site where pretty much all the questions and answers will impinge on this topic:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/tagged/coding-style">coding-style</a></li>
<li><a href="https://stackoverflow.com/questions/tagged/best-practices">best-practices</a></li>
<li><a href="https://stackoverflow.com/questions/tagged/refactoring">refactoring</a></li>
</ul> |
987,053 | How to show form in front in C# | <p>Folks,</p>
<p>Please does anyone know how to show a Form from an otherwise invisible application, <em>and</em> have it get the focus (i.e. appear on top of other windows)? I'm working in C# .NET 3.5.</p>
<p>I suspect I've taken "completely the wrong approach"... I do <strong>not</strong> <em>Application.Run(new TheForm ())</em> instead I <em>(new TheForm()).ShowModal()</em>... The Form is basically a modal dialogue, with a few check-boxes; a text-box, and OK and Cancel Buttons. The user ticks a checkbox and types in a description (or whatever) then presses OK, the form disappears and the process reads the user-input from the Form, Disposes it, and continues processing.</p>
<p>This works, except when the form is show it doesn't get the focus, instead it appears behind the "host" application, until you click on it in the taskbar (or whatever). This is a most annoying behaviour, which I predict will cause many "support calls", and the existing VB6 version doesn't have this problem, so I'm going backwards in usability... and users won't accept that (and nor should they).</p>
<p>So... I'm starting to think I need to rethink the whole shebang... I should show the form up front, as a "normal application" and attach the remainer of the processing to the OK-button-click event. It should work, But that will take time which I don't have (I'm already over time/budget)... so first I really need to try to make the current approach work... even by quick-and-dirty methods. </p>
<p>So please does anyone know how to "force" a .NET 3.5 Form (by fair means or fowl) to get the focus? I'm thinking "magic" windows API calls (I know</p>
<p><strong>Twilight Zone:</strong> This only appears to be an issue at work, we're I'm using Visual Studio 2008 on Windows XP SP3... I've just failed to reproduce the problem with an SSCCE (see below) at home on Visual C# 2008 on Vista Ulimate... This works fine. Huh? WTF? </p>
<p>Also, I'd swear that at work yesterday showed the form when I ran the EXE, but not when F5'ed (or Ctrl-F5'ed) straight from the IDE (which I just put up with)... At home the form shows fine either way. Totaly confusterpating!</p>
<p>It may or may not be relevant, but Visual Studio crashed-and-burned this morning when the project was running in debug mode and editing the code "on the fly"... it got stuck what I presumed was an endless loop of error messages. The error message was something about "can't debug this project because it is not the current project, or something... So I just killed it off with process explorer. It started up again fine, and even offered to recover the "lost" file, an offer which I accepted.</p>
<pre><code>using System;
using System.Windows.Forms;
namespace ShowFormOnTop {
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Form1 frm = new Form1();
frm.ShowDialog();
}
}
}
</code></pre>
<p><strong>Background:</strong> I'm porting an existing VB6 implementation to .NET... It's a "plugin" for a "client" GIS application called <a href="http://www.mapinfo.com/" rel="noreferrer">MapInfo</a>. The existing client "worked invisibly" and my instructions are "to keep the new version as close as possible to the old version", which works well enough (after years of patching); it's just written in an unsupported language, so we need to port it.</p>
<p><strong>About me:</strong> I'm pretty much a noob to C# and .NET generally, though I've got a bottoms wiping certificate, I have been a professional programmer for 10 years; So I sort of "know some stuff".</p>
<p>Any insights would be most welcome... and Thank you all for taking the time to read this far. Consiseness isn't (apparently) my forte. </p>
<p>Cheers. Keith.</p> | 987,209 | 11 | 0 | null | 2009-06-12 14:49:47.257 UTC | 2 | 2018-10-26 04:21:14.933 UTC | null | null | null | null | 69,224 | null | 1 | 25 | c#|forms|z-order | 91,475 | <p>Simply</p>
<pre><code>yourForm.TopMost = true;
</code></pre> |
458,657 | CSS for the "down arrow" on a <select> element? | <p>Is it possible to stylize the down arrow on a drop down select element? i.e., (<code><select><option>--></option></select></code>)</p>
<p>I suspect the answer is no because of the way IE handles that particular element. If there isn't a way, does anyone know of a 'fake' drop down box using javaScript that would mimic that behavior but give me the ability to customize?</p> | 458,663 | 11 | 0 | null | 2009-01-19 18:41:10.293 UTC | 15 | 2015-10-07 17:10:14.437 UTC | 2012-05-14 06:12:21.933 UTC | null | 507,674 | Chu | 36,620 | null | 1 | 36 | jquery|html|css | 170,435 | <p>Maybe you can use <a href="http://code.google.com/p/select-box/" rel="nofollow noreferrer">jQuery selectbox replacement</a>. It's a jQuery plugin.</p> |
1,038,006 | What are some good patterns for VBA error handling? | <p>What are some good patterns for error handling in VBA?</p>
<p>In particular, what should I do in this situation:</p>
<pre class="lang-none prettyprint-override"><code>... some code ...
... some code where an error might occur ...
... some code ...
... some other code where a different error might occur ...
... some other code ...
... some code that must always be run (like a finally block) ...
</code></pre>
<p>I want to handle both errors, and resume execution after the code where the error may occur. Also, the finally code at the end must <em>always</em> run - no matter what exceptions are thrown earlier. How can I achieve this outcome?</p> | 1,046,222 | 13 | 0 | null | 2009-06-24 12:17:15.523 UTC | 48 | 2021-12-03 18:59:27.44 UTC | 2021-10-27 15:33:42.77 UTC | null | 63,550 | null | 106,315 | null | 1 | 81 | vba|exception | 153,417 | <h1>Error Handling in VBA</h1>
<ul>
<li><code>On Error Goto</code> <em>ErrorHandlerLabel</em></li>
<li><code>Resume</code> (<code>Next</code> | <em>ErrorHandlerLabel</em>)</li>
<li><code>On Error Goto 0</code> (disables current error handler)</li>
<li><code>Err</code> object</li>
</ul>
<p>The <code>Err</code> object's properties are normally reset to a zero or a zero-length string in the error handling routine, but it can also be done explicitly with <code>Err.Clear</code>.</p>
<p>Errors in the error handling routine are terminating.</p>
<p>The range 513-65535 is available for user errors.
For custom class errors, you add <code>vbObjectError</code> to the error number.
See the Microsoft documentation about <a href="https://msdn.microsoft.com/en-us/vba/language-reference-vba/articles/raise-method" rel="nofollow noreferrer"><code>Err.Raise</code></a> and the <a href="http://web.archive.org/web/20150221085212/http://support.microsoft.com:80/kb/146864" rel="nofollow noreferrer">list of error numbers</a>.</p>
<p>For not implemented interface members in a <em>derived</em> class, you should use the constant <code>E_NOTIMPL = &H80004001</code>.</p>
<hr/>
<pre><code>Option Explicit
Sub HandleError()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub RaiseAndHandleError()
On Error GoTo errMyErrorHandler
' The range 513-65535 is available for user errors.
' For class errors, you add vbObjectError to the error number.
Err.Raise vbObjectError + 513, "Module1::Test()", "My custom error."
On Error GoTo 0
Debug.Print "This line will be executed."
Exit Sub
errMyErrorHandler:
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Err.Clear
Resume Next
End Sub
Sub FailInErrorHandler()
Dim a As Integer
On Error GoTo errMyErrorHandler
a = 7 / 0
On Error GoTo 0
Debug.Print "This line won't be executed."
DoCleanUp:
a = 0
Exit Sub
errMyErrorHandler:
a = 7 / 0 ' <== Terminating error!
MsgBox Err.Description, _
vbExclamation + vbOKCancel, _
"Error: " & CStr(Err.Number)
Resume DoCleanUp
End Sub
Sub DontDoThis()
' Any error will go unnoticed!
On Error Resume Next
' Some complex code that fails here.
End Sub
Sub DoThisIfYouMust()
On Error Resume Next
' Some code that can fail but you don't care.
On Error GoTo 0
' More code here
End Sub
</code></pre> |
683,037 | How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework? | <p>Is there a way to compare two <code>DateTime</code> variables in <code>Linq2Sql</code> but to disregard the Time part.</p>
<p>The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.</p>
<p>I want to compare <code>12/3/89 12:43:34</code> and <code>12/3/89 11:22:12</code> and have it disregard the actual time of day so both of these are considered the same.</p>
<p>I guess I can set all the times of day to <code>00:00:00</code> before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.</p>
<p>I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?</p> | 683,042 | 13 | 0 | null | 2009-03-25 19:17:43.163 UTC | 27 | 2021-10-29 16:15:31.903 UTC | 2019-10-22 20:03:31.073 UTC | null | 1,116,802 | Sruly | 72,453 | null | 1 | 382 | c#|.net|database|entity-framework|linq-to-sql | 369,649 | <p>try using the <code>Date</code> property on the <code>DateTime</code> Object...</p>
<pre><code>if(dtOne.Date == dtTwo.Date)
....
</code></pre> |
1,310,166 | How to import an excel file in to a MySQL database | <p>Can any one explain how to import a Microsoft Excel file in to a MySQL database?</p>
<p>For example, my Excel table looks like this:</p>
<pre><code>Country | Amount | Qty
----------------------------------
America | 93 | 0.60
Greece | 9377 | 0.80
Australia | 9375 | 0.80
</code></pre> | 1,310,183 | 15 | 12 | null | 2009-08-21 05:07:59.78 UTC | 51 | 2022-04-11 07:46:02.517 UTC | 2019-03-21 14:13:59.46 UTC | null | 4,348,556 | null | 154,137 | null | 1 | 101 | mysql|excel | 499,079 | <ol>
<li><p>Export it into some text format. The easiest will probably be a tab-delimited version, but CSV can work as well.</p></li>
<li><p>Use the load data capability. See <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/load-data.html</a></p></li>
<li><p>Look half way down the page, as it will gives a good example for tab separated data:</p>
<p>FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\'</p></li>
<li><p>Check your data. Sometimes quoting or escaping has problems, and you need to adjust your source, import command-- or it may just be easier to post-process via SQL.</p></li>
</ol> |
69,332 | Tracking CPU and Memory usage per process | <p>I suspect that one of my applications eats more CPU cycles than I want it to. The problem is - it happens in bursts, and just looking at the task manager doesn't help me as it shows immediate usage only.</p>
<p>Is there a way (on Windows) to track the history of CPU & Memory usage for some process. E.g. I will start tracking "firefox", and after an hour or so will see a graph of its CPU & memory usage during that hour.</p>
<p>I'm looking for either a ready-made tool or a programmatic way to achieve this.</p> | 69,416 | 16 | 0 | null | 2008-09-16 04:13:53.467 UTC | 49 | 2022-04-06 05:31:02.523 UTC | 2013-06-01 17:56:33.323 UTC | null | 322,020 | eliben | 8,206 | null | 1 | 179 | windows|sysadmin|process-management | 424,555 | <p>Press <kbd>Win</kbd>+<kbd>R</kbd>, type <code>perfmon</code> and press <kbd>Enter</kbd>. When the Performance window is open, click on the <strong>+</strong> sign to add new counters to the graph. The counters are different aspects of how your PC works and are grouped by similarity into groups called "Performance Object".</p>
<p>For your questions, you can choose the "Process", "Memory" and "Processor" performance objects. You then can see these counters in real time</p>
<p>You can also specify the utility to save the performance data for your inspection later. To do this, select "Performance Logs and Alerts" in the left-hand panel. (It's right under the System Monitor console which provides us with the above mentioned counters. If it is not there, click "File" > "Add/remove snap-in", click Add and select "Performance Logs and Alerts" in the list".) From the "Performance Logs and Alerts", create a new monitoring configuration under "Counter Logs". Then you can add the counters, specify the sampling rate, the log format (binary or plain text) and log location.</p> |
616,645 | How to duplicate sys.stdout to a log file? | <p>Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?</p>
<p>My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using <code>os.dup2()</code>. I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.</p>
<hr>
<p>In other words, I want the functionality of the command line 'tee' for any output generated by a python app, <strong>including system call output</strong>.</p>
<p>To clarify: </p>
<p>To redirect all output I do something like this, and it works great:</p>
<pre><code># open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
</code></pre>
<p>The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.</p>
<p>Simply, I want to do the same, except <em>duplicating</em> instead of redirecting.</p>
<p>At first thought, I thought that simply reversing the <code>dup2</code>'s should work. Why doesn't it? Here's my test: </p>
<pre><code>import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print("foo bar")
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>The file "a.log" should be identical to what was displayed on the screen.</p> | 651,718 | 19 | 4 | null | 2009-03-05 21:12:13.4 UTC | 107 | 2022-03-17 13:07:38.037 UTC | 2019-01-04 18:31:12.94 UTC | drue | 355,230 | drue | 63,439 | null | 1 | 163 | python|tee | 125,045 | <p>Since you're comfortable spawning external processes from your code, you could use <code>tee</code> itself. I don't know of any Unix system calls that do exactly what <code>tee</code> does.</p>
<pre><code># Note this version was written circa Python 2.6, see below for
# an updated 3.3+-compatible version.
import subprocess, os, sys
# Unbuffer output (this ensures the output is in the correct order)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
tee = subprocess.Popen(["tee", "log.txt"], stdin=subprocess.PIPE)
os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(tee.stdin.fileno(), sys.stderr.fileno())
print "\nstdout"
print >>sys.stderr, "stderr"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre>
<p>You could also emulate <code>tee</code> using the <a href="http://docs.python.org/dev/library/multiprocessing.html" rel="noreferrer">multiprocessing</a> package (or use <a href="http://pypi.python.org/pypi/processing" rel="noreferrer">processing</a> if you're using Python 2.5 or earlier).</p>
<p><strong>Update</strong></p>
<p>Here is a Python 3.3+-compatible version:</p>
<pre><code>import subprocess, os, sys
tee = subprocess.Popen(["tee", "log.txt"], stdin=subprocess.PIPE)
# Cause tee's stdin to get a copy of our stdin/stdout (as well as that
# of any child processes we spawn)
os.dup2(tee.stdin.fileno(), sys.stdout.fileno())
os.dup2(tee.stdin.fileno(), sys.stderr.fileno())
# The flush flag is needed to guarantee these lines are written before
# the two spawned /bin/ls processes emit any output
print("\nstdout", flush=True)
print("stderr", file=sys.stderr, flush=True)
# These child processes' stdin/stdout are
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
</code></pre> |
216,119 | How do I reverse a list using recursion in Python? | <p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p> | 216,136 | 20 | 0 | 2008-10-19 06:56:01.867 UTC | 2008-10-19 06:56:01.867 UTC | 4 | 2022-02-01 16:28:56.173 UTC | 2012-09-16 20:07:17.553 UTC | null | 635,608 | Alistair | 11,324 | null | 1 | 6 | python|list|recursion | 56,026 | <p>Append the first element of the list to a reversed sublist:</p>
<pre><code>mylist = [1, 2, 3, 4, 5]
backwards = lambda l: (backwards (l[1:]) + l[:1] if l else [])
print backwards (mylist)
</code></pre> |
926,069 | Add up a column of numbers at the Unix shell | <p>Given a list of files in <code>files.txt</code>, I can get a list of their sizes like this:</p>
<pre><code>cat files.txt | xargs ls -l | cut -c 23-30
</code></pre>
<p>which produces something like this:</p>
<pre><code> 151552
319488
1536000
225280
</code></pre>
<p>How can I get the <strong>total</strong> of all those numbers?</p> | 18,141,152 | 23 | 0 | null | 2009-05-29 13:50:41.453 UTC | 54 | 2021-08-24 15:46:52.823 UTC | null | null | null | null | 21,886 | null | 1 | 229 | linux|unix|shell | 210,602 | <pre><code>... | paste -sd+ - | bc
</code></pre>
<p>is the shortest one I've found (from the <a href="http://www.unixcl.com/2009/11/sum-of-numbers-in-file-unix.html">UNIX Command Line</a> blog).</p>
<p><strong>Edit:</strong> added the <code>-</code> argument for portability, thanks @Dogbert and @Owen.</p> |
748,062 | Return multiple values to a method caller | <p>I read the <a href="https://stackoverflow.com/questions/321068/returning-multiple-values-from-a-c-function">C++ version of this question</a> but didn't really understand it.</p>
<p>Can someone please explain clearly if it can be done in C#, and how?</p> | 10,278,769 | 28 | 1 | null | 2009-04-14 15:11:57.66 UTC | 150 | 2022-03-08 15:30:22.963 UTC | 2021-10-21 00:36:47.3 UTC | null | 3,375,713 | null | 84,546 | null | 1 | 601 | c#|return | 1,012,375 | <p>In C# 7 and above, see <a href="https://stackoverflow.com/a/36436255/316760">this answer</a>.</p>
<p>In previous versions, you can use <a href="http://msdn.microsoft.com/en-us/library/system.tuple.aspx" rel="noreferrer">.NET 4.0+'s Tuple</a>:</p>
<p>For Example:</p>
<pre><code>public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
</code></pre>
<p>Tuples with two values have <code>Item1</code> and <code>Item2</code> as properties.</p> |
57,909 | When creating a new GUI, is WPF the preferred choice over Windows Forms? | <p>Most restrictions and tricks with windows forms are common to most programmers. But since .NET 3.0 there is also WPF available, the Windows Presentation Foundation. It is said that you can make "sexy applications" more easy with it and with .NET 3.5 SP1 it got a good speed boost on execution.</p>
<p>But on the other side a lot of things are working different with WPF. I will not say it is more difficult but you have to learn "everything" from scratch.</p>
<p>My question: Is it worth to spend this extra time when you have to create a new GUI and there is no time pressure for the project?</p> | 75,387 | 34 | 5 | null | 2008-09-11 23:33:59.913 UTC | 138 | 2012-01-30 20:37:58.76 UTC | 2008-09-25 11:15:56.817 UTC | Matt Hamilton | 615 | Anheledir | 5,703 | null | 1 | 47 | .net|wpf|winforms|.net-3.5|.net-3.0 | 50,059 | <p>WPF enables you to do some amazing things, and I LOVE it... but I always feel obligated to qualify my recommendations, whenever developers ask me whether I think they should be moving to the new technology.</p>
<p>Are your developers willing (preferrably, EAGER) to spend the time it takes to learn to use WPF effectively? I never would have thought to say this about MFC, or Windows Forms, or even unmanaged DirectX, but you probably do NOT want a team trying to "pick up" WPF over the course of a normal dev. cycle for a shipping product!</p>
<p>Do at least one or two of your developers have some design sensibilities, and do individuals with final design authority have a decent understanding of development issues, so you can leverage WPF capabilities to create something which is actually BETTER, instead of just more "colorful", featuring gratuitous animation?</p>
<p>Does some percentage of your target customer base run on integrated graphics chip sets that might not support the features you were planning -- or are they still running Windows 2000, which would eliminate them as customers altogether? Some people would also ask whether your customers actually CARE about enhanced visuals but, having lived through internal company "Our business customers don't care about colors and pictures" debates in the early '90s, I know that well-designed solutions from your competitors will MAKE them care, and the real question is whether the conditions are right, to enable you to offer something that will make them care NOW.</p>
<p>Does the project involve grounds-up development, at least for the presentation layer, to avoid the additional complexity of trying to hook into incompatible legacy scaffolding (Interop with Win Forms is NOT seamless)?</p>
<p>Can your manager accept (or be distracted from noticing) a significant DROP in developer productivity for four to six months?</p>
<p>This last issue is due to what I like to think of as the "FizzBin" nature of WPF, with ten different ways to implement any task, and no apparent reason to prefer one approach to another, and little guidance available to help you make a choice. Not only will the shortcomings of whatever choice you make become clear only much later in the project, but you are virtually guaranteed to have every developer on your project adopting a different approach, resulting in a major maintenance headache. Most frustrating of all are the inconsistencies that constantly trip you up, as you try to learn the framework.</p>
<p>You can find more in-depth WPF-related information in an entry on my blog:</p>
<p><a href="http://missedmemo.com/blog/2008/09/13/WPFTheFizzBinAPI.aspx" rel="nofollow noreferrer">http://missedmemo.com/blog/2008/09/13/WPFTheFizzBinAPI.aspx</a></p> |
6,622,452 | Alias template specialisation | <p>Can alias templates (14.5.7) be explicitly specialised (14.7.3)?</p>
<p>My standard-fu fails me, and I can't find a compiler to test on.</p>
<p>The text "when a template-id refers to the specialization of an alias template" implies <em>yes</em>, but then the example appears to refer to something else, implying <em>no</em>.</p>
<p><sub><strong>NB.</strong> I'm working from n3242, one behind the FDIS, in which the title of this section is "Aliase templates". Lol.</sub></p> | 6,623,089 | 4 | 5 | null | 2011-07-08 09:25:32.083 UTC | 10 | 2018-04-12 09:41:16.28 UTC | 2011-10-02 10:31:04.137 UTC | null | 34,509 | null | 560,648 | null | 1 | 41 | c++|templates|c++11 | 27,443 | <p>What the Standard means by "specialization" is the transformation of a generic template to a <em>more specialized</em> entity. For example, instantiating a non-member class template yields a class that's not a template anymore. The term "specialization" is two fold, and can refer to a generated specialization (which is a specialization that was instantiated, possibly from a partial specialization) and to an explicit specialization (which is what you referred to). </p>
<p>Alias templates aren't instantiated and there aren't specializations of them. There is nothing they could instantiate to. Instead, whenever their name is followed by a template argument list, the type denoted is the type you get by replacing the name and argument list by the alias'ed type, replacing all template parameter references with the arguments given in the argument list. That is, rather than the specialization of it being an alias, the alias template itself serves as an alias, without the need to instantiate anything. This replacement is done very early. Consider:</p>
<pre><code>template<typename T> using ref = T&;
template<typename T> void f(ref<T> x) { x = 10; }
int main() { int a; f(a); return a; /* 10 */ }
</code></pre>
<p>The replacement is done at the time <code>ref<T></code> is named (such a names are used to refer to class or function template specializations; hence the spec describes such names to "refer to the specialization of an alias template"). That is, the parameter of <code>f</code> has type <code>T&</code>, and thus, <code>T</code> can be deduced. This property is preventing explicit or partial specializations of alias templates. Because in order to pick the correct specialization of <code>ref</code>, it needs to know <code>T</code>. But to know it, it needs to compare <code>ref<T></code> against the argument type to deduce <code>T</code>. It's summarized in the paper <a href="http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2002/n1406.pdf" rel="noreferrer">N1406, "Proposed addition to C++: Typedef Templates"</a>, section 2.2</p>
<blockquote>
<p><strong>2.2 The Main Choice: Specialization vs. Everything Else</strong></p>
<p>After discussion on the reflectors and in the Evolution WG, it turns out that we have to choose between two mutually exclusive models:</p>
<ol>
<li><p>A typedef template is not itself an alias; only the (possibly-specialized) instantiations of the typedef template are aliases. This choice allows us to have specialization of typedef templates.</p></li>
<li><p>A typedef template is itself an alias; it cannot be specialized. This choice would allow:</p>
<ul>
<li>deduction on typedef template function parameters (see 2.4)</li>
<li>a declaration expressed using typedef templates be the same as the declaration without
typedef templates (see 2.5)</li>
<li>typedef templates to match template template parameters (see 2.6)</li>
</ul></li>
</ol>
</blockquote>
<p>It should be noted that the quoted paper, which favors option 1, did not make it into C++0x.</p>
<hr>
<p>EDIT: Because you desperately want to have a spec quote saying so explicitly. 14.5p3 is one that does</p>
<blockquote>
<p>Because an alias-declaration cannot declare a template-id, it is not possible to partially or explicitly specialize an alias template.</p>
</blockquote> |
6,625,458 | Removing <p> and <br/> tags in WordPress posts | <p>Whenever I am posting some content in WordPress post page it is showing some paragraph tags like <code><p></code> and <code><br/></code>. Which is showing some extra space in output. So is there any solution for it? How to remove all the tags?</p> | 6,627,460 | 10 | 0 | null | 2011-07-08 13:53:46.313 UTC | 24 | 2019-03-12 02:53:48.507 UTC | 2014-04-24 17:28:43.653 UTC | null | 1,696,030 | null | 614,208 | null | 1 | 54 | wordpress | 89,578 | <p>This happens because of WordPress's <code>wpautop</code>.
Simply add below line of code in your theme's functions.php file</p>
<p><code>remove_filter( 'the_content', 'wpautop' );</code></p>
<p><code>remove_filter( 'the_excerpt', 'wpautop' );</code></p>
<p>For more information: <a href="http://codex.wordpress.org/Function_Reference/wpautop" rel="noreferrer">http://codex.wordpress.org/Function_Reference/wpautop</a></p> |
6,736,476 | How to turn NaN from parseInt into 0 for an empty string? | <p>Is it possible somehow to return 0 instead of <code>NaN</code> when parsing values in JavaScript?</p>
<p>In case of the empty string <code>parseInt</code> returns <code>NaN</code>.</p>
<p>Is it possible to do something like that in JavaScript to check for <code>NaN</code>?</p>
<pre><code>var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)
</code></pre>
<p>Or maybe there is another function or jQuery plugin which may do something similar?</p> | 6,736,521 | 18 | 3 | null | 2011-07-18 16:58:33.64 UTC | 47 | 2022-02-18 03:15:14.04 UTC | 2017-07-20 21:52:38.747 UTC | null | 4,642,212 | null | 733,323 | null | 1 | 342 | javascript|nan | 299,420 | <pre><code>var s = '';
var num = parseInt(s) || 0;
</code></pre>
<p>When not used with boolean values, the logical OR <code>||</code> operator returns the first expression <code>parseInt(s)</code> if it can be evaluated to <code>true</code>, otherwise it returns the second expression <code>0</code>. The return value of <code>parseInt('')</code> is <code>NaN</code>. <code>NaN</code> evaluates to <code>false</code>, so <code>num</code> ends up being set to <code>0</code>.</p> |
45,633,699 | How does the `prop.table()` function work in r? | <p>I've just started learning r and have had trouble finding an (understandable) explanation of what the <code>prop.table()</code> function does. I found the following <a href="https://www.rdocumentation.org/packages/base/versions/3.4.1/topics/prop.table" rel="nofollow noreferrer">explanation</a> and example:</p>
<blockquote>
<p><strong>prop.table: Express Table Entries as Fraction of Marginal Table</strong></p>
<p><strong>Examples</strong></p>
<pre><code>m <- matrix(1:4, 2)
m
prop.table(m, 1)
</code></pre>
</blockquote>
<p>But, as a beginner, I do not understand what this explanation means. I've also attempted to discern its functionality from the result of the above example, but I haven't been able to make sense of it.</p>
<p>With reference to the example above, what does the <code>prop.table()</code> function do? Furthermore, what is a "marginal table"?</p> | 45,634,043 | 3 | 3 | null | 2017-08-11 11:06:09.687 UTC | 5 | 2021-06-27 06:20:16.5 UTC | 2021-06-27 06:20:16.5 UTC | null | 6,828,329 | null | 6,828,329 | null | 1 | 19 | r | 52,728 | <p>The values in each cell divided by the sum of the 4 cells:</p>
<pre><code>prop.table(m)
</code></pre>
<p>The value of each cell divided by the sum of the row cells:</p>
<pre><code>prop.table(m, 1)
</code></pre>
<p>The value of each cell divided by the sum of the column cells:</p>
<pre><code>prop.table(m, 2)
</code></pre> |
51,503,851 | Calculate the accuracy every epoch in PyTorch | <p>I am working on a Neural Network problem, to classify data as 1 or 0. I am using Binary cross entropy loss to do this. The loss is fine, however, the accuracy is very low and isn't improving. I am assuming I did a mistake in the accuracy calculation. After every epoch, I am calculating the correct predictions after thresholding the output, and dividing that number by the total number of the dataset. Is there any thing wrong I did in the accuracy calculation? And why isn't it improving, but getting more worse?
This is my code:</p>
<pre class="lang-py prettyprint-override"><code>net = Model()
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
num_epochs = 100
for epoch in range(num_epochs):
for i, (inputs,labels) in enumerate (train_loader):
inputs = Variable(inputs.float())
labels = Variable(labels.float())
output = net(inputs)
optimizer.zero_grad()
loss = criterion(output, labels)
loss.backward()
optimizer.step()
#Accuracy
output = (output>0.5).float()
correct = (output == labels).float().sum()
print("Epoch {}/{}, Loss: {:.3f}, Accuracy: {:.3f}".format(epoch+1,num_epochs, loss.data[0], correct/x.shape[0]))
</code></pre>
<p>And this is the strange output I get:</p>
<pre><code>Epoch 1/100, Loss: 0.389, Accuracy: 0.035
Epoch 2/100, Loss: 0.370, Accuracy: 0.036
Epoch 3/100, Loss: 0.514, Accuracy: 0.030
Epoch 4/100, Loss: 0.539, Accuracy: 0.030
Epoch 5/100, Loss: 0.583, Accuracy: 0.029
Epoch 6/100, Loss: 0.439, Accuracy: 0.031
Epoch 7/100, Loss: 0.429, Accuracy: 0.034
Epoch 8/100, Loss: 0.408, Accuracy: 0.035
Epoch 9/100, Loss: 0.316, Accuracy: 0.035
Epoch 10/100, Loss: 0.436, Accuracy: 0.035
Epoch 11/100, Loss: 0.365, Accuracy: 0.034
Epoch 12/100, Loss: 0.485, Accuracy: 0.031
Epoch 13/100, Loss: 0.392, Accuracy: 0.033
Epoch 14/100, Loss: 0.494, Accuracy: 0.030
Epoch 15/100, Loss: 0.369, Accuracy: 0.035
Epoch 16/100, Loss: 0.495, Accuracy: 0.029
Epoch 17/100, Loss: 0.415, Accuracy: 0.034
Epoch 18/100, Loss: 0.410, Accuracy: 0.035
Epoch 19/100, Loss: 0.282, Accuracy: 0.038
Epoch 20/100, Loss: 0.499, Accuracy: 0.031
Epoch 21/100, Loss: 0.446, Accuracy: 0.030
Epoch 22/100, Loss: 0.585, Accuracy: 0.026
Epoch 23/100, Loss: 0.419, Accuracy: 0.035
Epoch 24/100, Loss: 0.492, Accuracy: 0.031
Epoch 25/100, Loss: 0.537, Accuracy: 0.031
Epoch 26/100, Loss: 0.439, Accuracy: 0.033
Epoch 27/100, Loss: 0.421, Accuracy: 0.035
Epoch 28/100, Loss: 0.532, Accuracy: 0.034
Epoch 29/100, Loss: 0.234, Accuracy: 0.038
Epoch 30/100, Loss: 0.492, Accuracy: 0.027
Epoch 31/100, Loss: 0.407, Accuracy: 0.035
Epoch 32/100, Loss: 0.305, Accuracy: 0.038
Epoch 33/100, Loss: 0.663, Accuracy: 0.025
Epoch 34/100, Loss: 0.588, Accuracy: 0.031
Epoch 35/100, Loss: 0.329, Accuracy: 0.035
Epoch 36/100, Loss: 0.474, Accuracy: 0.033
Epoch 37/100, Loss: 0.535, Accuracy: 0.031
Epoch 38/100, Loss: 0.406, Accuracy: 0.033
Epoch 39/100, Loss: 0.513, Accuracy: 0.030
Epoch 40/100, Loss: 0.593, Accuracy: 0.030
Epoch 41/100, Loss: 0.265, Accuracy: 0.036
Epoch 42/100, Loss: 0.576, Accuracy: 0.031
Epoch 43/100, Loss: 0.565, Accuracy: 0.027
Epoch 44/100, Loss: 0.576, Accuracy: 0.030
Epoch 45/100, Loss: 0.396, Accuracy: 0.035
Epoch 46/100, Loss: 0.423, Accuracy: 0.034
Epoch 47/100, Loss: 0.489, Accuracy: 0.033
Epoch 48/100, Loss: 0.591, Accuracy: 0.029
Epoch 49/100, Loss: 0.415, Accuracy: 0.034
Epoch 50/100, Loss: 0.291, Accuracy: 0.039
Epoch 51/100, Loss: 0.395, Accuracy: 0.033
Epoch 52/100, Loss: 0.540, Accuracy: 0.026
Epoch 53/100, Loss: 0.436, Accuracy: 0.033
Epoch 54/100, Loss: 0.346, Accuracy: 0.036
Epoch 55/100, Loss: 0.519, Accuracy: 0.029
Epoch 56/100, Loss: 0.456, Accuracy: 0.031
Epoch 57/100, Loss: 0.425, Accuracy: 0.035
Epoch 58/100, Loss: 0.311, Accuracy: 0.039
Epoch 59/100, Loss: 0.406, Accuracy: 0.034
Epoch 60/100, Loss: 0.360, Accuracy: 0.035
Epoch 61/100, Loss: 0.476, Accuracy: 0.030
Epoch 62/100, Loss: 0.404, Accuracy: 0.034
Epoch 63/100, Loss: 0.382, Accuracy: 0.036
Epoch 64/100, Loss: 0.538, Accuracy: 0.031
Epoch 65/100, Loss: 0.392, Accuracy: 0.034
Epoch 66/100, Loss: 0.434, Accuracy: 0.033
Epoch 67/100, Loss: 0.479, Accuracy: 0.031
Epoch 68/100, Loss: 0.494, Accuracy: 0.031
Epoch 69/100, Loss: 0.415, Accuracy: 0.034
Epoch 70/100, Loss: 0.390, Accuracy: 0.036
Epoch 71/100, Loss: 0.330, Accuracy: 0.038
Epoch 72/100, Loss: 0.449, Accuracy: 0.030
Epoch 73/100, Loss: 0.315, Accuracy: 0.039
Epoch 74/100, Loss: 0.450, Accuracy: 0.031
Epoch 75/100, Loss: 0.562, Accuracy: 0.030
Epoch 76/100, Loss: 0.447, Accuracy: 0.031
Epoch 77/100, Loss: 0.408, Accuracy: 0.038
Epoch 78/100, Loss: 0.359, Accuracy: 0.034
Epoch 79/100, Loss: 0.372, Accuracy: 0.035
Epoch 80/100, Loss: 0.452, Accuracy: 0.034
Epoch 81/100, Loss: 0.360, Accuracy: 0.035
Epoch 82/100, Loss: 0.453, Accuracy: 0.031
Epoch 83/100, Loss: 0.578, Accuracy: 0.030
Epoch 84/100, Loss: 0.537, Accuracy: 0.030
Epoch 85/100, Loss: 0.483, Accuracy: 0.035
Epoch 86/100, Loss: 0.343, Accuracy: 0.036
Epoch 87/100, Loss: 0.439, Accuracy: 0.034
Epoch 88/100, Loss: 0.686, Accuracy: 0.023
Epoch 89/100, Loss: 0.265, Accuracy: 0.039
Epoch 90/100, Loss: 0.369, Accuracy: 0.035
Epoch 91/100, Loss: 0.521, Accuracy: 0.027
Epoch 92/100, Loss: 0.662, Accuracy: 0.027
Epoch 93/100, Loss: 0.581, Accuracy: 0.029
Epoch 94/100, Loss: 0.322, Accuracy: 0.034
Epoch 95/100, Loss: 0.375, Accuracy: 0.035
Epoch 96/100, Loss: 0.575, Accuracy: 0.031
Epoch 97/100, Loss: 0.489, Accuracy: 0.030
Epoch 98/100, Loss: 0.435, Accuracy: 0.033
Epoch 99/100, Loss: 0.440, Accuracy: 0.031
Epoch 100/100, Loss: 0.444, Accuracy: 0.033
</code></pre> | 51,664,637 | 10 | 8 | null | 2018-07-24 16:49:36.687 UTC | 5 | 2022-09-20 08:17:23.15 UTC | 2022-01-27 17:24:19.547 UTC | null | 3,867,406 | null | 9,109,354 | null | 1 | 23 | python|neural-network|pytorch | 85,129 | <p>Is <code>x</code> the entire input dataset? If so, you might be dividing by the size of the entire input dataset in <code>correct/x.shape[0]</code> (as opposed to the size of the mini-batch). Try changing this to <code>correct/output.shape[0]</code></p> |
15,991,561 | Intelli J IDEA takes forever to update indices | <p>Is it normal for Intelli J to take a lot of time (almost 12 hours) to update indices for a project? I just installed Intelli J on my machine and imported a rather large Maven project (13k+ files). </p>
<p>I understand that the project is large but I let my computer up all night and when I woke up in the morning, Intelli J still hasn't finished updating the indices for the files yet, which makes it impossible to do anything since the popup with title 'Updating Index' keep hanging there in the middle of the screen.</p> | 23,005,286 | 14 | 5 | null | 2013-04-13 18:48:49.453 UTC | 45 | 2022-08-05 05:45:05.353 UTC | 2017-08-25 17:16:08.587 UTC | null | 1,031,797 | null | 1,031,797 | null | 1 | 167 | maven|ide|intellij-idea|indexing | 128,651 | <p>There are several answers in the Forums for different IntelliJ Versions, here is what I´ve tried (IntelliJ 13).</p>
<ul>
<li>Give more Memory. Does not help anything with the 'Updating indices'</li>
<li>Delete .idea and iml in project. Does not help.</li>
</ul>
<p>In the end what resolved my problem with 'Updating indices' was:</p>
<ul>
<li>delete 'caches' folder in user/.IntellIJIdea13/system/ </li>
</ul> |
33,037,559 | Spring REST security - Secure different URLs differently | <p>I have working REST API under Spring 4 using Basic authentication. These REST services are under /api/v1/** URL. However, I want to add another set of REST endpoints under different url /api/v2/**, but protected with token-based authentication.</p>
<p>Is it possible to do this with one servlet ? How to configure Spring Security to use different forms of authentication for different URLs ?</p>
<p>Thank you.</p> | 33,039,767 | 1 | 6 | null | 2015-10-09 11:50:38.64 UTC | 12 | 2015-10-09 13:38:47.213 UTC | null | null | null | user1930502 | null | null | 1 | 15 | java|spring|rest|spring-mvc|spring-security | 17,438 | <p>Here's a code sample in Java config that uses <code>UserDetailsService</code> and has different security configurations for different URL endpoints:</p>
<pre><code>@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Configuration
@Order(1)
public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/v1/**")
.httpBasic()
.realmName("API")
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/v1/**").authenticated();
}
}
@Configuration
@Order(2)
public static class ApiTokenSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/v2/**")
/* other config options go here... */
}
}
}
</code></pre> |
32,923,605 | Is there a way to get the index of the median in python in one command? | <p>Is there something like <code>numpy.argmin(x)</code>, but for median?</p> | 38,253,918 | 6 | 7 | null | 2015-10-03 14:21:59.48 UTC | 2 | 2021-03-09 06:38:08.003 UTC | 2015-10-03 14:36:20.887 UTC | null | 5,403,928 | null | 5,403,928 | null | 1 | 30 | python|math|numpy | 24,605 | <p>a quick approximation:</p>
<pre><code>numpy.argsort(data)[len(data)//2]
</code></pre> |
10,325,599 | Delete all branches that are more than X days/weeks old | <p>I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?</p>
<pre><code>for k in $(git branch | sed /\*/d); do
echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
</code></pre> | 10,325,758 | 14 | 3 | null | 2012-04-26 00:15:14.78 UTC | 20 | 2022-01-21 13:36:02.69 UTC | 2015-11-07 03:25:17.133 UTC | null | 45,375 | null | 200,295 | null | 1 | 67 | git|shell | 42,811 | <p>How about using <code>--since</code> and <code>--before</code>?</p>
<p>For example, this will delete all branches that have not received any commits for a week:</p>
<pre><code>for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --since='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
</code></pre>
<p>If you want to delete all branches that are more than a week old, use <code>--before</code>:</p>
<pre><code>for k in $(git branch | sed /\*/d); do
if [ -z "$(git log -1 --before='1 week ago' -s $k)" ]; then
git branch -D $k
fi
done
</code></pre>
<p>Be warned though that this will also delete branches that where not merged into master or whatever the checked out branch is.</p> |
10,284,299 | Xcode only lets me run for an iOS device (no simulator) | <p>I just cloned a project into Xcode and am trying to run it in the simulator. However, my only option is iOS Device. This is unique to this project only and I don't know how to fix it. Anyone else run into this and know how to fix it?</p>
<p><img src="https://imgur.com/lhO0Z.png" alt="screenshot"></p> | 10,865,018 | 19 | 4 | null | 2012-04-23 16:18:05.777 UTC | 10 | 2018-02-12 06:56:08.47 UTC | 2012-04-23 16:25:27.9 UTC | null | 128,595 | null | 835,868 | null | 1 | 68 | xcode|simulator | 71,581 | <p>Under Your project Build Settings</p>
<ol>
<li>select Deployment section</li>
<li>change iOS Deployment Target to a version iOS 5.0 or less</li>
<li>now you can go ahead and change the deployment target from device to simulator!</li>
</ol>
<p>In my case the deployment target was set to version 5.1 and i still am running snow leapord OS with appropriate JARS copied from xcode 4.3 to make it run with a device running iOS 5.1.</p>
<p>However, my simulators do not yet support version 5.1 so till i changed the deployment target to lower version e.g. 5.0 or 4.2 it won't let me run on simulator.</p> |
46,408,051 | python json load set encoding to utf-8 | <p>I have this code:</p>
<pre><code>keys_file = open("keys.json")
keys = keys_file.read().encode('utf-8')
keys_json = json.loads(keys)
print(keys_json)
</code></pre>
<p>There are some none-english characters in keys.json.
But as a result I get:</p>
<pre><code>[{'category': 'мбт', 'keys': ['Блендер Philips',
'мультиварка Polaris']}, {'category': 'КБТ', 'keys':
['холод ильник атлант', 'посудомоечная
машина Bosch']}]
</code></pre>
<p>what do I do?</p> | 46,408,435 | 1 | 12 | null | 2017-09-25 14:44:39.373 UTC | 7 | 2017-09-25 15:03:09.137 UTC | 2017-09-25 14:56:59.063 UTC | null | 2,950,593 | null | 2,950,593 | null | 1 | 50 | python|python-3.x | 137,732 | <p><code>encode</code> means <em>characters to binary</em>. What you want when <em>reading</em> a file is <em>binary to characters</em> → <code>decode</code>. But really this entire process is way too manual, simply do this:</p>
<pre><code>with open('keys.json', encoding='utf-8') as fh:
data = json.load(fh)
print(data)
</code></pre>
<p><code>with</code> handles the correct opening and closing of the file, the <code>encoding</code> argument to <code>open</code> ensures the file is read using the correct encoding, and the <code>load</code> call reads directly from the file handle instead of storing a copy of the file contents in memory first.</p>
<p>If this still outputs invalid characters, it means your source encoding isn't UTF-8 or your console/terminal doesn't handle UTF-8.</p> |
10,402,241 | C++11 move constructor | <p><br/>
What would be the correct way to implement a move constructor considering the following class:</p>
<pre><code>class C {
public:
C();
C(C&& c);
private:
std::string string;
}
</code></pre>
<p>Of course, the idea is to avoid copying <code>string</code> or deallocating it twice.<br/>
Lets assume the basic example is just for clarity and I do need a move constructor.<p>
<br/>I tried:</p>
<pre><code>C::C(C&& c) {
//move ctor
string = std::move(c.string);
}
</code></pre>
<p>And</p>
<pre><code>C::C(C&& c) : string(std::move(c.string)) {
//move ctor
}
</code></pre>
<p>Both compile fine on gcc 4.8 and run fine. It <em>seems</em> option A is the correct behaviour, <code>string</code> gets copied instead of moved with option B.<br/>
Is this the correct implementation of a move constructor?</p> | 10,402,308 | 4 | 9 | null | 2012-05-01 18:22:14.43 UTC | 12 | 2018-03-28 09:07:18.92 UTC | 2012-05-01 18:30:29.137 UTC | null | 642,681 | null | 642,681 | null | 1 | 26 | c++|c++11|move-semantics | 11,364 | <p>Since <code>std::string</code> itself has a move-ctor, the implicitly defined move-ctor for <code>C</code> will take care of the proper move operation. You may not define it yourself. However, if you have any other data member and specifically:</p>
<blockquote>
<p><strong>12.8 Copying and moving class objects</strong></p>
<p><strong>12</strong> An implicitly-declared copy/move constructor is an inline public
member of its class. A defaulted copy- /move constructor for a class X
is defined as deleted (8.4.3) if X has:</p>
<p>— a variant member with a
non-trivial corresponding constructor and X is a union-like class,</p>
<p>— a
non-static data member of class type M (or array thereof) that cannot
be copied/moved because overload resolution (13.3), as applied to M’s
corresponding constructor, results in an ambiguity or a function that
is deleted or inaccessible from the defaulted constructor, or</p>
<p>— a
direct or virtual base class B that cannot be copied/moved because
overload resolution (13.3), as applied to B’s corresponding
constructor, results in an ambiguity or a function that is deleted or
inaccessible from the defaulted constructor, or</p>
<p>— for the move
constructor, a non-static data member or direct or virtual base class
with a type that does not have a move constructor and is not trivially
copyable.</p>
<p><strong>13</strong> A copy/move constructor for class X is trivial if it is
neither user-provided nor deleted and if</p>
<p>— class X has no virtual functions (10.3) and no virtual base classes (10.1), and
functions (10.3) and no virtual base classes (10.1), and</p>
<p>— the
constructor selected to copy/move each direct base class subobject is
trivial, and</p>
<p>— for each non-static data member of X that is of class
type (or array thereof), the constructor selected to copy/move that
member is trivial; otherwise the copy/move constructor is non-trivial.</p>
</blockquote>
<p>you may want to implement your own move-ctor.</p>
<p>In case you need the move-ctor, prefer the initializer list syntax. Always! Otherwise, you may end up with a default construction per object not mentioned in the initializer list (which is what you're forced for member objects with non-default ctors only).</p> |
37,955,942 | Vagrant up - VBoxManage.exe error: VT-x is not available (VERR_VMX_NO_VMX) code E_FAIL (0x80004005) gui headless | <p>Machine: Window10 (64bit).</p>
<p>I downloaded the latest VirtualBox, Vagrant and initialized CentOS 6.7 64bit image/url.</p>
<p>The following worked successfully in Git-Bash session.<br/>
1. vagrant box add "centos67x64" "<a href="https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box" rel="noreferrer">https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box</a>"<br/>
2. vagrant init<br/>
3. Updated Vagrantfile (and turned vb.gui option i.e. uncommented that config section in the file).</p>
<pre><code> config.vm.provider "virtualbox" do |vb|
# Display the VirtualBox GUI when booting the machine
vb.gui = true
# Customize the amount of memory on the VM:
vb.memory = "2048"
end
</code></pre>
<p>After that, I tried the following command but I'm getting this error message.</p>
<pre><code>$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos67x64'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vv_default_1466548735200_80300
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["startvm", "ae74ebaa-8f01-48cf-bdad-956c59ef1208", "--type", "gui"]
Stderr: VBoxManage.exe: error: VT-x is not available (VERR_VMX_NO_VMX)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
</code></pre>
<p>If I turn/comment off the whole Vagrantfile respective section, I'm still getting the following error.</p>
<pre><code>$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
default: Adapter 1: nat
==> default: Forwarding ports...
default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
There was an error while executing `VBoxManage`, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["startvm", "ae74ebaa-8f01-48cf-bdad-956c59ef1208", "--type", "headless"]
Stderr: VBoxManage.exe: error: VT-x is not available (VERR_VMX_NO_VMX)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
</code></pre>
<p>Any ideas! I looked into other posts but couldn't find how to resolve in my case.</p>
<p>As I got some hints, I tried one of the solution.</p>
<ol>
<li>TURN off the Hyper-V which is turned of by default I guess in Windows10.</li>
<li><p>To do this, I Went to Control panel in Windows10 and looked here and found this.
<a href="https://i.stack.imgur.com/cTDpO.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cTDpO.jpg" alt="enter image description here"></a></p></li>
<li><p>Then, I turned Hyper-V off by unchecking (the tick mark, or black box). </p></li>
<li>Windows10 told me to RESTART, I said "No" (later).</li>
<li><p>Tried running "vagrant up" again (without or without any changes or the above mentioned config.vm... changes to the Vagrantfile). It didn't work and gave me the same --headless error message.</p></li>
<li><p>OK, time to restart. Restarted Windows10. After the restart, I saw bunch of Virtual Box error messages popups (few of them are shown below).</p></li>
</ol>
<p><a href="https://i.stack.imgur.com/uhIaf.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/uhIaf.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/xnlRu.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xnlRu.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/5qyWV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5qyWV.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/zms5k.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zms5k.jpg" alt="enter image description here"></a></p>
<ol start="7">
<li>Once I clicked on OK button on all of those Virtual Box popup windows, I tried to run Virtual Box on my machine, it came up fine(successfully).</li>
<li>Now, I opened Git-BASH and again went to the directory where Vagrantfile was present. Tried tweaking the settings on / off or commenting/uncommenting the Vagrantfile respective section (as I described above). </li>
</ol>
<p><strong>STILL</strong> getting the the same error messages for running "vagrant up" (even after turning the Hyper-V off as well).</p> | 38,111,013 | 13 | 10 | null | 2016-06-21 23:00:42.507 UTC | 16 | 2020-08-20 19:27:57.853 UTC | 2016-06-21 23:44:24.043 UTC | null | 1,499,296 | null | 1,499,296 | null | 1 | 44 | vagrant|windows-10|virtualbox|vagrantfile|headless | 110,935 | <p>Stop hyper-v service running by default in Windows 8/10, since it blocks all other calls to VT hardware.</p>
<p>Additional explanation here:
<a href="https://social.technet.microsoft.com/Forums/windows/en-US/118561b9-7155-46e3-a874-6a38b35c67fd/hyperv-disables-vtx-for-other-hypervisors?forum=w8itprogeneral" rel="noreferrer">https://social.technet.microsoft.com/Forums/windows/en-US/118561b9-7155-46e3-a874-6a38b35c67fd/hyperv-disables-vtx-for-other-hypervisors?forum=w8itprogeneral</a></p>
<p>Also as you have mentioned, if not already enabled, turn on Intel VT virtualization in BIOS settings and restart the machine.</p>
<hr>
<p>To turn Hypervisor off, run this from Command Prompt (Admin) (<kbd>Windows</kbd>+<kbd>X</kbd>):</p>
<pre><code>bcdedit /set hypervisorlaunchtype off
</code></pre>
<p>and reboot your computer. To turn it back on again, run:</p>
<pre><code>bcdedit /set hypervisorlaunchtype on
</code></pre>
<p>If you receive "The integer data is not valid as specified", try:</p>
<pre><code>bcdedit /set hypervisorlaunchtype auto
</code></pre>
<p>-- credit <a href="https://stackoverflow.com/users/54055/tj-kellie">Tj Kellie</a></p> |
37,629,745 | Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)? | <p><strong>MY ENVIRONMENT (WHERE I GET THE LAG):</strong></p>
<p>Mac OSX El Capitan 10.11.2 on Chrome Version 50.0.2661.102 (64-bit)</p>
<p><strong>CODEPEN:</strong></p>
<p><a href="http://codepen.io/vieron/pen/hnEev" rel="noreferrer">http://codepen.io/vieron/pen/hnEev</a></p>
<hr>
<p><strong>ANIMATION:</strong></p>
<p><a href="https://i.stack.imgur.com/J2ZoE.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/J2ZoE.gif" alt="enter image description here"></a></p>
<hr>
<p><strong>SITUATION:</strong></p>
<p>I googled this a lot without finding anything that works for me. I know this questions has been asked before.</p>
<p>The CSS3 animation is smooth on my Mac when I open the website with Safari and Firefox, but not with Chrome!</p>
<p>Strangely enough, the original CodePen is smooth on Chrome.</p>
<hr>
<p><strong>PROBLEM:</strong></p>
<p>Something in my code is causing the animation to be choppy only on Chrome. What is it and how can I fix it ?</p>
<hr>
<p><strong>WHAT I LOOKED AT:</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/17754561/chrome-css-3-transition-not-smooth">Chrome CSS 3 Transition Not Smooth</a></li>
</ul>
<p>I need my positioning to be relative to adapt to different screen sizes.</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/14418359/css3-transition-not-smooth-in-chrome">CSS3 transition not smooth in Chrome</a></p></li>
<li><p><a href="http://blog.teamtreehouse.com/create-smoother-animations-transitions-browser" rel="noreferrer">http://blog.teamtreehouse.com/create-smoother-animations-transitions-browser</a></p></li>
<li><p><a href="https://www.binarymoon.co.uk/2014/02/fixing-css-transitions-in-google-chrome/" rel="noreferrer">https://www.binarymoon.co.uk/2014/02/fixing-css-transitions-in-google-chrome/</a></p></li>
<li><p><a href="http://blog.teamtreehouse.com/create-smoother-animations-transitions-browser" rel="noreferrer">http://blog.teamtreehouse.com/create-smoother-animations-transitions-browser</a></p></li>
</ul>
<hr>
<p><strong>CODE:</strong></p>
<p>HTML</p>
<pre><code><div class="marquee">
<ul>
<li>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
</li>
<li>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
</li>
<li>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
<a href="https://developer.apple.com/swift/"><img class="marquee-itm" src="Vendors/Images/Apple_Swift_Logo.png" /></a>
<a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html"><img class="marquee-itm" src="Vendors/Images/Objective-c-logo.png" /></a>
</li>
</ul>
</div>
</code></pre>
<p>CSS</p>
<pre><code>* {
margin: 0;
padding: 0;
}
@-webkit-keyframes loop {
0% {
-moz-transform: translateX(0);
-ms-transform: translateX(0);
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-moz-transform: translateX(-66.6%);
-ms-transform: translateX(-66.6%);
-webkit-transform: translateX(-66.6%);
transform: translateX(-66.6%);
}
}
@-moz-keyframes loop {
0% {
-moz-transform: translateX(0);
-ms-transform: translateX(0);
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-moz-transform: translateX(-66.6%);
-ms-transform: translateX(-66.6%);
-webkit-transform: translateX(-66.6%);
transform: translateX(-66.6%);
}
}
@-ms-keyframes loop {
0% {
-moz-transform: translateX(0);
-ms-transform: translateX(0);
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-moz-transform: translateX(-66.6%);
-ms-transform: translateX(-66.6%);
-webkit-transform: translateX(-66.6%);
transform: translateX(-66.6%);
}
}
@keyframes loop {
0% {
-moz-transform: translateX(0);
-ms-transform: translateX(0);
-webkit-transform: translateX(0);
transform: translateX(0);
}
100% {
-moz-transform: translateX(-66.6%);
-ms-transform: translateX(-66.6%);
-webkit-transform: translateX(-66.6%);
transform: translateX(-66.6%);
}
}
.cssanimations .marquee {
position: relative;
width: 90%;
margin: auto;
overflow: hidden;
}
.cssanimations .marquee > ul {
list-style: none;
position: relative;
z-index: 1;
top: 0;
left: 0;
width: 300% !important;
height: 80px;
-webkit-animation-play-state: running;
-moz-animation-play-state: running;
-o-animation-play-state: running;
animation-play-state: running;
-moz-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
-webkit-animation: loop 20s linear infinite;
-moz-animation: loop 20s linear infinite;
-o-animation: loop 20s linear infinite;
animation: loop 20s linear infinite;
}
.cssanimations .marquee > ul > li {
white-space: normal;
position: relative;
text-align: justify;
text-justify: distribute-all-lines;
line-height: 0;
letter-spacing: -0.31em;
float: left;
width: 33.333333%;
overflow: hidden;
height: 80px;
}
.cssanimations .marquee > ul > li:before {
content: '';
position: relative;
height: 100%;
width: 0;
}
.cssanimations .marquee > ul > li:before,
.cssanimations .marquee > ul > li > * {
vertical-align: middle;
display: inline-block;
}
.cssanimations .marquee > ul > li:after {
content: '.';
display: inline-block;
height: 0 !important;
width: 100%;
overflow: hidden !important;
visibility: hidden;
font-size: 0;
word-spacing: 100%;
}
.cssanimations .marquee > ul > li > * {
display: inline-block;
vertical-align: middle;
text-align: left;
line-height: 1;
letter-spacing: 0;
}
.cssanimations .marquee > ul > li img {
margin: 0 1.6%;
}
.marquee ul li a{
display: inline-block;
height: 80%;
}
.marquee ul li a img {
max-height: 100%;
}
</code></pre>
<p>JS LINKS IN THE HTML</p>
<pre><code><script src="Vendors/js/modernizr.js" type="text/javascript"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
</code></pre>
<hr>
<p><strong>IMPORTANT N.B.:</strong></p>
<p>Only thing I added to the CodePen:</p>
<pre><code>.marquee ul li a{
display: inline-block;
height: 80%;
}
.marquee ul li a img {
max-height: 100%;
}
</code></pre>
<p>Removing this doesn't solve the issue.</p>
<hr>
<p><strong>EDIT 1:</strong></p>
<p>Google Chrome Profiler (option 1):</p>
<p><a href="https://i.stack.imgur.com/WCpqX.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/WCpqX.gif" alt="enter image description here"></a></p>
<p>Google Chrome Profiler (option 2 (Snapshot)):</p>
<p><a href="https://i.stack.imgur.com/q4pjj.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/q4pjj.gif" alt="enter image description here"></a></p>
<p><strong>EDIT 2:</strong></p>
<p><a href="https://stackoverflow.com/questions/14418359/css3-transition-not-smooth-in-chrome">CSS3 transition not smooth in Chrome</a></p>
<p>I seem to have just found a strange behaviour in my animation. It "grows" (gets larger) every time I move out of sight and back on it by scrolling.</p>
<p>This behaviour seems to be what is described in the answer to the question above. But specifying a fixed width like suggested didn't fix the lag.</p>
<p><strong>EDIT 3:</strong></p>
<p>Google Timeline (after removing gravity.js):</p>
<p><a href="https://i.stack.imgur.com/lTLfc.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/lTLfc.gif" alt="enter image description here"></a></p>
<p><strong>EDIT 4:</strong></p>
<p>This is weird. After commenting and uncommenting some lines (basically going back to what the code was when there was lag), the animation performance became better. Not as smooth as in Safari or Firefox, but still smoother.</p>
<p><strong>EDIT 5:</strong></p>
<p>I found the "culprit".</p>
<p>I am using another codepen in my website's header :</p>
<p><a href="https://codepen.io/saransh/pen/BKJun" rel="noreferrer">https://codepen.io/saransh/pen/BKJun</a></p>
<pre><code><link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
#stars
#stars2
#stars3
#title
%span
PURE CSS
%br
%span
PARALLAX PIXEL STARS
</code></pre>
<p>Removing it makes the other animation smooth.</p>
<hr>
<p><strong>NONETHELESS:</strong></p>
<p>This doesn't explain why everything is smooth in Firefox and Safari but not in Chrome.</p>
<p>Is Chrome less powerful ?</p>
<p>I filed a report to Chrome and hope they will answer here but there is no guarantee.</p>
<p>If someone can get an answer from Google / Chrome on this, I award him/her the bounty.</p>
<hr>
<p><strong>UPDATE 6:</strong></p>
<p>Tried on the Opera browser. Exactly the same lag ! Now we know it's a problem with the BLINK rendering engine !</p> | 37,793,921 | 7 | 89 | null | 2016-06-04 11:37:34.097 UTC | 11 | 2022-05-18 22:25:39.437 UTC | 2018-03-21 21:05:43.54 UTC | null | 1,081,234 | null | 6,230,185 | null | 1 | 68 | html|css|google-chrome|animation | 40,066 | <p>I found the "culprit".</p>
<p>I am using another codepen in my website's header :</p>
<p><a href="https://codepen.io/saransh/pen/BKJun" rel="nofollow">https://codepen.io/saransh/pen/BKJun</a></p>
<pre><code><link href='http://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'>
#stars
#stars2
#stars3
#title
%span
PURE CSS
%br
%span
PARALLAX PIXEL STARS
</code></pre>
<p>Removing it makes the other animation smooth.</p>
<hr>
<p><strong>NONETHELESS:</strong></p>
<p>This doesn't explain why everything is smooth in Firefox and Safari but not in Chrome.</p>
<p>Is Chrome less powerful ?</p>
<p>I filed a report to Chrome and hope they will answer here but there is no guarantee.</p>
<p>If someone can get an answer from Google / Chrome on this, I award him/her the bounty.</p>
<p><strong>UPDATE 6:</strong></p>
<p>Tried on the Opera browser. Exactly the same lag ! Now we know it's a problem with the BLINK rendering engine !</p> |
33,749,543 | Unique 4 digit random number in C# | <p>I want to generate an unique 4 digit random number. This is the below code what I have tried:</p>
<p><strong>Code for generating random number</strong></p>
<pre><code>//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 0000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
</code></pre>
<p>The problem is I have received a random no with value <code>241</code> which is not a 4 digit number. Is there any problems with the code?</p> | 33,749,592 | 13 | 6 | null | 2015-11-17 05:05:25.153 UTC | 3 | 2021-02-04 15:10:50.863 UTC | 2018-08-14 19:00:16.927 UTC | null | 271,200 | null | 958,396 | null | 1 | 25 | c#|random | 67,713 | <pre><code>//Generate RandomNo
public int GenerateRandomNo()
{
int _min = 1000;
int _max = 9999;
Random _rdm = new Random();
return _rdm.Next(_min, _max);
}
</code></pre>
<p>you need a 4 digit code, start with 1000</p> |
53,203,254 | failed to open stream: No such file or directory (Laravel) | <p>I renamed my <code>UsersController.php</code> file to <code>~UsersController.php</code> for testing purposes and everything was working fine until I renamed it back to <code>UsersController.php</code> and now I'm getting the below error</p>
<blockquote>
<p><code>include(C:\xampp\htdocs\xxx\vendor\composer/../../app/Http/Controllers/~UsersController.php):
failed to open stream: No such file or directory</code></p>
</blockquote>
<p>i'm getting the above error when I want submit form to <code>UsersController</code> while I didn't change anything in my route file or views.</p> | 53,203,486 | 6 | 3 | null | 2018-11-08 07:41:26.587 UTC | 8 | 2022-09-09 05:42:07.167 UTC | 2018-11-08 08:10:31.623 UTC | null | 7,051,937 | null | 10,114,756 | null | 1 | 25 | laravel|controller | 80,852 | <p>Try
<code>php artisan config:cache && php artisan config:clear && composer dump-autoload -o</code></p> |
33,422,681 | Xcode UI test - UI Testing Failure - Failed to scroll to visible (by AX action) when tap on Search field "Cancel' button | <p>I am trying to dismiss the search field by tapping 'Cancel' button in search bar.</p>
<p>The test case is failing to find the cancel button. It was working fine in Xcode 7.0.1</p>
<p>I have added predicate to wait for button to appear. The test case is failing when we tap of "cancel" button</p>
<pre><code>let button = app.buttons[“Cancel”]
let existsPredicate = NSPredicate(format: "exists == 1")
expectationForPredicate(existsPredicate, evaluatedWithObject: button, handler: nil)
waitForExpectationsWithTimeout(5, handler: nil)
button.tap() // Failing here
</code></pre>
<p><strong>logs</strong>:</p>
<pre><code> t = 7.21s Tap SearchField
t = 7.21s Wait for app to idle
t = 7.29s Find the SearchField
t = 7.29s Snapshot accessibility hierarchy for com.test.mail
t = 7.49s Find: Descendants matching type SearchField
t = 7.49s Find: Element at index 0
t = 7.49s Wait for app to idle
t = 7.55s Synthesize event
t = 7.84s Wait for app to idle
t = 8.97s Type '[email protected]' into
t = 8.97s Wait for app to idle
t = 9.03s Find the "Search" SearchField
t = 9.03s Snapshot accessibility hierarchy for com.test.mail
t = 9.35s Find: Descendants matching type SearchField
t = 9.35s Find: Element at index 0
t = 9.36s Wait for app to idle
t = 9.42s Synthesize event
t = 10.37s Wait for app to idle
t = 10.44s Check predicate `exists == 1` against object `"Cancel" Button`
t = 10.44s Snapshot accessibility hierarchy for com.test.mail
t = 10.58s Find: Descendants matching type Button
t = 10.58s Find: Elements matching predicate '"Cancel" IN identifiers'
t = 10.58s Tap "Cancel" Button
t = 10.58s Wait for app to idle
t = 10.64s Find the "Cancel" Button
t = 10.64s Snapshot accessibility hierarchy for com.test.mail
t = 10.78s Find: Descendants matching type Button
t = 10.78s Find: Elements matching predicate '"Cancel" IN identifiers'
t = 10.79s Wait for app to idle
t = 11.08s Synthesize event
t = 11.13s Scroll element to visible
t = 11.14s Assertion Failure: UI Testing Failure - Failed to scroll to visible (by AX action) Button 0x7f7fcaebde40: traits: 8589934593, {{353.0, 26.0}, {53.0, 30.0}}, label: 'Cancel', error: Error -25204 performing AXAction 2003
</code></pre> | 33,534,187 | 9 | 7 | null | 2015-10-29 19:10:24.4 UTC | 28 | 2021-11-25 18:25:55.287 UTC | null | null | null | null | 1,146,013 | null | 1 | 96 | xcode|xcode7|xcode-ui-testing | 31,533 | <p>I guess here "Cancel" button returns <code>false</code> for <code>hittable</code> property, that is preventing it from tapping.</p>
<p>If you see <code>tap()</code> in documentation it says</p>
<pre><code>/*!
* Sends a tap event to a hittable point computed for the element.
*/
- (void)tap;
</code></pre>
<p>It seems things are broken with Xcode 7.1. To keep myself (and you too ;)) unblocked from these issues I wrote an extension on <code>XCUIElement</code> that allows tap on an element even if it is not hittable. Following can help you.</p>
<pre><code>/*Sends a tap event to a hittable/unhittable element.*/
extension XCUIElement {
func forceTapElement() {
if self.hittable {
self.tap()
}
else {
let coordinate: XCUICoordinate = self.coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
coordinate.tap()
}
}
}
</code></pre>
<p>Now you can call as</p>
<pre><code>button.forceTapElement()
</code></pre>
<p><strong>Update</strong> - For Swift 3 use the following:</p>
<pre><code>extension XCUIElement {
func forceTapElement() {
if self.isHittable {
self.tap()
}
else {
let coordinate: XCUICoordinate = self.coordinate(withNormalizedOffset: CGVector(dx:0.0, dy:0.0))
coordinate.tap()
}
}
}
</code></pre> |
13,280,179 | ASP.NET Web API Architecture Suggestion/Feedback | <p>Currently I am faced with the requirement building an web service that will let a java client retrieve and trigger actions on our data through httprequest. We are a .Net shop it appears the latest solution for this is Microsoft's MVC4 Web API. I am used to your standard tiered architecture I have pulled data from API's but this will be my first web service supplying data. </p>
<p>From my studies I have seen suggestions as follows:</p>
<ul>
<li>Separating the logic and data access into a separate project type class library. </li>
<li>Using your Controls to access data and perform logic. </li>
<li>Using your Model to access data and perform logic. </li>
</ul>
<p>I am looking for someone who has experience with MVC4 Web API who can shed some light on good practices for building a web service in this way. </p>
<p>Thanks in advance. </p> | 13,285,693 | 1 | 4 | null | 2012-11-07 23:37:05.577 UTC | 10 | 2015-05-09 15:18:13.55 UTC | 2015-05-09 15:18:13.55 UTC | null | 463,785 | null | 1,807,669 | null | 1 | 6 | asp.net-mvc-4|asp.net-web-api | 3,194 | <p>First of all, do put your ASP.NET Web API logic into a separate project. This will give you flexibility over hosting layer (as ASP.NET Web API is hosting agnostic) and it just makes the whole project clean. Let's say your project's name is MyProject. You can name the API project as <code>MyProject.API</code> and you can install the <code>Microsoft.AspNet.WebApi.Core</code> NuGet package into this project.</p>
<p>I also suggest you to separate your domain layer as well (POCO entities, repositories, your service layer pieces, etc.). Let's call this <code>MyProject.Domain</code>. Then, you would reference this <code>MyProject.Domain</code> project from the <code>MyProject.API</code>project. </p>
<p>I wouldn't recommend you to dump all your POCO entities into your API. So, I would definately work with Data Transfer Objects (Dto). You can use a 3rd party tool like autoMapper to map your entity classes to your Dtos. However, do put your Dtos, Request Commands, Request Models into a separate project. You would reference <code>MyProject.API.Model</code> project from <code>MyProject.API</code> project. Why do we create a separate project for this? Because, later if you decide to build a .NET client wrapper for your HTTP API, you can easily reference this project to use those with your .NET client as well. Let's call this project <code>MyProject.API.Model</code>.</p>
<p>Lastly, we need a hosting layer for our API. Asumming that you would like to host this project under ASP.NET, you can create a new project through the Empty Web Application template and let's call this project <code>MyProject.API.WebHost</code>. Then, you can install the <code>Microsoft.AspNet.WebApi</code> package into this project. From this project, you would reference <code>MyProject.API</code>, <code>MyProject.API.Model</code> and <code>MyProject.Domain</code> projects. This project is the one that you should deploy to your server.</p>
<p>If you would like to create a .NET wrapper for your HTTP API, you can create another project called <code>MyProject.API.Client</code> and install <code>Microsoft.AspNet.WebApi.Client</code> package into this one. You would also reference the <code>MyProject.API.Model</code> project from this one so that you can deserialize into and serialize from strongly-typed objects.</p>
<p>Here is the screenshot of the solution explorer for the project I have been working with:</p>
<p><img src="https://i.stack.imgur.com/H6eeb.png" alt="enter image description here"></p>
<p>Hope this gives you a bit of an idea.</p> |
13,290,825 | Control ExecutorService to execute N tasks per second maximum | <p>How to control/limit the tasks that are submitted to a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" rel="noreferrer"><code>ExecutorService</code></a>? I have <code>SMSTask</code> that sends SMS messages and I need to control the executor so that it can only send at maximum N messages/second.</p> | 13,290,929 | 2 | 0 | null | 2012-11-08 14:21:40.383 UTC | 11 | 2012-11-08 15:54:22.777 UTC | null | null | null | null | 597,657 | null | 1 | 8 | java|multithreading|concurrency|executorservice | 4,346 | <p>Assuming you are creating one SMS message per task you can use a ScheduleExecutorService.</p>
<pre><code>final Queue<Task> tasks = new ConcurrentLinkedQueue<Task>();
int ratePerSecond = 10;
final ExecutorService es = Executors.newCachedThreadPool();
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
final Task task = tasks.poll();
if (task == null) return;
es.submit(new Runnable() {
@Override
public void run() {
process(task);
}
});
}
}, 0, 1000/ratePerSecond, TimeUnit.MILLISECONDS);
</code></pre>
<p>Add tasks to the queue and they will be processed at a rate of 10 per second.</p> |
13,489,473 | How can i extract only text in scrapy selector in python | <p>I have this code</p>
<pre><code> site = hxs.select("//h1[@class='state']")
log.msg(str(site[0].extract()),level=log.ERROR)
</code></pre>
<p>The ouput is</p>
<pre><code> [scrapy] ERROR: <h1 class="state"><strong>
1</strong>
<span> job containing <strong>php</strong> in <strong>region</strong> paying <strong>$30-40k per year</strong></span>
</h1>
</code></pre>
<p>Is it possible to only get the text without any html tags</p> | 13,490,664 | 5 | 0 | null | 2012-11-21 08:51:21.787 UTC | 10 | 2017-07-11 21:44:59.31 UTC | null | null | null | null | 767,244 | null | 1 | 22 | python|scrapy | 35,846 | <pre><code>//h1[@class='state']
</code></pre>
<p>in your above xpath you are selecting <code>h1</code> tag that has <code>class</code> attribute <code>state</code></p>
<p>so that's why it's selecting everything that comes in <code>h1 element</code></p>
<p>if you just want to select text of <code>h1</code> tag all you have to do is </p>
<pre><code>//h1[@class='state']/text()
</code></pre>
<p>if you want to select text of <code>h1</code> tag as well as its children tags, you have to use </p>
<pre><code>//h1[@class='state']//text()
</code></pre>
<p>so the difference is <code>/text()</code> for specific tag text and <code>//text()</code> for text of specific tag as well as its children tags </p>
<p>below mentioned code works for you</p>
<pre><code>site = ''.join(hxs.select("//h1[@class='state']/text()").extract()).strip()
</code></pre> |
13,752,715 | QUnit is only running the first test | <p>I can't get QUnit to run any test after the first. To be sure I wasn't doing something weird, I pared down the code to be as basic as possible. </p>
<pre><code>test("A", function () {
ok(true, "Test A");
});
test("B", function () {
ok(true, "Test B");
});
</code></pre>
<p>Test A is the only one that runs. No errors thrown or anything else. </p>
<p>My HTML file looks like this. </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Test title</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.10.0.css">
</head>
<body>
<div id="qunit"></div>
<script src="http://code.jquery.com/qunit/qunit-1.10.0.js"></script>
<script src="tests.js" type="text/javascript"></script>
</body>
</html>
</code></pre> | 13,753,426 | 2 | 3 | null | 2012-12-06 21:16:02.733 UTC | 1 | 2015-07-25 18:33:09.26 UTC | null | null | null | null | 168,665 | null | 1 | 28 | unit-testing|qunit | 2,215 | <p>Found the problem. It was this!</p>
<p><code>qunit.html?testNumber=1</code></p>
<p>I guess at some point I hit <code>rerun</code> and it ignored the other tests!</p>
<p>This other question deserves credit for pointing me in the right direction. <a href="https://stackoverflow.com/questions/13040167/qunit-wont-run-tests">QUnit Won't Run Tests</a></p> |
13,266,229 | HQL like operator for case insensitive search | <p>I am implementing an autocomplete functionality using Jquery, when I type the name, it fetches the record from the db, The records stored in db are mixture of capital & small letters. I have written a HQL Query which fetches me the records with case-sensitive, but I need to records irrespective of case. Here is the query,</p>
<pre><code>List<OrganizationTB> resultList = null;
Query query = session.createQuery("from DataOrganization dataOrg where dataOrg.poolName
like '%"+ poolName +"%'");
resultList = query.list();
</code></pre>
<p>Ex : If I have pool names, HRMS Data set, Hrms Data, Hr data etc... if I type HR or hr I need to get all the 3 records, which I'm not able to. </p>
<p>Please help... </p> | 13,266,410 | 2 | 0 | null | 2012-11-07 08:57:49.657 UTC | 5 | 2021-12-13 08:42:23.79 UTC | 2013-12-16 18:24:55.16 UTC | null | 1,376,473 | null | 1,799,300 | null | 1 | 28 | spring|hibernate|spring-mvc|sql-like | 43,515 | <p>change your query to </p>
<pre><code>"from DataOrganization dataOrg where lower(dataOrg.poolName)
like lower('%"+ poolName +"%')"
</code></pre>
<p>for more information have a look 14.3 <a href="http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html">doc</a></p> |
13,388,541 | PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR | <p>I got this error when debugging my code:</p>
<blockquote>
<p>PHP Parse error: syntax error, unexpected T_OBJECT_OPERATOR in order.php on line 72</p>
</blockquote>
<p>Here is a snippet of the code (starting on line 72):</p>
<pre><code>$purchaseOrder = new PurchaseOrderFactory->instance();
$arrOrderDetails = $purchaseOrder->load($customerName);
</code></pre> | 13,388,570 | 3 | 0 | null | 2012-11-14 22:33:16.383 UTC | 9 | 2020-10-22 16:02:00.623 UTC | 2017-08-06 19:21:20.843 UTC | null | 3,167,040 | null | 1,825,110 | null | 1 | 52 | php | 100,448 | <p>Unfortunately, it is not possible to call a method on an object just created with <code>new</code> before PHP 5.4.</p>
<p>In PHP 5.4 and later, the following can be used:</p>
<pre><code>$purchaseOrder = (new PurchaseOrderFactory)->instance();
</code></pre>
<p>Note the mandatory pair of parenthesis.</p>
<p>In previous versions, you have to call the method on a variable:</p>
<pre><code>$purchaseFactory = new PurchaseOrderFactory;
$purchaseOrder = $purchaseFactory->instance();
</code></pre> |
13,671,031 | Server polling with AngularJS | <p>I'm trying to learn AngularJS. My first attempt to get new data every second worked:</p>
<pre><code>'use strict';
function dataCtrl($scope, $http, $timeout) {
$scope.data = [];
(function tick() {
$http.get('api/changingData').success(function (data) {
$scope.data = data;
$timeout(tick, 1000);
});
})();
};
</code></pre>
<p>When I simulate a slow server by sleeping the thread for 5 seconds it waits for the response before updating the UI and setting another timeout. The problem is when I rewrote the above to use Angular modules and DI for module creation:</p>
<pre><code>'use strict';
angular.module('datacat', ['dataServices']);
angular.module('dataServices', ['ngResource']).
factory('Data', function ($resource) {
return $resource('api/changingData', {}, {
query: { method: 'GET', params: {}, isArray: true }
});
});
function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query();
$timeout(tick, 1000);
})();
};
</code></pre>
<p>This only works if the server response is fast. If there's any delay it spams out 1 request a second without waiting for a response and seems to clear the UI. I think I need to use a callback function. I tried:</p>
<pre><code>var x = Data.get({}, function () { });
</code></pre>
<p>but got an error: "Error: destination.push is not a function" This was based on the docs for <a href="http://docs.angularjs.org/api/ngResource.$resource" rel="noreferrer">$resource</a> but I didn't really understand the examples there.</p>
<p>How do I make the second approach work?</p> | 13,671,558 | 4 | 0 | null | 2012-12-02 16:07:03.273 UTC | 49 | 2017-04-02 05:00:41.58 UTC | 2012-12-02 16:19:21.47 UTC | null | 1,725,032 | null | 1,725,032 | null | 1 | 86 | javascript|angularjs | 71,140 | <p>You should be calling the <code>tick</code> function in the callback for <code>query</code>.</p>
<pre><code>function dataCtrl($scope, $timeout, Data) {
$scope.data = [];
(function tick() {
$scope.data = Data.query(function(){
$timeout(tick, 1000);
});
})();
};
</code></pre> |
39,650,511 | R - Group by variable and then assign a unique ID | <p>I am interested in de-identifying a sensitive data set with both time-fixed and time-variant values. I want to (a) group all cases by social security number, (b) assign those cases a unique ID and then (c) remove the social security number.</p>
<p>Here's an example data set:</p>
<pre><code>personal_id gender temperature
111-11-1111 M 99.6
999-999-999 F 98.2
111-11-1111 M 97.8
999-999-999 F 98.3
888-88-8888 F 99.0
111-11-1111 M 98.9
</code></pre>
<p>Any solutions would be very much appreciated.</p> | 39,756,310 | 3 | 2 | null | 2016-09-22 23:47:26.753 UTC | 15 | 2020-06-25 13:40:41.683 UTC | 2018-08-07 10:31:26.167 UTC | null | 8,467,042 | null | 4,518,650 | null | 1 | 39 | r|dplyr | 48,894 | <p><code>dplyr</code> has a <code>group_indices</code> function for creating unique group IDs</p>
<pre><code>library(dplyr)
data <- data.frame(personal_id = c("111-111-111", "999-999-999", "222-222-222", "111-111-111"),
gender = c("M", "F", "M", "M"),
temperature = c(99.6, 98.2, 97.8, 95.5))
data$group_id <- data %>% group_indices(personal_id)
data <- data %>% select(-personal_id)
data
gender temperature group_id
1 M 99.6 1
2 F 98.2 3
3 M 97.8 2
4 M 95.5 1
</code></pre>
<p>Or within the same pipeline (<a href="https://github.com/tidyverse/dplyr/issues/2160" rel="noreferrer">https://github.com/tidyverse/dplyr/issues/2160</a>):</p>
<pre><code>data %>%
mutate(group_id = group_indices(., personal_id))
</code></pre> |
24,413,766 | How to use SVG markers in Google Maps API v3 | <p>Can I use my converted image.svg as google map icon. I was converting my png image to svg and I want to use this like google map symbol that can be rotated. I already tried to use the google map symbol but I want to have an icon like car, man, etc... That's why I converted my some png files to svg, just like this example site what does he use for these <a href="http://www.goprotravelling.com/" rel="noreferrer">http://www.goprotravelling.com/</a></p> | 24,426,400 | 8 | 2 | null | 2014-06-25 16:14:23.503 UTC | 39 | 2018-01-08 07:23:03.22 UTC | 2018-01-08 07:23:03.22 UTC | null | 3,438,846 | null | 589,973 | null | 1 | 106 | google-maps|google-maps-api-3|svg | 188,291 | <p>You can render your icon using the <a href="https://developer.mozilla.org/en/docs/Web/SVG/Tutorial/Paths">SVG Path notation</a>.</p>
<p>See <a href="https://developers.google.com/maps/documentation/javascript/symbols">Google documentation</a> for more information.</p>
<p>Here is a basic example:</p>
<pre><code>var icon = {
path: "M-20,0a20,20 0 1,0 40,0a20,20 0 1,0 -40,0",
fillColor: '#FF0000',
fillOpacity: .6,
anchor: new google.maps.Point(0,0),
strokeWeight: 0,
scale: 1
}
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: false,
icon: icon
});
</code></pre>
<p>Here is a working example on how to display and scale a marker SVG icon:</p>
<p><a href="http://jsfiddle.net/upsidown/88JLY/">JSFiddle demo</a></p>
<p><strong>Edit:</strong></p>
<p>Another example here with a complex icon:</p>
<p><a href="http://jsfiddle.net/upsidown/eLcNq/">JSFiddle demo</a></p>
<p><strong>Edit 2:</strong></p>
<p>And here is how you can have a SVG file as an icon:</p>
<p><a href="http://jsfiddle.net/upsidown/r1mm0hft/">JSFiddle demo</a></p> |
24,420,795 | Dynamically add Items to Combobox VB.NET | <p>I have 2 combobox in windows application. I want to programmatically add Items to second combobox based on what is selected in the first combobox.</p>
<p>This is what I do in the selected index change of the combobox:</p>
<pre><code>Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
If ComboBox1.SelectedIndex = 0 Then
ComboBox2.Items.Add("MM")
ComboBox2.Items.Add("PP")
ElseIf ComboBox1.SelectedIndex = 1 Then
ComboBox2.Items.Add("SMS")
ElseIf ComboBox1.SelectedIndex = 2 Then
ComboBox2.Items.Add("MMS")
ComboBox2.Items.Add("SSSS")
End If
Catch ex As Exception
End Try
End Sub
</code></pre>
<p>It works fine, however, if I keep selecting different items it's keep adding the value over and over. I would like to add those values only once.</p>
<p>Also, when I add an item I would prefer to add an ID with the item description. I tried:</p>
<pre><code>ComboBox2.Items.Add("SSSS", "1")
</code></pre>
<p>It seems that it's not working.</p>
<p>Any suggestions?</p> | 24,420,989 | 2 | 3 | null | 2014-06-26 00:40:28.98 UTC | null | 2014-06-26 11:50:54.657 UTC | null | null | null | null | 1,426,542 | null | 1 | 1 | vb.net|combobox | 45,925 | <p>try this</p>
<pre><code>Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
If ComboBox1.SelectedIndex = 0 Then
If Not (ComboBox2.Items.Contains("MM")) And Not (ComboBox2.Items.Contains("PP")) Then
ComboBox2.Items.Add("MM")
ComboBox2.Items.Add("PP")
End If
ElseIf ComboBox1.SelectedIndex = 1 Then
If Not (ComboBox2.Items.Contains("SMS")) Then
ComboBox2.Items.Add("SMS")
End If
ElseIf ComboBox1.SelectedIndex = 2 Then
If Not (ComboBox2.Items.Contains("MMS")) And Not (ComboBox2.Items.Contains("SSSS")) Then
ComboBox2.Items.Add("MMS")
ComboBox2.Items.Add("SSSS")
End If
End If
Catch ex As Exception
End Try
</code></pre> |
3,335,670 | <c:if test> seems to always evaluate true in JSF2 Facelets | <p>I am using JSF2 on Facelets.</p>
<p>I define an <code><ui:param></code> in a page:</p>
<pre><code><ui:composition template="/WEB-INF/templates/ui.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<ui:param name="title" value="OnAir WebDemo" />
...
</ui:composition>
</code></pre>
<p>in the <code>ui.xhtml</code> template I have:</p>
<pre><code><html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jstl/core"
>
<c:if test="#{not empty title}">
<h1>#{title}</h1>
</c:if>
</html>
</code></pre>
<p>However, <code><c:if test></code> seems to always evaluate <code>true</code>, also if the <code><ui:param></code> is not specified. How can I change the code so that <code><c:if test></code> will actually evaluate <code>false</code> when the <code><ui:param></code> is not specified?</p> | 3,335,942 | 2 | 0 | null | 2010-07-26 14:16:22.42 UTC | 8 | 2014-07-18 07:53:18.697 UTC | 2014-07-18 07:53:18.697 UTC | null | 157,882 | null | 264,419 | null | 1 | 10 | jsf|jsf-2|jstl|facelets | 45,273 | <p>The XML namespace is invalid. It should be</p>
<pre><code>xmlns:c="http://java.sun.com/jsp/jstl/core"
</code></pre>
<p>Yes, astonishingly with the <code>/jsp</code> part in the URI! The one without <code>/jsp</code> works only in Facelets 1.x for JSF 1.x. If you have checked the generated HTML output in the webbrowser, you should have noticed as well that the <code><c:if></code> is left unparsed in the HTML output.</p>
<hr />
<p>That said, you should prefer JSF components over JSTL tags, unless technically impossible (i.e. when you actually want to control the <em>building</em> of the view, not <em>rendering</em> of the view). The <code>h:panelGroup</code> as you found out yourself is a good candidate, however the <code>ui:fragment</code> is a nicer choice since it has less overhead.</p>
<pre><code><ui:fragment rendered="#{not empty title}">
<h1>#{title}</h1>
</ui:fragment>
</code></pre>
<p>Note that due to a mistake of the JSF guys in the <code><ui:fragment></code> tag definition file of the initial JSF 2.0 version, Netbeans will jerk that the tag doesn't support the <code>rendered</code> attribute, but this is untrue. It certainly supports it. It has been fixed in JSF 2.1 tag definition.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/3342984/jstl-in-jsf2-facelets-makes-sense">JSTL in JSF2 Facelets... makes sense?</a></li>
<li><a href="https://stackoverflow.com/questions/3713468/alternative-to-uifragment-in-jsf/">Alternative to ui:fragment in JSF</a></li>
<li><a href="https://stackoverflow.com/questions/15946985/the-right-way-to-conditional-rendering-of-non-jsf-components">Conditional rendering of non-JSF components (plain vanilla HTML and template text)</a></li>
</ul> |
9,197,031 | Where can I get additional NetBeans color themes | <p>How can I change netbeans color scheme to some predetermined theme? I don't want to set each value manually. When I was working with Eclipse I had to download some plugin. Does anything similar exist for Netbeans? or perhaps there is some website with all themes to download?</p>
<p>edit: I will expand my question a little bit. I am specifically looking for Oblivion color theme for Eclipse <a href="http://www.eclipsecolorthemes.org/?view=theme&id=1" rel="noreferrer">http://www.eclipsecolorthemes.org/?view=theme&id=1</a> or very similar.</p> | 9,197,135 | 5 | 2 | null | 2012-02-08 16:08:06.093 UTC | 8 | 2013-05-31 10:06:10.583 UTC | 2012-02-08 16:16:32.407 UTC | null | 940,908 | null | 940,908 | null | 1 | 41 | netbeans | 63,613 | <p>You can import a theme, here are a couple of examples:</p>
<ul>
<li><a href="http://marcfearby.com/computing/desert-colour-scheme-for-netbeans" rel="noreferrer">Desert Colour Scheme for NetBeans</a></li>
<li><a href="http://forums.netbeans.org/topic11387.html" rel="noreferrer">Dark Color Scheme/Theme for PHP</a></li>
</ul> |
29,671,543 | Merge r brings error "'by' must specify uniquely valid columns" | <p>R doesn't like me today...</p>
<p>I have two tables asembled via cbind(). Tab 1 (<strong>dwd_nogap</strong>) is</p>
<pre><code> x1 col1_x1 col2_x1
A "1982 12 01 00:00" " 0.4" " 0"
B "1982 12 02 00:00" " -0.5" " 0"
C "1982 12 03 00:00" " -0.2" " 0"
D "1982 12 04 00:00" " -1" " 0.1"
E "1982 12 05 00:00" " -0.9" " 0"
F "1982 12 06 00:00" " 3.7" " 4.1"
</code></pre>
<p>Tab 2 (<strong>dwd_gap</strong>) is:</p>
<pre><code> x2 col1_x2 col2_x2
[1,] "1982 12 01 00:00" " 0.4" " 0"
[2,] "1982 12 03 00:00" " -0.2" " 0"
[3,] "1982 12 04 00:00" " -1" " 0.1"
[4,] "1982 12 05 00:00" " -0.9" " 0"
[5,] "1982 12 06 00:00" " 3.7" " 4.1"
[6,] "1982 12 07 00:00" " 7" " 5.8"
</code></pre>
<p>My merge command is:</p>
<pre><code>exporttab <- merge(x=dwd_nogap,y=dwd_gap,by.x=dwd_nogap[,1],by.y=dwd_gap[,1], fill=-9999)
</code></pre>
<p>In my opinion the command is correct, but it's apparently not doing well...</p>
<pre><code>Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
</code></pre> | 29,671,619 | 2 | 3 | null | 2015-04-16 10:08:57.7 UTC | 3 | 2019-12-02 18:02:54.367 UTC | null | null | null | null | 3,519,324 | null | 1 | 23 | r|merge | 126,501 | <p>Rather give names of the column on which you want to merge:</p>
<pre><code>exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
</code></pre> |
16,350,720 | Using `geom_line()` with X axis being factors | <p>Suppose I have a dataframe:</p>
<pre><code>hist <- data.frame(date=Sys.Date() + 0:13,
counts=1:14)
</code></pre>
<p>I want to plot the total count against weekday, using a <em>line</em> to connect the points.
The following puts <em>points</em> on each value:</p>
<pre><code>hist <- transform(hist, weekday=factor(weekdays(date),
levels=c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')))
ggplot(hist, aes(x=weekday, y=counts)) + geom_point(stat='summary', fun.y=sum)
</code></pre>
<p>When I try to connect them with a line (<code>geom_line()</code>), ggplot complains about only having one data observation per group and hence is not able to draw a line between the points.</p>
<p>I understand this - it's trying to draw one line for each weekday (factor level).</p>
<p>How can I get ggplot to just pretend (for the purposes of the line only) that the weekdays are numeric? Perhaps I have to have another column <code>day_of_week</code> that is 0 for monday, 1 for tuesday, etc?</p> | 16,350,805 | 1 | 0 | null | 2013-05-03 02:33:44.627 UTC | 12 | 2013-05-03 02:45:07.807 UTC | null | null | null | null | 913,184 | null | 1 | 66 | r|ggplot2 | 52,678 | <p>If I understand the issue correctly, specifying <code>group=1</code> and adding a <code>stat_summary()</code> layer should do the trick:</p>
<pre><code>ggplot(hist, aes(x=weekday, y=counts, group=1)) +
geom_point(stat='summary', fun.y=sum) +
stat_summary(fun.y=sum, geom="line")
</code></pre>
<p><img src="https://i.stack.imgur.com/Maqfn.png" alt="enter image description here"></p> |
16,376,035 | fatal: could not create work tree dir 'kivy' | <p>I'm trying to clone my fork of the kivy git, but it's not working. I've made the fork correctly, I believe, but when I type this into my Mac terminal:</p>
<blockquote>
<p>git clone <a href="https://github.com/mygitusername/kivy.git" rel="noreferrer">https://github.com/mygitusername/kivy.git</a></p>
</blockquote>
<p>I get this error:</p>
<blockquote>
<p>fatal: could not create work tree dir 'kivy.: Permission denied</p>
</blockquote>
<p>Anyone see what I am doing wrong? Thanks!</p> | 16,384,466 | 14 | 0 | null | 2013-05-04 15:40:25.22 UTC | 26 | 2022-09-15 17:38:20.483 UTC | null | null | null | null | 1,024,973 | null | 1 | 122 | github|git-clone|kivy | 343,166 | <p>You should do the command in a directory where you have write permission. So:</p>
<pre><code>cd ~/
mkdir code
cd code
git clone https://github.com/kivy/kivy
</code></pre>
<p>For example.</p> |
13,212,300 | How to reconfigure tkinter canvas items? | <p>I don't know if this question has duplicates , but i haven't found one yet.</p>
<p>when using python you can create GUI fastly , but sometimes you cannot find a method to do what you want. for example i have the following problem:</p>
<p>let's suppose that there is a canvas called K with a rectangle with ID=1(canvas item id , not memory id) in it.</p>
<p>if i want to redraw the item i can delete it and then redraw it with new settings.</p>
<pre><code>K.delete(1)
K.create_rectangle(x1,y1,x2,y2,options...)
</code></pre>
<p>here is the problem:the object id changes; how can i redraw or move or resize the rectangle or simply change it without changing its id with a method?for example:</p>
<pre><code>K.foo(1,options....)
</code></pre>
<p>if there isn't such a method , then i should create a list with the canvas object ids , but it is not elegant and not fast.for example:</p>
<pre><code>ItemIds=[None,None,etc...]
ItemIds[0]=K.create_rectangle(old options...)
K.delete(ItemIds[0])
ItemIds[0]=K.create_rectangle(new options...)
</code></pre> | 13,212,501 | 2 | 0 | null | 2012-11-03 18:42:41.163 UTC | 1 | 2021-05-26 01:36:53.333 UTC | null | null | null | null | 1,569,222 | null | 1 | 5 | python|user-interface|tkinter | 47,176 | <p>You can use <a href="https://web.archive.org/web/20201108093851id_/http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.itemconfig-method" rel="nofollow noreferrer"><code>Canvas.itemconfig</code></a>:</p>
<pre><code>item = K.create_rectangle(x1,y1,x2,y2,options...)
K.itemconfig(item,options)
</code></pre>
<p>To move the item, you can use <a href="https://web.archive.org/web/20201108093851id_/http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.move-method" rel="nofollow noreferrer"><code>Canvas.move</code></a></p>
<hr />
<pre><code>import Tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
item = canvas.create_rectangle(50, 25, 150, 75, fill="blue")
def callback():
canvas.itemconfig(item,fill='red')
button = tk.Button(root,text='Push me!',command=callback)
button.pack()
root.mainloop()
</code></pre> |
28,875,325 | gcc optimization flag -O3 makes code slower than -O2 | <p>I find this topic <a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array?rq=1">Why is it faster to process a sorted array than an unsorted array?</a> . And try to run this code. And I find strange behavior. If I compile this code with <code>-O3</code> optimization flag it takes <code>2.98605 sec</code> to run. If I compile with <code>-O2</code> it takes <code>1.98093 sec</code>. I try to run this code several times(5 or 6) on the same machine in the same environment, I close all other software(chrome, skype etc).<br></p>
<pre><code>gcc --version
gcc (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code></pre>
<p>So please can you explain to me why this happens? I read <code>gcc</code> manual and I see that <code>-O3</code> includes <code>-O2</code>. Thank you for help.</p>
<p><strong>P.S.</strong> add code</p>
<pre><code>#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
</code></pre> | 43,941,854 | 1 | 8 | null | 2015-03-05 10:17:38.12 UTC | 23 | 2022-05-22 21:50:15.893 UTC | 2022-05-22 21:50:15.893 UTC | null | 224,132 | null | 1,624,275 | null | 1 | 43 | c++|gcc|optimization|cpu-architecture|compiler-optimization | 17,005 | <p><code>gcc -O3</code> uses a <a href="http://felixcloutier.com/x86/CMOVcc.html" rel="noreferrer">cmov</a> for the conditional, so it lengthens the loop-carried dependency chain to include a <code>cmov</code> (which is 2 uops and 2 cycles of latency on your Intel Sandybridge CPU, according to <a href="http://agner.org/optimize/" rel="noreferrer">Agner Fog's instruction tables</a>. See also the <a href="/questions/tagged/x86" class="post-tag" title="show questions tagged 'x86'" rel="tag">x86</a> tag wiki). This is <a href="http://yarchive.net/comp/linux/cmov.html" rel="noreferrer">one of the cases where <code>cmov</code> sucks</a>.</p>
<p>If the data was even moderately unpredictable, <code>cmov</code> would probably be a win, so this is a fairly sensible choice for a compiler to make. (However, <a href="https://bugs.llvm.org/show_bug.cgi?id=33013" rel="noreferrer">compilers may sometimes use branchless code too much</a>.)</p>
<p>I <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Calgorithm%3E%0A%23include+%3Cctime%3E%0A%23include+%3Ciostream%3E%0A%0Aint+main()%0A%7B%0A++++//+Generate+data%0A++++const+unsigned+arraySize+%3D+32768%3B%0A++++int+data%5BarraySize%5D%3B%0A%0A++++for+(unsigned+c+%3D+0%3B+c+%3C+arraySize%3B+%2B%2Bc)%0A++++++++data%5Bc%5D+%3D+std::rand()+%25+256%3B%0A%0A++++//+!!!!!!+With+this,+the+next+loop+runs+faster%0A++++std::sort(data,+data+%2B+arraySize)%3B%0A%0A++++//+Test%0A++++clock_t+start+%3D+clock()%3B%0A++++long+long+sum+%3D+0%3B%0A%0A++++for+(unsigned+i+%3D+0%3B+i+%3C+100000%3B+%2B%2Bi)%0A++++%7B%0A++++++++//+Primary+loop%0A++++++++for+(unsigned+c+%3D+0%3B+c+%3C+arraySize%3B+%2B%2Bc)%0A++++++++%7B%0A++++++++++++if+(data%5Bc%5D+%3E%3D+128)%0A++++++++++++++++sum+%2B%3D+data%5Bc%5D%3B%0A++++++++%7D%0A++++%7D%0A%0A++++double+elapsedTime+%3D+static_cast%3Cdouble%3E(clock()+-+start)+/+CLOCKS_PER_SEC%3B%0A%0A++++std::cout+%3C%3C+elapsedTime+%3C%3C+std::endl%3B%0A++++std::cout+%3C%3C+%22sum+%3D+%22+%3C%3C+sum+%3C%3C+std::endl%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:33.36599326802078,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g492,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-O2+-std%3Dgnu%2B%2B11+-Wall+',source:1),l:'5',n:'0',o:'x86-64+gcc+4.9.2+(Editor+%231,+Compiler+%231)',t:'0')),k:32.731651559407744,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g492,filters:(b:'0',commentOnly:'0',directives:'0',intel:'0'),options:'-O3+-std%3Dgnu%2B%2B11+-Wall',source:1),l:'5',n:'0',o:'x86-64+gcc+4.9.2+(Editor+%231,+Compiler+%232)',t:'0')),k:33.90235517257147,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="noreferrer">put your code on the Godbolt compiler explorer</a> to see the asm (with nice highlighting and filtering out irrelevant lines. You still have to scroll down past all the sort code to get to main(), though).</p>
<pre><code>.L82: # the inner loop from gcc -O3
movsx rcx, DWORD PTR [rdx] # sign-extending load of data[c]
mov rsi, rcx
add rcx, rbx # rcx = sum+data[c]
cmp esi, 127
cmovg rbx, rcx # sum = data[c]>127 ? rcx : sum
add rdx, 4 # pointer-increment
cmp r12, rdx
jne .L82
</code></pre>
<p>gcc could have saved the MOV by using LEA instead of ADD.</p>
<p>The loop bottlenecks on the latency of ADD->CMOV (3 cycles), since one iteration of the loop writes rbx with CMO, and the next iteration reads rbx with ADD.</p>
<p>The loop only contains 8 fused-domain uops, so it can issue at one per 2 cycles. Execution-port pressure is also not as bad a bottleneck as the latency of the <code>sum</code> dep chain, but it's close (Sandybridge only has 3 ALU ports, unlike Haswell's 4).</p>
<p>BTW, writing it as <code>sum += (data[c] >= 128 ? data[c] : 0);</code> to take the <code>cmov</code> out of the loop-carried dep chain is potentially useful. Still lots of instructions, but the <code>cmov</code> in each iteration is independent. This <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:'%23include+%3Calgorithm%3E%0A%23include+%3Cctime%3E%0A%23include+%3Ciostream%3E%0A%0Aint+main()%0A%7B%0A++++//+Generate+data%0A++++const+unsigned+arraySize+%3D+32768%3B%0A++++int+data%5BarraySize%5D%3B%0A%0A++++for+(unsigned+c+%3D+0%3B+c+%3C+arraySize%3B+%2B%2Bc)%0A++++++++data%5Bc%5D+%3D+std::rand()+%25+256%3B%0A%0A++++//+!!!!!!+With+this,+the+next+loop+runs+faster%0A++++std::sort(data,+data+%2B+arraySize)%3B%0A%0A++++//+Test%0A++++clock_t+start+%3D+clock()%3B%0A++++long+long+sum+%3D+0%3B%0A%0A++++for+(unsigned+i+%3D+0%3B+i+%3C+100000%3B+%2B%2Bi)%0A++++%7B%0A++++++++//+Primary+loop%0A++++++++for+(unsigned+c+%3D+0%3B+c+%3C+arraySize%3B+%2B%2Bc)%0A++++++++%7B%0A%23if+0%0A++++++++++++if+(data%5Bc%5D+%3E%3D+128)%0A++++++++++++++++sum+%2B%3D+data%5Bc%5D%3B%0A%23else%0A++++++++++++sum+%2B%3D+(data%5Bc%5D+%3E%3D+128+%3F+data%5Bc%5D+:+0)%3B%0A%23endif%0A++++++++%7D%0A++++%7D%0A%0A++++double+elapsedTime+%3D+static_cast%3Cdouble%3E(clock()+-+start)+/+CLOCKS_PER_SEC%3B%0A%0A++++std::cout+%3C%3C+elapsedTime+%3C%3C+std::endl%3B%0A++++std::cout+%3C%3C+%22sum+%3D+%22+%3C%3C+sum+%3C%3C+std::endl%3B%0A%7D%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:33.36599326802078,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g63,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),libs:!(),options:'-O2+-std%3Dgnu%2B%2B11+-Wall+-mtune%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+gcc+6.3+(Editor+%231,+Compiler+%231)',t:'0')),k:32.731651559407744,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g63,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',trim:'1'),libs:!(),options:'-O3+-std%3Dgnu%2B%2B11+-Wall+-mtune%3Dhaswell',source:1),l:'5',n:'0',o:'x86-64+gcc+6.3+(Editor+%231,+Compiler+%232)',t:'0')),k:33.90235517257147,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',n:'0',o:'',t:'0')),version:4" rel="noreferrer">compiles as expected in gcc6.3 <code>-O2</code> and earlier</a>, but gcc7 de-optimizes into a <code>cmov</code> on the critical path (<a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82666" rel="noreferrer">https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82666</a>). (It also auto-vectorizes with earlier gcc versions than the <code>if()</code> way of writing it.)</p>
<p>Clang takes the cmov off the critical path even with the original source.</p>
<hr>
<p><code>gcc -O2</code> uses a branch (for gcc5.x and older), which predicts well because your data is sorted. Since modern CPUs use branch-prediction to handle control dependencies, the loop-carried dependency chain is shorter: just an <code>add</code> (1 cycle latency). </p>
<p>The compare-and-branch in every iteration is independent, thanks to branch-prediction + speculative execution, which lets execution continue before the branch direction is known for sure.</p>
<pre><code>.L83: # The inner loop from gcc -O2
movsx rcx, DWORD PTR [rdx] # load with sign-extension from int32 to int64
cmp ecx, 127
jle .L82 # conditional-jump over the next instruction
add rbp, rcx # sum+=data[c]
.L82:
add rdx, 4
cmp rbx, rdx
jne .L83
</code></pre>
<p>There are two loop-carried dependency chains: <code>sum</code> and the loop-counter. <code>sum</code> is 0 or 1 cycle long, and the loop-counter is always 1 cycle long. However, the loop is 5 fused-domain uops on Sandybridge, so it can't execute at 1c per iteration anyway, so latency isn't a bottleneck.</p>
<p>It probably runs at about one iteration per 2 cycles (bottlenecked on branch instruction throughput), vs. one per 3 cycles for the -O3 loop. The next bottleneck would be ALU uop throughput: 4 ALU uops (in the not-taken case) but only 3 ALU ports. (ADD can run on any port).</p>
<p><strong>This pipeline-analysis prediction matches pretty much exactly with your timings of ~3 sec for -O3 vs. ~2 sec for -O2.</strong></p>
<hr>
<p>Haswell/Skylake could run the not-taken case at one per 1.25 cycles, since it can execute a not-taken branch in the same cycle as a taken branch and has 4 ALU ports. (Or slightly less since <a href="https://stackoverflow.com/questions/39311872/is-performance-reduced-when-executing-loops-whose-uop-count-is-not-a-multiple-of">a 5 uop loop doesn't quite issue at 4 uops every cycle</a>).</p>
<p>(Just tested: Skylake @ 3.9GHz runs the branchy version of the whole program in 1.45s, or the branchless version in 1.68s. So the difference is much smaller there.)</p>
<hr>
<p>g++6.3.1 uses <code>cmov</code> even at <code>-O2</code>, but g++5.4 still behaves like 4.9.2.</p>
<p>With both g++6.3.1 and g++5.4, using <code>-fprofile-generate</code> / <code>-fprofile-use</code> produces the branchy version even at <code>-O3</code> (with <code>-fno-tree-vectorize</code>).</p>
<p>The CMOV version of the loop from newer gcc uses <code>add ecx,-128</code> / <code>cmovge rbx,rdx</code> instead of CMP/CMOV. That's kinda weird, but probably doesn't slow it down. ADD writes an output register as well as flags, so creates more pressure on the number of physical registers. But as long as that's not a bottleneck, it should be about equal.</p>
<hr>
<p>Newer gcc auto-vectorizes the loop with -O3, which is a significant speedup even with just SSE2. (e.g. my i7-6700k Skylake runs the vectorized version
in 0.74s, so about twice as fast as scalar. Or <code>-O3 -march=native</code> in 0.35s, using AVX2 256b vectors).</p>
<p>The vectorized version looks like a lot of instructions, but it's not too bad, and most of them aren't part of a loop-carried dep chain. It only has to unpack to 64-bit elements near the end. It does <code>pcmpgtd</code> twice, though, because it doesn't realize it could just zero-extend instead of sign-extend when the condition has already zeroed all negative integers.</p> |
21,731,745 | How to add shebang #! with php script on linux? | <p>I'm having a little issue with adding shebang #! with my php script on RedHat linux. I have a small piece of test code with shebang added (I've tried different variations as well), but I get the following error message everytime I try to run the script.</p>
<p>Error msg:</p>
<pre><code>-bash: script.php: command not found
</code></pre>
<p>Test script:</p>
<pre><code>#!/bin/env php
<?php echo "test"; ?>
</code></pre>
<p>Shebang #! variations:</p>
<pre><code>#!/usr/bin/php
#!/usr/bin/env php
</code></pre> | 21,731,882 | 5 | 4 | null | 2014-02-12 15:10:48.86 UTC | 2 | 2020-10-10 16:13:04.75 UTC | null | null | null | null | 2,799,603 | null | 1 | 30 | php|linux|shebang | 31,470 | <p>It should (for most systems) be <code>#!/usr/bin/env php</code>, but your error isn't related to that.</p>
<blockquote>
<pre><code>-bash: script.php: command not found
</code></pre>
</blockquote>
<p>It says that <strong>script.php</strong> is not found.</p>
<p>If the problem was the shebang line then the error would say something like:</p>
<pre><code>bash: script.php: /usr/env: bad interpreter: No such file or directory
</code></pre>
<p>Presumably, you are typing <code>script.php</code> and the file is not in a directory on your <code>$PATH</code> or is not executable.</p>
<ol>
<li>Make it executable: <code>chmod +x script.php</code>.</li>
<li>Type the path to it instead of just the filename, if it is in the current directory then: <code>./script.php</code>.</li>
</ol>
<p>Instead of 2, you can move/copy/symlink the file to somewhere listed in <code>$PATH</code> or <a href="https://stackoverflow.com/questions/16560332/what-is-this-path-in-linux-and-how-to-modify-it">modify the <code>$PATH</code></a> to include the directory containing the script.</p> |
26,456,125 | Python Pandas: Is Order Preserved When Using groupby() and agg()? | <p>I've frequented used pandas' <code>agg()</code> function to run summary statistics on every column of a data.frame. For example, here's how you would produce the mean and standard deviation:</p>
<pre><code>df = pd.DataFrame({'A': ['group1', 'group1', 'group2', 'group2', 'group3', 'group3'],
'B': [10, 12, 10, 25, 10, 12],
'C': [100, 102, 100, 250, 100, 102]})
>>> df
[output]
A B C
0 group1 10 100
1 group1 12 102
2 group2 10 100
3 group2 25 250
4 group3 10 100
5 group3 12 102
</code></pre>
<p>In both of those cases, the order that individual rows are sent to the agg function does not matter. But consider the following example, which:</p>
<pre><code>df.groupby('A').agg([np.mean, lambda x: x.iloc[1] ])
[output]
mean <lambda> mean <lambda>
A
group1 11.0 12 101 102
group2 17.5 25 175 250
group3 11.0 12 101 102
</code></pre>
<p>In this case the lambda functions as intended, outputting the second row in each group. However, I have not been able to find anything in the pandas documentation that implies that this is guaranteed to be true in all cases. I want use <code>agg()</code> along with a weighted average function, so I want to be sure that the rows that come into the function will be in the same order as they appear in the original data frame.</p>
<p>Does anyone know, ideally via somewhere in the docs or pandas source code, if this is guaranteed to be the case?</p> | 26,465,555 | 6 | 2 | null | 2014-10-19 22:31:41.47 UTC | 17 | 2021-06-18 11:12:13.923 UTC | 2014-10-19 23:36:57.733 UTC | null | 3,124,423 | null | 3,124,423 | null | 1 | 65 | python|pandas|aggregate | 36,793 | <p>See this enhancement <a href="https://github.com/pydata/pandas/issues/8588" rel="noreferrer">issue</a></p>
<p>The short answer is yes, the groupby will preserve the orderings as passed in. You can prove this by using your example like this:</p>
<pre><code>In [20]: df.sort_index(ascending=False).groupby('A').agg([np.mean, lambda x: x.iloc[1] ])
Out[20]:
B C
mean <lambda> mean <lambda>
A
group1 11.0 10 101 100
group2 17.5 10 175 100
group3 11.0 10 101 100
</code></pre>
<p>This is NOT true for resample however as it requires a monotonic index (it WILL work with a non-monotonic index, but will sort it first).</p>
<p>Their is a <code>sort=</code> flag to groupby, but this relates to the sorting of the groups themselves and not the observations within a group.</p>
<p>FYI: <code>df.groupby('A').nth(1)</code> is a safe way to get the 2nd value of a group (as your method above will fail if a group has < 2 elements)</p> |
19,560,498 | Faster way to remove stop words in Python | <p>I am trying to remove stopwords from a string of text:</p>
<pre><code>from nltk.corpus import stopwords
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in (stopwords.words('english'))])
</code></pre>
<p>I am processing 6 mil of such strings so speed is important. Profiling my code, the slowest part is the lines above, is there a better way to do this? I'm thinking of using something like regex's <code>re.sub</code> but I don't know how to write the pattern for a set of words. Can someone give me a hand and I'm also happy to hear other possibly faster methods.</p>
<p>Note: I tried someone's suggest of wrapping <code>stopwords.words('english')</code> with <code>set()</code> but that made no difference.</p>
<p>Thank you.</p> | 19,560,949 | 6 | 7 | null | 2013-10-24 08:13:45.427 UTC | 28 | 2022-02-13 17:00:13.823 UTC | null | null | null | null | 1,583,516 | null | 1 | 53 | python|regex|stop-words | 102,412 | <p>Try caching the stopwords object, as shown below. Constructing this each time you call the function seems to be the bottleneck.</p>
<pre><code> from nltk.corpus import stopwords
cachedStopWords = stopwords.words("english")
def testFuncOld():
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in stopwords.words("english")])
def testFuncNew():
text = 'hello bye the the hi'
text = ' '.join([word for word in text.split() if word not in cachedStopWords])
if __name__ == "__main__":
for i in xrange(10000):
testFuncOld()
testFuncNew()
</code></pre>
<p>I ran this through the profiler: <strong>python -m cProfile -s cumulative test.py</strong>. The relevant lines are posted below.</p>
<p>nCalls Cumulative Time</p>
<p>10000 7.723 words.py:7(testFuncOld)</p>
<p>10000 0.140 words.py:11(testFuncNew)</p>
<p>So, caching the stopwords instance gives a ~70x speedup.</p> |
44,838,568 | Trigger Angular change detection from console | <p>In AngularJS we were able to trigger a digest cycle by getting the ng-app element with something like </p>
<pre><code>var scope = angular.element(element).scope();
scope.$apply(...);
</code></pre>
<p>I have looked all over for a solution to do this in Angular(4+) but have only found solutions that work in the app like(<a href="https://stackoverflow.com/questions/34827334/triggering-angular2-change-detection-manually">Triggering Angular2 change detection manually</a>). I need something that works from the console.</p>
<p>I'm sure I'm doing it wrong but trying to apply the answer on the above question didn't work. I tried many variations of this:</p>
<pre><code>ng.probe($0).injector.view.root.ngModule.injector.get('ApplicationRef')
</code></pre> | 44,838,660 | 3 | 3 | null | 2017-06-30 04:23:44.287 UTC | 8 | 2020-10-13 13:37:59.977 UTC | 2017-06-30 18:11:38.86 UTC | null | 234,834 | null | 234,834 | null | 1 | 17 | angular | 7,679 | <p>I usually do it as follows in dev mode</p>
<pre><code>ng.probe(getAllAngularRootElements()[0]).injector.get(ng.coreTokens.ApplicationRef).tick()
</code></pre>
<p><a href="https://i.stack.imgur.com/fVER5.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fVER5.gif" alt="enter image description here" /></a></p>
<p>Starting with <strong>Angular 9</strong> with Ivy you can call:</p>
<pre><code>ng.applyChanges(ng.getComponent($0))
</code></pre>
<p>Where <code>$0</code> points to component's element</p>
<p><a href="https://i.stack.imgur.com/7QrSE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7QrSE.png" alt="enter image description here" /></a></p> |
17,292,783 | GPX files for iOS Simulator | <p>Where I can find GPX files that I can import into my iOS Simulator?</p>
<p>The iOS Simulator only contains static locations around the world and walk / bike / car drive simulations.
This is not good enough for unit testing or other specific use cases.</p>
<p>This is the for GPX file: <a href="http://www.topografix.com/GPX/1/1/gpx.xsd" rel="nofollow noreferrer">http://www.topografix.com/GPX/1/1/gpx.xsd</a></p>
<p>How can I simulate a movement along some custom route in Simulator or Xcode, cause it's needed in ios mobile development?</p> | 17,478,860 | 8 | 0 | null | 2013-06-25 08:40:47.247 UTC | 15 | 2022-02-14 15:02:50.957 UTC | 2022-02-14 15:02:50.957 UTC | null | 14,563,565 | null | 1,317,394 | null | 1 | 51 | ios|xcode|gps|ios-simulator|gpx | 51,728 | <p>You create a route and generate a gpx file here - <a href="http://www.bikehike.co.uk/mapview.php">http://www.bikehike.co.uk/mapview.php</a></p>
<p>On another note it might help, are you aware the simulator can simulate movement if you run the simulator then select the following menu options:</p>
<ul>
<li>Debug</li>
<li>Location</li>
<li>You can select freeway drive, cycle ride, run etc</li>
</ul> |
17,327,202 | python replace single backslash with double backslash | <p>In python, I am trying to replace a single backslash ("\") with a double backslash("\"). I have the following code:</p>
<pre><code>directory = string.replace("C:\Users\Josh\Desktop\20130216", "\", "\\")
</code></pre>
<p>However, this gives an error message saying it doesn't like the double backslash. Can anyone help?</p> | 17,327,500 | 9 | 8 | null | 2013-06-26 17:56:37.66 UTC | 7 | 2022-08-07 03:09:55.487 UTC | 2014-10-19 22:22:41.477 UTC | null | 846,892 | null | 1,054,287 | null | 1 | 66 | python|string|replace|backslash | 135,146 | <p>No need to use <code>str.replace</code> or <code>string.replace</code> here, just convert that string to a raw string:</p>
<pre><code>>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
</code></pre>
<p>Below is the <code>repr</code> version of the above string, that's why you're seeing <code>\\</code> here.
But, in fact the actual string contains just <code>'\'</code> not <code>\\</code>.</p>
<pre><code>>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
</code></pre>
<p>But when you're going to print this string you'll not get <code>'\\'</code> in the output.</p>
<pre><code>>>> print strs
C:\Users\Josh\Desktop\20130216
</code></pre>
<p>If you want the string to show <code>'\\'</code> during <code>print</code> then use <code>str.replace</code>:</p>
<pre><code>>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
</code></pre>
<p><code>repr</code> version will now show <code>\\\\</code>:</p>
<pre><code>>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
</code></pre> |
30,352,431 | CSS transition not working with underline | <p>I am using css to make an underline come under a span: </p>
<p><strong>CSS:</strong></p>
<pre><code>.un{
text-decoration:none;
transition: all .5s ease-in;
}
.un:hover{
text-decoration:underline;
}
</code></pre>
<p><strong>HTML:</strong></p>
<pre><code><span class="un"> Underlined Text - Or to be underlined </span>
</code></pre>
<p>The underline simply appears, it doesn't move in over .5 seconds, like the <code>transition</code> should apply. Why not? How can I make this work?</p> | 30,352,626 | 10 | 2 | null | 2015-05-20 14:20:20.277 UTC | 20 | 2022-08-30 12:07:36.353 UTC | 2015-05-20 15:15:23.757 UTC | null | 3,937,664 | null | 4,633,197 | null | 1 | 45 | html|css | 50,672 | <h2>Updated for 2021:</h2>
<p>The support for <code>text-decoration-color</code> has come a long way, and common browser support requirements have loosened making it a viable option for most new projects. If you are only seeking a color transition, and can do without IE support, see <a href="https://stackoverflow.com/a/53139326/3285730">this answer below</a>.</p>
<hr />
<h2>Original answer:</h2>
<p>You cannot change the color of the <code>text-decoration</code> independent of the <code>color</code>. However, you can achieve a similar effect with pseudo elements:</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>.un {
display: inline-block;
}
.un::after {
content: '';
width: 0px;
height: 1px;
display: block;
background: black;
transition: 300ms;
}
.un:hover::after {
width: 100%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="un">Underlined Text - Or to be underlined</span></code></pre>
</div>
</div>
</p>
<p>That is the most customizable way to do it, you can get all sorts of transitions. (Try playing around with the margins/alignment. You can make some awesome effects without adding to your HTML)<br />
But if you just want a simple underline, use a border:</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>.un {
transition: 300ms;
border-bottom: 1px solid transparent;
}
.un:hover {
border-color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="un"> Underlined Text - Or to be underlined </span></code></pre>
</div>
</div>
</p> |
18,527,051 | Split a large dataframe into a list of data frames based on common value in column | <p>I have a data frame with 10 columns, collecting actions of "users", where one of the columns contains an ID (not unique, identifying user)(column 10). the length of the data frame is about 750000 rows. I am trying to extract individual data frames (so getting a list or vector of data frames) split by the column containing the "user" identifier, to isolate the actions of a single actor.</p>
<pre><code>ID | Data1 | Data2 | ... | UserID
1 | aaa | bbb | ... | u_001
2 | aab | bb2 | ... | u_001
3 | aac | bb3 | ... | u_001
4 | aad | bb4 | ... | u_002
</code></pre>
<p>resulting into </p>
<pre><code>list(
ID | Data1 | Data2 | ... | UserID
1 | aaa | bbb | ... | u_001
2 | aab | bb2 | ... | u_001
3 | aac | bb3 | ... | u_001
,
4 | aad | bb4 | ... | u_002
...)
</code></pre>
<p>The following works very well for me on a small sample (1000 rows):</p>
<pre><code>paths = by(smallsampleMat, smallsampleMat[,"userID"], function(x) x)
</code></pre>
<p>and then accessing the element I want by paths[1] for instance.</p>
<p>When applying on the original large data frame or even a matrix representation, this chokes my machine ( 4GB RAM, MacOSX 10.6, R 2.15) and never completes (I know that a newer R version exists, but I believe this is not the main problem). </p>
<p>It seems that split is more performant and after a long time completes, but I do not know ( inferior R knowledge) how to piece the resulting list of vectors into a vector of matrices.</p>
<pre><code>path = split(smallsampleMat, smallsampleMat[,10])
</code></pre>
<p>I have considered also using <code>big.matrix</code> etc, but without much success that would speed up the process.</p> | 18,527,515 | 3 | 0 | null | 2013-08-30 07:14:29.19 UTC | 33 | 2021-01-21 22:50:46.77 UTC | 2013-08-30 08:38:04.863 UTC | null | 172,261 | null | 2,731,872 | null | 1 | 103 | r|performance|matrix|split|dataframe | 135,330 | <p>You can just as easily access each element in the list using e.g. <code>path[[1]]</code>. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by <code>split</code>, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use <code>*apply</code> functions to further operate on each element in the list. Example below.</p>
<pre><code># For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
</code></pre>
<p>Access each element using the <code>[[</code> operator like this:</p>
<pre><code>out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
</code></pre>
<p>Or use an <code>*apply</code> function to do further operations on each list element. For instance, to take the mean of the <code>data2</code> column you could use sapply like this:</p>
<pre><code>sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
</code></pre> |
18,245,394 | "ignore" in Bower's bower.json? | <p>Bower's website describes the <code>ignore</code> key in bower.json:</p>
<blockquote>
<p><code>ignore</code> [array]: An array of paths not needed in production that you want Bower to ignore when installing your package.</p>
</blockquote>
<p>Does this mean that it's ignoring paths in installed components, or in your package? Or something else? I was confused by this.</p> | 18,245,451 | 3 | 0 | null | 2013-08-15 02:27:00.797 UTC | 3 | 2021-08-10 23:32:24.033 UTC | 2021-08-10 23:32:24.033 UTC | null | 12,299,000 | null | 804,100 | null | 1 | 63 | bower | 31,960 | <h3>TL;DR:</h3>
<p><code>ignore</code> only works within the scope of packages being installed, ignoring matching patterns.</p>
<hr>
<h3>Somewhat longer answer:</h3>
<p>Bower will ignore all files matching the patterns specified in the <code>ignore</code> property of <code>bower.json</code> in installed packages.</p>
<p>So, suppose if you ran <code>bower install someBowerPackage</code> which had following structure:</p>
<pre><code>someBowerPackage
|- css/
|- js/
|- index.html
|- bower.json
</code></pre>
<p>with a bower.json file having:</p>
<pre><code>{
...
"ignore": [ "index.html" ]
}
</code></pre>
<p>then, <code>index.html</code> file of this <code>someBowerPackage</code> will not be installed within this package.</p> |
31,850,824 | AngularJs force browser to clear cache | <p>My <code>angular</code> application is constantly changing these days because our team runs rapid updates right now.</p>
<p>Because of cache our clients does not always have the newest version of our code.</p>
<p>So is there a way in <code>angular</code> to force the browser to clear cache?</p> | 37,766,386 | 3 | 9 | null | 2015-08-06 08:39:18.727 UTC | 14 | 2019-01-17 10:34:52.133 UTC | null | null | null | null | 1,647,457 | null | 1 | 45 | javascript|angularjs|html|caching | 60,944 | <p>You can use a very simple solution that consist in append a hash to your scripts files. Each time your App is deployed you serve your files with a different hash automatically via a gulp/grunt task. As an example you can use <a href="https://github.com/sindresorhus/gulp-rev" rel="noreferrer">gulp-rev</a>. I use this technique in all my projects and works just fine, this automatized in your build/deploy process can be a solution for all your projects.</p>
<p>Yeoman generator for AngularJS <a href="https://github.com/Swiip/generator-gulp-angular" rel="noreferrer">generator-gulp-angular</a> <em>(this was my generator of choice)</em> use this solution to ensure that the browser load the new optimazed file and not the old one in cache. Please create a demo project and play with it and you will see it in action.</p> |
5,068,251 | Android: What are the recommended configurations for Proguard? | <p>I'm developing apps for Android and using Proguard to obfuscate the code.</p>
<p>Currently i'm using ProGuard configurations:</p>
<pre><code>-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.android.vending.licensing.ILicensingService
</code></pre>
<p>To maintain custom components names that are used on layouts XML:</p>
<pre><code>-keep public class custom.components.**
</code></pre>
<p>To remove debug logs:</p>
<pre><code>-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** v(...);
}
</code></pre>
<p>To avoid changing names of methods invoked on layout's onClick:</p>
<pre><code>-keepclassmembers class * {
public void onClickButton1(android.view.View);
public void onClickButton2(android.view.View);
public void onClickButton3(android.view.View);
}
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
</code></pre>
<p>The question is (are): </p>
<p>Are any other tags recommended? Why and what for?</p>
<p>It's possible to make a comment on a proguard.cfg file? I would like to have it with comments for what some lines are doing so that other developers don't have doubts about why i added.</p>
<p>Also in proguard, is it possible to maintain the comment header of a file (with the copyright)? If it's not, or it's not a good policy where should i add the copyright? </p> | 6,492,478 | 3 | 0 | null | 2011-02-21 16:09:05.22 UTC | 63 | 2018-06-15 23:32:10.49 UTC | null | null | null | null | 327,011 | null | 1 | 65 | android|proguard | 59,379 | <p><strong>Android SDK (r20 or higher)</strong></p>
<p>Please check the predefined proguard.config refered in project.properties</p>
<pre><code>proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt
</code></pre>
<p>More info: <a href="http://proguard.sourceforge.net/manual/examples.html#androidapplication" rel="nofollow noreferrer">http://proguard.sourceforge.net/manual/examples.html#androidapplication</a></p>
<p>Here you can check a <strong>proguard "default" file that I keep updating</strong>: <a href="https://medium.com/code-procedure-and-rants/android-my-standard-proguard-ffeceaf65521" rel="nofollow noreferrer">https://medium.com/code-procedure-and-rants/android-my-standard-proguard-ffeceaf65521</a></p>
<hr>
<p><strong>Android SDK (r19 or lower)</strong></p>
<p>Based on my answer <a href="https://stackoverflow.com/questions/4732656/enabling-proguard-in-eclipse-for-android/5040675#5040675">Enabling ProGuard in Eclipse for Android</a> I've ended up with this generic file. I've added comments to remember what each line is for. It might help people out there so here it is:</p>
<pre><code>-optimizationpasses 5
#When not preverifing in a case-insensitive filing system, such as Windows. Because this tool unpacks your processed jars, you should then use:
-dontusemixedcaseclassnames
#Specifies not to ignore non-public library classes. As of version 4.5, this is the default setting
-dontskipnonpubliclibraryclasses
#Preverification is irrelevant for the dex compiler and the Dalvik VM, so we can switch it off with the -dontpreverify option.
-dontpreverify
#Specifies to write out some more information during processing. If the program terminates with an exception, this option will print out the entire stack trace, instead of just the exception message.
-verbose
#The -optimizations option disables some arithmetic simplifications that Dalvik 1.0 and 1.5 can't handle. Note that the Dalvik VM also can't handle aggressive overloading (of static fields).
#To understand or change this check http://proguard.sourceforge.net/index.html#/manual/optimizations.html
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
#To repackage classes on a single package
#-repackageclasses ''
#Uncomment if using annotations to keep them.
#-keepattributes *Annotation*
#Keep classes that are referenced on the AndroidManifest
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class com.android.vending.licensing.ILicensingService
#To remove debug logs:
-assumenosideeffects class android.util.Log {
public static *** d(...);
public static *** v(...);
}
#To avoid changing names of methods invoked on layout's onClick.
# Uncomment and add specific method names if using onClick on layouts
#-keepclassmembers class * {
# public void onClickButton(android.view.View);
#}
#Maintain java native methods
-keepclasseswithmembernames class * {
native <methods>;
}
#To maintain custom components names that are used on layouts XML.
#Uncomment if having any problem with the approach below
#-keep public class custom.components.package.and.name.**
#To maintain custom components names that are used on layouts XML:
-keep public class * extends android.view.View {
public <init>(android.content.Context);
public <init>(android.content.Context, android.util.AttributeSet);
public <init>(android.content.Context, android.util.AttributeSet, int);
public void set*(...);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
#Maintain enums
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
#To keep parcelable classes (to serialize - deserialize objects to sent through Intents)
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
#Keep the R
-keepclassmembers class **.R$* {
public static <fields>;
}
###### ADDITIONAL OPTIONS NOT USED NORMALLY
#To keep callback calls. Uncomment if using any
#http://proguard.sourceforge.net/index.html#/manual/examples.html#callback
#-keep class mypackage.MyCallbackClass {
# void myCallbackMethod(java.lang.String);
#}
#Uncomment if using Serializable
#-keepclassmembers class * implements java.io.Serializable {
# private static final java.io.ObjectStreamField[] serialPersistentFields;
# private void writeObject(java.io.ObjectOutputStream);
# private void readObject(java.io.ObjectInputStream);
# java.lang.Object writeReplace();
# java.lang.Object readResolve();
#}
</code></pre> |
25,867,989 | What is the difference between Java Non Heap Memory and Stack Memory? Are they Same if not what is the difference between them? | <p>I am using Jconsole for monitoring a Java Application. The memory tab shows different Heap and Non Heap memories like</p>
<ol>
<li>Heap Memory Usage</li>
<li>Non Heap Memory Usage</li>
<li>Memory Pool "CMS Old Gen"</li>
<li>Memory Pool "Par Eden Space"</li>
<li>Memory Pool "Par Survivor Space"</li>
<li>Memory Pool "Code Cache"</li>
<li>Memory Pool "CMS Perm Gen"</li>
</ol>
<p>What is the difference between these terms. Also please provide some information regarding - how to find anomalies in the application behavior by monitoring these parameters.</p> | 25,868,171 | 3 | 2 | null | 2014-09-16 11:48:12.807 UTC | 10 | 2014-09-16 11:57:20.943 UTC | null | null | null | null | 2,885,295 | null | 1 | 20 | java|memory-management|jvm|heap-memory|jconsole | 44,670 | <p>There are essentially three categories of storage in all C-based languages (and most other languages):</p>
<ol>
<li>Heap</li>
<li>Stack</li>
<li>Static (with several variations)</li>
</ol>
<p>Heap you're familiar with.</p>
<p>Stack you're also familiar with, but you just don't know it. When you have a method with "local" variables, those variables are allocated in a "invocation frame". The "invocation frame" is allocated when you call the method and deleted when you return from the method, and hence it's most efficiently implemented using a "stack" that grows with call and shrinks with return.</p>
<p>Static is stuff that you don't explicitly allocate and essentially exists from the time program execution begins.</p>
<p>The space required for stack is generally fairly small and is lumped in with "Non Heap Memory" in the categories above.</p> |
25,562,542 | PostgreSQL window function: row_number() over (partition col order by col2) | <p>Following result set is derived from a sql query with a few joins and a union. The sql query already groups rows on Date and game. I need a column to describe the number of attempts at a game partitioned by date column.</p>
<pre><code>Username Game ID Date
johndoe1 Game_1 100 7/22/14 1:52 AM
johndoe1 Game_1 100 7/22/14 1:52 AM
johndoe1 Game_1 100 7/22/14 1:52 AM
johndoe1 Game_1 100 7/22/14 1:52 AM
johndoe1 Game_1 121 7/22/14 1:56 AM
johndoe1 Game_1 121 7/22/14 1:56 AM
johndoe1 Game_1 121 7/22/14 1:56 AM
johndoe1 Game_1 121 7/22/14 1:56 AM
johndoe1 Game_1 121 7/22/14 1:56 AM
johndoe1 Game_1 130 7/22/14 1:59 AM
johndoe1 Game_1 130 7/22/14 1:59 AM
johndoe1 Game_1 130 7/22/14 1:59 AM
johndoe1 Game_1 130 7/22/14 1:59 AM
johndoe1 Game_1 130 7/22/14 1:59 AM
johndoe1 Game_1 200 7/22/14 2:54 AM
johndoe1 Game_1 200 7/22/14 2:54 AM
johndoe1 Game_1 200 7/22/14 2:54 AM
johndoe1 Game_1 200 7/22/14 2:54 AM
johndoe1 Game_1 210 7/22/14 3:54 AM
johndoe1 Game_1 210 7/22/14 3:54 AM
johndoe1 Game_1 210 7/22/14 3:54 AM
johndoe1 Game_1 210 7/22/14 3:54 AM
</code></pre>
<p>I've the following sql query that enumerates the rows within the partition but not entirely correct since I want the count of the instances of that game based on the date and game. In this case johndoe1 has attempted at Game_1 five times partitioned by the time stamps. </p>
<p>This query returns result set below</p>
<pre><code>select *
, row_number() over (partition by ct."date" order by ct."date") as "Attempts"
from csv_temp as ct
Username Game ID Date Attempts (Desired Attempts col.)
johndoe1 Game_1 100 7/22/14 1:52 AM 1 1
johndoe1 Game_1 100 7/22/14 1:52 AM 2 1
johndoe1 Game_1 100 7/22/14 1:52 AM 3 1
johndoe1 Game_1 100 7/22/14 1:52 AM 4 1
johndoe1 Game_1 121 7/22/14 1:56 AM 1 2
johndoe1 Game_1 121 7/22/14 1:56 AM 2 2
johndoe1 Game_1 121 7/22/14 1:56 AM 3 2
johndoe1 Game_1 121 7/22/14 1:56 AM 4 2
johndoe1 Game_1 121 7/22/14 1:56 AM 5 2
johndoe1 Game_1 130 7/22/14 1:59 AM 1 3
johndoe1 Game_1 130 7/22/14 1:59 AM 2 3
johndoe1 Game_1 130 7/22/14 1:59 AM 3 3
johndoe1 Game_1 130 7/22/14 1:59 AM 4 3
johndoe1 Game_1 130 7/22/14 1:59 AM 5 3
johndoe1 Game_1 200 7/22/14 2:54 AM 1 4
johndoe1 Game_1 200 7/22/14 2:54 AM 2 4
johndoe1 Game_1 200 7/22/14 2:54 AM 3 4
johndoe1 Game_1 200 7/22/14 2:54 AM 4 4
johndoe1 Game_1 210 7/22/14 3:54 AM 1 5
johndoe1 Game_1 210 7/22/14 3:54 AM 2 5
johndoe1 Game_1 210 7/22/14 3:54 AM 3 5
johndoe1 Game_1 210 7/22/14 3:54 AM 4 5
</code></pre>
<p>Any pointers would be of great help.</p> | 25,562,772 | 1 | 2 | null | 2014-08-29 06:07:27.84 UTC | 8 | 2014-08-29 06:33:53.28 UTC | null | null | null | null | 1,951,677 | null | 1 | 14 | sql|postgresql|window-functions|row-number | 69,361 | <p>Consider <code>partition by</code> to be similar to the fields that you would <code>group by</code>, then, when the partition values change, the windowing function restarts at 1</p>
<p>EDIT
as indicated by a_horse_with_no_name, for this need we need <code>dense_rank()</code>
unlike <code>row_number()</code> <code>rank()</code> or <code>dense_rank()</code> repeat the numbers it assigns. <code>row_number()</code> must be a different value for each row in a partition. The difference between <code>rank()</code> and <code>dense_rank()</code> is the latter does not "skip" numbers.</p>
<p>For your query try:</p>
<pre><code>dense_rank() over (partition by Username, Game order by ct."date") as "Attempts"
</code></pre>
<p>You don't partition by, and order by, the same field by the way; just order by would be sufficient if that was the need. It isn't here.</p> |
9,401,521 | Is action really required on forms? | <p>Here it says it's required</p>
<p><a href="http://www.w3schools.com/tags/att_form_action.asp" rel="noreferrer">http://www.w3schools.com/tags/att_form_action.asp</a></p>
<p>but I see that forms get submitted even if I don't specify an action attribute, and the form gets submitted to the current page which is exactly what I want.</p> | 9,401,608 | 4 | 4 | null | 2012-02-22 19:22:21.27 UTC | 8 | 2018-09-29 15:29:57.337 UTC | 2012-07-13 14:22:32.173 UTC | null | 468,793 | null | 376,947 | null | 1 | 56 | forms|html|html-validation | 84,536 | <p>The requirement is only by <strong>standards</strong>. It is perfectly possible to do whatever you want on a page and not follow standards. Things may not display or work correctly if you do that, but likely they will. The goal is to follow them, and the idea is that if you follow them, your page will <strong>always</strong> work; you don't have to worry about anything.</p>
<p>Yes, the form is <strong>required</strong> to have an action attribute in HTML4. If it's not set, the browser will likely use the same method as providing an empty string to it. You really should set <code>action=""</code> which is perfectly valid HTML4, follows standards, and achieves the same exact result.</p>
<p>In HTML5, you can actually specify an action on the submit button itself. If there isn't one, it uses the form's action and if that is not set, it defaults to the empty string (note you cannot explicitly set the action to an empty string in HTML5).</p> |
18,452,134 | Filling a Datagrid with dynamic Columns | <p>I have an Datagrid which needs to get filled dynamicly.</p>
<p>The tablelayout is like: </p>
<pre><code>id | image | name | Description | Name-1 | Name-N
</code></pre>
<p>The first 4 columns are static the others are dynamic. The User should be able to add as many users as he wants. </p>
<p>I try to compare data of multiple users by putting them next to each other in the table.</p>
<p>Right now I have an Listbox whitch containes the Names of the dynamic generated Columns and an method that filles the static columns. I also can load the datas for each User. now I need to merge them to one big Table.</p>
<p>The main Problem is now: How to put the "Userdata" and the static content in one datagrid.</p> | 18,452,378 | 4 | 3 | null | 2013-08-26 20:03:52.627 UTC | 24 | 2021-04-09 16:20:04.59 UTC | 2013-08-26 20:05:43.97 UTC | null | 1,501,794 | null | 2,043,252 | null | 1 | 36 | c#|.net|wpf|datagrid | 52,371 | <p>There are at least three ways of doing this:</p>
<ol>
<li>Modify the DataGrid's columns manually from code-behind</li>
<li>Use a DataTable as the ItemsSource *</li>
<li><p>Use a CustomTypeDescriptor</p>
<p>*recommended for simplicity</p></li>
</ol>
<hr/>
<p><strong>1st approach:</strong> use code-behind to generate the DataGrid's columns at runtime. This is simple to implement, but maybe feels a bit hackish, especially if you're using MVVM. So you'd have your DataGrid with fixed columns:</p>
<pre><code><DataGrid x:Name="grid">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding id}" Header="id" />
<DataGridTextColumn Binding="{Binding image}" Header="image" />
</DataGrid.Columns>
</DataGrid>
</code></pre>
<p>When you have your "Names" ready, then modify the grid by adding/removing columns, eg:</p>
<pre><code>// add new columns to the data grid
void AddColumns(string[] newColumnNames)
{
foreach (string name in newColumnNames)
{
grid.Columns.Add(new DataGridTextColumn {
// bind to a dictionary property
Binding = new Binding("Custom[" + name + "]"),
Header = name
});
}
}
</code></pre>
<p>You'll want to create a wrapper class, which should contain the original class, plus a dictionary to contain the custom properties. Let's say your main row class is "User", then you'd want a wrapper class something like this:</p>
<pre><code>public class CustomUser : User
{
public Dictionary<string, object> Custom { get; set; }
public CustomUser() : base()
{
Custom = new Dictionary<string, object>();
}
}
</code></pre>
<p>Populate the <code>ItemsSource</code> with a collection of this new "CustomUser" class:</p>
<pre><code>void PopulateRows(User[] users, Dictionary<string, object>[] customProps)
{
var customUsers = users.Select((user, index) => new CustomUser {
Custom = customProps[index];
});
grid.ItemsSource = customUsers;
}
</code></pre>
<p>So tying it together, for example:</p>
<pre><code>var newColumnNames = new string[] { "Name1", "Name2" };
var users = new User[] { new User { id="First User" } };
var newProps = new Dictionary<string, object>[] {
new Dictionary<string, object> {
"Name1", "First Name of First User",
"Name2", "Second Name of First User",
},
};
AddColumns(newColumnNames);
PopulateRows(users, newProps);
</code></pre>
<hr/>
<p><strong>2nd approach:</strong> use a <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.aspx" rel="noreferrer">DataTable</a>. This makes use of the custom-type infrastructure under the hood, but is easier to use. Just bind the DataGrid's <code>ItemsSource</code> to a <code>DataTable.DefaultView</code> property:</p>
<pre><code><DataGrid ItemsSource="{Binding Data.DefaultView}" AutoGenerateColumns="True" />
</code></pre>
<p>Then you can define the columns however you like, eg:</p>
<pre><code>Data = new DataTable();
// create "fixed" columns
Data.Columns.Add("id");
Data.Columns.Add("image");
// create custom columns
Data.Columns.Add("Name1");
Data.Columns.Add("Name2");
// add one row as an object array
Data.Rows.Add(new object[] { 123, "image.png", "Foo", "Bar" });
</code></pre>
<hr/>
<p><strong>3rd approach:</strong> make use of the extensibility of .Net's type system. Specifically, use a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.customtypedescriptor.aspx" rel="noreferrer"><code>CustomTypeDescriptor</code></a>. This allows you to create a custom type at runtime; which in turn enables you to tell the DataGrid that your type has the properties "Name1", "Name2", ... "NameN", or whatever others you want. See <a href="https://stackoverflow.com/q/1834454/1001985">here</a> for a simple example of this approach.</p> |
18,626,039 | $apply already in progress error | <p>Stack trace:</p>
<pre><code>Error: $apply already in progress
at Error (<anonymous>)
at beginPhase (file:///android_asset/www/built.min.js:7:22740)
at Object.Scope.$apply (file:///android_asset/www/built.min.js:7:25967)
at navigator.geolocation.getCurrentPosition.that (file:///android_asset/www/built.min.js:13:8670)
at Object.geolocation.getCurrentPosition (file:///android_asset/www/plugins/org.apache.cordova.core.geolocation/www/geolocation.js:122:13)
at Object.getCurrentPosition (file:///android_asset/www/built.min.js:13:8589)
at Object.getCurrentPosition (file:///android_asset/www/built.min.js:13:8277)
at Object.getCurrentCity (file:///android_asset/www/built.min.js:13:8941)
at Object.$scope.locateDevice (file:///android_asset/www/built.min.js:13:10480)
at file:///android_asset/www/built.min.js:7:12292:7
</code></pre>
<p>refers to this code <a href="http://pastebin.com/B9V6yvFu">http://pastebin.com/B9V6yvFu</a></p>
<pre><code> getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {
navigator.geolocation.getCurrentPosition(function () {
var that = this,
args = arguments;
if (onSuccess) {
$rootScope.$apply(function () {
onSuccess.apply(that, args);
});
}
}, function () {
var that = this,
args = arguments;
if (onError) {
$rootScope.$apply(function () {
onError.apply(that, args);
});
}
}, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 18000000
});
})
</code></pre>
<p>Strange thing, on my LG4X it works fine, however on my samsung s2 it throws the above error. Any ideas whats wrong?</p> | 18,626,099 | 12 | 3 | null | 2013-09-05 00:46:08.537 UTC | 28 | 2021-01-07 02:54:51.807 UTC | 2016-07-28 17:22:44 UTC | null | 379,512 | null | 401,025 | null | 1 | 142 | angularjs|cordova|angularjs-digest | 182,714 | <p>You are getting this error because you are calling <code>$apply</code> inside an existing digestion cycle. </p>
<p>The big question is: why are you calling <code>$apply</code>? You shouldn't ever need to call <code>$apply</code> unless you are interfacing from a non-Angular event. The existence of <code>$apply</code> usually means I am doing something wrong (unless, again, the $apply happens from a non-Angular event).</p>
<p>If <code>$apply</code> really is appropriate here, consider using a "safe apply" approach:</p>
<p><a href="https://coderwall.com/p/ngisma">https://coderwall.com/p/ngisma</a></p> |
18,548,465 | Prevent scroll-bar from adding-up to the Width of page on Chrome | <p>I have a small issue trying to keep my .html pages at a consistent width on Chrome,
For example I have a page (1) with lots of contents that overflows the viewport's (right word?) height, so there's a vertical scroll-bar on that page (1). On page (2) i have the same layout (menus, divs,...etc) but less content, so no vertical scroll-bars in there.</p>
<p>The problem is that on page (1) the scroll-bars seem to push elements slightly to the left (adding-up to the width?) while everything appears well centered on page (2)</p>
<p>I'm still a beginner on HTML/CSS/JS, and I'm fairly convinced that this isn't so difficult, but i had no luck figuring out the solution. It does work as intended on IE10, and FireFox (non-interfering scroll-bars), I only encountered this on Chrome.</p> | 18,548,909 | 17 | 1 | null | 2013-08-31 13:03:55.543 UTC | 52 | 2022-09-18 21:10:57.433 UTC | 2017-05-10 23:20:05.9 UTC | null | 759,866 | null | 1,856,928 | null | 1 | 203 | html|css|google-chrome|scrollbar | 241,993 | <p>You can get the scrollbar size and then apply a margin to the container.</p>
<p>Something like this:</p>
<pre><code>var checkScrollBars = function(){
var b = $('body');
var normalw = 0;
var scrollw = 0;
if(b.prop('scrollHeight')>b.height()){
normalw = window.innerWidth;
scrollw = normalw - b.width();
$('#container').css({marginRight:'-'+scrollw+'px'});
}
}
</code></pre>
<p>CSS for remove the h-scrollbar:</p>
<pre><code>body{
overflow-x:hidden;
}
</code></pre>
<p>Try to take a look at this:
<a href="http://jsfiddle.net/NQAzt/" rel="noreferrer">http://jsfiddle.net/NQAzt/</a></p> |
19,914,349 | How can I make generated content selectable? | <p>I can have CSS display the ID for an element by using generated content, like this:</p>
<pre><code><style>
h2:hover:after {
color: grey;
content: "#" attr(id);
float: right;
font-size: smaller;
font-weight: normal;
}
</style>
<h2 id="my-id">My ID</h2>
<p>Pellentesque habitant morbi tristique senectus et netus et.</p>
</code></pre>
<p>How can I make that generated content ("#my-id") selectable so that the user can highlight and copy it?</p> | 19,914,366 | 2 | 2 | null | 2013-11-11 19:33:12.56 UTC | 5 | 2017-05-01 14:34:54.503 UTC | 2015-03-23 18:58:20.333 UTC | null | 2,756,409 | null | 327,466 | null | 1 | 36 | css|pseudo-element | 6,706 | <p>You can't make a pseudo-element selectable, as it doesn't exist in the DOM.</p>
<blockquote>
<p><strong><a href="http://www.w3.org/TR/CSS2/selector.html#pseudo-elements" rel="noreferrer">5.10 Pseudo-elements and pseudo-classes</a></strong></p>
<p>Neither pseudo-elements nor pseudo-classes appear in the document source or document tree.</p>
</blockquote> |
20,229,822 | Check if all values in list are greater than a certain number | <pre><code>my_list1 = [30,34,56]
my_list2 = [29,500,43]
</code></pre>
<p>How to I check if all values in list are >= 30? <code>my_list1</code> should work and <code>my_list2</code> should not.</p>
<p>The only thing I could think of doing was:</p>
<pre><code>boolean = 0
def func(ls):
for k in ls:
if k >= 30:
boolean = boolean + 1
else:
boolean = 0
if boolean > 0:
print 'Continue'
elif boolean = 0:
pass
</code></pre>
<h1>Update 2016:</h1>
<p>In hindsight, after dealing with bigger datasets where speed actually matters and utilizing <code>numpy</code>...I would do this:</p>
<pre><code>>>> my_list1 = [30,34,56]
>>> my_list2 = [29,500,43]
>>> import numpy as np
>>> A_1 = np.array(my_list1)
>>> A_2 = np.array(my_list2)
>>> A_1 >= 30
array([ True, True, True], dtype=bool)
>>> A_2 >= 30
array([False, True, True], dtype=bool)
>>> ((A_1 >= 30).sum() == A_1.size).astype(np.int)
1
>>> ((A_2 >= 30).sum() == A_2.size).astype(np.int)
0
</code></pre>
<p>You could also do something like: </p>
<pre><code>len([*filter(lambda x: x >= 30, my_list1)]) > 0
</code></pre> | 20,229,831 | 9 | 2 | null | 2013-11-26 23:01:18.693 UTC | 23 | 2022-08-11 05:21:44.5 UTC | 2017-07-24 17:23:02.297 UTC | null | 678,572 | null | 678,572 | null | 1 | 116 | python|list|function|max | 305,719 | <p>Use the <a href="http://docs.python.org/3/library/functions.html#all" rel="noreferrer"><code>all()</code> function</a> with a generator expression:</p>
<pre><code>>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False
</code></pre>
<p>Note that this tests for greater than <em>or equal to</em> 30, otherwise <code>my_list1</code> would not pass the test either.</p>
<p>If you wanted to do this in a function, you'd use:</p>
<pre><code>def all_30_or_up(ls):
for i in ls:
if i < 30:
return False
return True
</code></pre>
<p>e.g. as soon as you find a value that proves that there is <em>a</em> value below 30, you return <code>False</code>, and return <code>True</code> if you found no evidence to the contrary.</p>
<p>Similarly, you can use the <a href="http://docs.python.org/3/library/functions.html#any" rel="noreferrer"><code>any()</code> function</a> to test if <em>at least 1</em> value matches the condition.</p> |
15,417,130 | How to get latitude and longitude from google maps v3 api? | <p>I am trying create a map using google maps v3 api. I have found the below code over internet and I want to show the latitude and logitude in map window instead of address.</p>
<pre><code><script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35)
};
marker.setIcon(image);
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
});
</code></pre>
<p>Please some one help me to get and show latitude and longitude. Thank you very much.</p> | 15,417,374 | 6 | 0 | null | 2013-03-14 18:17:21.667 UTC | 5 | 2019-11-27 12:28:45.083 UTC | 2018-10-11 15:29:15.673 UTC | null | 1,341,556 | null | 1,341,556 | null | 1 | 14 | javascript|google-maps|google-maps-api-3 | 81,439 | <p>Where you have</p>
<pre><code> var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
infowindow.open(map, marker);
</code></pre>
<p>Change the infowindow line to read</p>
<pre><code> infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + place.geometry.location.lat() + ',' + place.geometry.location.lng());
</code></pre> |
15,361,189 | How to select all other values in an array except the ith element? | <p>I have a function using an array value represented as </p>
<pre><code> markers[i]
</code></pre>
<p><strong>How can I select all other values in an array except this one?</strong></p>
<p>The purpose of this is to reset all other Google Maps images to their original state but highlight a new one by changing the image.</p> | 15,361,261 | 7 | 0 | null | 2013-03-12 12:28:16.603 UTC | 7 | 2021-03-30 19:07:24.11 UTC | 2013-03-12 13:02:47.987 UTC | null | 218,196 | null | 1,842,443 | null | 1 | 41 | javascript|arrays | 95,546 | <p>Use <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>Array.prototype.splice</code></a> to get an array of elements excluding this one.</p>
<p>This affects the array permanently, so if you don't want that, create a copy first.</p>
<pre><code>var origArray = [0,1,2,3,4,5];
var cloneArray = origArray.slice();
var i = 3;
cloneArray.splice(i,1);
console.log(cloneArray.join("---"));
</code></pre> |
28,192,650 | IndexNotReadyException - Android Studio | <p>While changing the values of a <code>widget</code> in <code>properties</code> tab, <code>AndroidStudio</code> keeps on throwing <code>IndexNotReadyException</code>. But after few minutes while retrying, the error is not occurring.</p>
<p><strong>Here is the error log:</strong></p>
<pre><code>com.intellij.openapi.project.IndexNotReadyException: Please change caller according to com.intellij.openapi.project.IndexNotReadyException documentation
at com.intellij.util.indexing.FileBasedIndexImpl.handleDumbMode(FileBasedIndexImpl.java:856)
at com.intellij.util.indexing.FileBasedIndexImpl.ensureUpToDate(FileBasedIndexImpl.java:805)
at com.intellij.util.indexing.FileBasedIndexImpl.processExceptions(FileBasedIndexImpl.java:930)
at com.intellij.util.indexing.FileBasedIndexImpl.collectFileIdsContainingAllKeys(FileBasedIndexImpl.java:1190)
at com.intellij.util.indexing.FileBasedIndexImpl.processFilesContainingAllKeys(FileBasedIndexImpl.java:1018)
at com.intellij.psi.impl.search.PsiSearchHelperImpl$26.compute(PsiSearchHelperImpl.java:1096)
at com.intellij.psi.impl.search.PsiSearchHelperImpl$26.compute(PsiSearchHelperImpl.java:1093)
</code></pre>
<p>I've updated the <code>AndroidStudio</code>, to latest one. But still the error occurs. Any fix or work around?</p> | 28,193,427 | 5 | 2 | null | 2015-01-28 12:46:56.967 UTC | 10 | 2017-11-08 21:44:16.68 UTC | null | null | null | null | 2,147,481 | null | 1 | 58 | android|android-studio|ide | 55,036 | <p>Happens because of the background <code>indexing</code> processes.</p>
<p>When the IDE is indexing, if we try to change the values in properties tab, then <code>IndexNotReadyException</code> is thrown.</p>
<p>Wait till indexing is complete. </p>
<p>Hope Google fixes this in <code>AndroidStudio</code>'s next release!</p> |
48,375,904 | Read data from cloud firestore with firebase cloud function? | <p>I'm an Android developer and recently I've started working on a project based on firebase cloud functions and firestore database. I'm writing an HTTP trigger function that will take two parameters and compare that parameter value with the firestore data value and if the value matches then return a response of true or else false.</p>
<p><strong>Duplicate Question:</strong></p>
<p>Yes, there are some question already asked related to mine but they are not similar:</p>
<ol>
<li><p><a href="https://stackoverflow.com/questions/47522205/firestore-cloud-functions-how-to-read-from-another-document">Firestore + cloud functions: How to read from another document</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/43913139/firebase-http-cloud-functions-read-database-once">Firebase HTTP Cloud Functions - Read database once</a></p></li>
</ol>
<p><strong>Firebase Docs says</strong>: </p>
<blockquote>
<p>Cloud Firestore supports create, update, delete, and write events</p>
</blockquote>
<p>I want to read firestore value from HTTP trigger.</p>
<p><strong>What I have tried:</strong></p>
<pre><code>exports.userData = functions.https.onRequest((req, res) => {
const user = req.query.user;
const pass = req.query.pass;
});
</code></pre>
<p>I'm pretty much stuck at this part. Any help will be greatly appreciated. Thanks</p>
<p>P.S. I have very limited knowledge related to JS/TypeScript/NodeJS</p> | 49,516,133 | 3 | 4 | null | 2018-01-22 06:40:37.32 UTC | 16 | 2022-02-28 13:20:46.377 UTC | null | null | null | null | 6,699,134 | null | 1 | 32 | android|node.js|firebase|google-cloud-functions|google-cloud-firestore | 30,390 | <p>a bit late, but for any one else stumbling upon this.</p>
<pre><code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.someMethod = functions.https.onRequest((req, res) => {
var stuff = [];
var db = admin.firestore();
db.collection("Users").doc("7vFjDJ63DmhcQiEHwl0M7hfL3Kt1").collection("blabla").get().then(snapshot => {
snapshot.forEach(doc => {
var newelement = {
"id": doc.id,
"xxxx": doc.data().xxx,
"yyy": doc.data().yyy
}
stuff = stuff.concat(newelement);
});
res.send(stuff)
return "";
}).catch(reason => {
res.send(reason)
})
});
</code></pre> |
7,836,766 | Calling a stored procedure with asp.net | <p>If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from <strong>C#</strong> code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView. </p>
<p>Here is how the connection string is defined in the web.config:</p>
<pre><code><connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
</code></pre>
<p>The db server is a Microsoft SQL server. </p>
<p>Here is what I was looking for: </p>
<pre><code>ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
</code></pre>
<p>The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.</p> | 7,836,843 | 2 | 1 | null | 2011-10-20 13:37:19.85 UTC | 3 | 2013-10-09 03:00:10.307 UTC | 2013-10-09 03:00:10.307 UTC | null | 729,907 | null | 897,868 | null | 1 | 10 | asp.net|sql-server|stored-procedures|web-config|connection-string | 46,560 | <p>If it's a resource file like so:</p>
<p><code>private static readonly string connString = Resource1.connString;</code></p>
<p>Where connString is the name of the key. If it is a <code>web.config</code> file</p>
<p>Something like so:</p>
<p><code>private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"];</code> where conn is defined in your web config file.</p>
<pre><code><add key="strConn" value="User ID=test;Password=test;Initial Catalog=TestDB;Data Source=NameOfServer;"/>
</code></pre>
<p>Then call the sproc:</p>
<pre><code> //connString = the string of our database app found in the resource file
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("EMPDLL_selClientByClientID", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ClientID", SqlDbType.VarChar).Value = cID;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//more code
}
}
}
}
}
</code></pre>
<p>That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:</p>
<pre><code> Public Sub DeleteEmployee(ByVal lVID As Long)
Dim conMyData As SqlConnection
Dim cmdDelete As SqlCommand
Try
conMyData = New SqlConnection(connString)
cmdDelete = New SqlCommand("delEmployee", conMyData)
With cmdDelete
.CommandType = CommandType.StoredProcedure
'add the parameters
.Parameters.Add("@LoginID", SqlDbType.BigInt).Value = lVID 'the request
conMyData.Open() 'open a connection
.ExecuteNonQuery() 'execute it
End With
Catch ex As Exception
Throw ex
Finally
cmdDelete = Nothing
conMyData.Close()
conMyData = Nothing
End Try
End Sub
</code></pre>
<p>Of course you should use a <code>using</code> statement instead of <code>try/catch/finally</code> to ensure you clean up your resources that are being used.</p> |
7,727,876 | Any CPU dependent on C++/CLI dependent on native C dll (any cpu for c++/cli) | <p>Here's my problem.
I am wrapping a C dll in C#. To do this, I am first writing a C++/CLI wrapper. The native C library is linked to the C++/CLI wrapper. (Linker properties in C++/cli project).</p>
<p>Here's how it is all organised now:
- The native C .lib: both x86 and 64bit.</p>
<ul>
<li>1 solution containing 2 projects:
<ul>
<li>C++/CLI wrapper project to which is linked native C .lib</li>
<li>C# project referencing C++/CLI project</li>
</ul></li>
</ul>
<p>My problem comes from the fact that I need C# to target "Any CPU". But this option is not available in C++/CLI since it compiles directly to native code.</p>
<p>My idea to solve this is:
- Compile C++/CLI wrapper in x86 and then change the config and compile to 64 bit. When it compiles, I would like to tell it which dll to take based on the platform. ie: if compiling in 64bit, link 64 bit native C dll, else if x86, link x86 native C.
- With this done, I should then be able to have Any CPU target in my C# platform. Here again, instead of referencing my C++/CLI wrapper project, I would reference the required dll based on the target platform.</p>
<p>My questions are:</p>
<ul>
<li>How to I tell the C++/CLI project which .lib to link to based on the target platform?</li>
<li>How to I tell the C# project which C++/CLI dll to reference based on the target platform?</li>
</ul>
<p>Let me add that the <strong>C# project a CLASS LIBRARY</strong> to be used by an x86 or x64 client. </p>
<p>I hope my question is clear enough. Any helps would be appreciated !</p>
<p><strong>UPDATE</strong> based on:<a href="https://stackoverflow.com/questions/2583732/conditional-references-in-net-project-possible-to-get-rid-of-warning">Conditional references in .NET project, possible to get rid of warning?</a>...</p>
<p>So now I've edited my .csproj file using a condition to reference the dll as follows:</p>
<pre><code><ItemGroup>
<Reference Include="AlibCppWrapper, Version=1.0.4303.21410, Culture=neutral, PublicKeyToken=c0c17a53adc44091, processorArchitecture=AMD64"
Condition="$(Platform) == 'x64'">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\x64\Debug\AlibCppWrapper.dll</HintPath>
</Reference>
<Reference Include="AlibCppWrapper, Version=1.0.4303.21410, Culture=neutral, PublicKeyToken=c0c17a53adc44091, processorArchitecture=x86"
Condition="$(Platform) == 'x86'">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\Debug\AlibCppWrapper.dll</HintPath>
</Reference>
</ItemGroup>
</code></pre>
<p>Unfortunately this doesn't work as the $(Platform) is set to AnyCPU...</p> | 7,728,001 | 2 | 7 | null | 2011-10-11 14:43:32.93 UTC | 19 | 2020-10-28 20:12:46.21 UTC | 2017-05-23 10:32:59.757 UTC | null | -1 | null | 625,036 | null | 1 | 19 | c#|c|c++-cli|64-bit|x86 | 13,364 | <p>What you describe is known as "side-by-side assembly" (two versions of the same assembly, one 32 and the other 64 bit)... I think you will find these helpful:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/108971/using-side-by-side-assemblies-to-load-the-x64-or-x32-version-of-a-dll/156024#156024">Using Side-by-Side assemblies to load the x64 or x32 version of a DLL</a></li>
<li><a href="http://blogs.msdn.com/b/gauravseth/archive/2006/03/07/545104.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/gauravseth/archive/2006/03/07/545104.aspx</a></li>
<li><a href="http://www.thescarms.com/dotnet/Assembly.aspx" rel="nofollow noreferrer">http://www.thescarms.com/dotnet/Assembly.aspx</a></li>
</ul>
<p>EDIT - as per comment:</p>
<p>Here you can find a walkthrough for exactly your scenario: <a href="https://web.archive.org/web/20180118101655/http://scottbilas.com/blog/automatically-choose-32-or-64-bit-mixed-mode-dlls/" rel="nofollow noreferrer">.NET DLL wrapping C++/CLI DLL referencing a native DLL</a></p> |
7,891,427 | MATLAB: extract every nth element of vector | <p>Is there an easy way to extract every nth element of a vector in MATLAB? Say we have </p>
<pre><code>x = linspace(1,10,10);
</code></pre>
<p>Is there a command something like</p>
<pre><code>y = nth(x,3)
</code></pre>
<p>so that <code>y = 3 6 9</code>?</p>
<p>Cheers!</p> | 7,891,494 | 2 | 0 | null | 2011-10-25 15:06:48.08 UTC | 4 | 2015-04-19 16:36:39.027 UTC | null | null | null | null | 108,542 | null | 1 | 19 | matlab | 61,219 | <p>Try this:</p>
<pre><code>x = linspace(1, 10, 10);
n = 3;
y = x(1 : n : end); % => 1 4 7 10
y = x(n : n : end); % => 3 6 9
</code></pre> |
9,122,282 | How do I open a terminal application from node.js? | <p>I would like to be able to open <code>Vim</code> from node.js program running in the terminal, create some content, save and exit <code>Vim</code>, and then grab the contents of the file.</p>
<p>I'm trying to do something like this:</p>
<pre class="lang-coffee prettyprint-override"><code>filename = '/tmp/tmpfile-' + process.pid
editor = process.env['EDITOR'] ? 'vi'
spawn editor, [filename], (err, stdout, stderr) ->
text = fs.readFileSync filename
console.log text
</code></pre>
<p>However, when this runs, it just hangs the terminal.</p>
<p>I've also tried it with <code>exec</code> and got the same result.</p>
<p><strong>Update:</strong></p>
<p>This is complicated by the fact that this process is launched from a command typed at a prompt with <a href="http://nodejs.org/docs/latest/api/readline.html">readline</a> running. I completely extracted the relevant parts of my latest version out to a file. Here is it in its entirety:</p>
<pre class="lang-coffee prettyprint-override"><code>{spawn} = require 'child_process'
fs = require 'fs'
tty = require 'tty'
rl = require 'readline'
cli = rl.createInterface process.stdin, process.stdout, null
cli.prompt()
filename = '/tmp/tmpfile-' + process.pid
proc = spawn 'vim', [filename]
#cli.pause()
process.stdin.resume()
indata = (c) ->
proc.stdin.write c
process.stdin.on 'data', indata
proc.stdout.on 'data', (c) ->
process.stdout.write c
proc.on 'exit', () ->
tty.setRawMode false
process.stdin.removeListener 'data', indata
# Grab content from the temporary file and display it
text = fs.readFile filename, (err, data) ->
throw err if err?
console.log data.toString()
# Try to resume readline prompt
cli.prompt()
</code></pre>
<p>The way it works as show above, is that it shows a prompt for a couple of seconds, and then launches in to Vim, but the TTY is messed up. I can edit, and save the file, and the contents are printed correctly. There is a bunch of junk printed to terminal on exit as well, and Readline functionality is broken afterward (no Up/Down arrow, no Tab completion).</p>
<p>If I uncomment the <code>cli.pause()</code> line, then the TTY is OK in Vim, but I'm stuck in insert mode, and the <code>Esc</code> key doesn't work. If I hit <code>Ctrl-C</code> it quits the child and parent process.</p> | 17,110,285 | 3 | 6 | null | 2012-02-03 00:51:28.433 UTC | 13 | 2021-06-27 12:04:09.857 UTC | 2012-02-03 19:20:35.623 UTC | null | 1,129,076 | null | 1,129,076 | null | 1 | 27 | node.js|vim|terminal|coffeescript|readline | 15,741 | <p>You can inherit stdio from the main process.</p>
<pre><code>const child_process = require('child_process')
var editor = process.env.EDITOR || 'vi';
var child = child_process.spawn(editor, ['/tmp/somefile.txt'], {
stdio: 'inherit'
});
child.on('exit', function (e, code) {
console.log("finished");
});
</code></pre>
<p>More options here: <a href="http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options" rel="noreferrer">http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options</a> </p> |
9,098,022 | Problems converting byte array to string and back to byte array | <p>There are a lot of questions with this topic, the same solution, but this doesn't work for me. I have a simple test with an encryption. The encryption/decryption itself works (as long as I handle this test with the byte array itself and not as Strings). The problem is that don't want to handle it as byte array but as String, but when I encode the byte array to string and back, the resulting byte array differs from the original byte array, so the decryption doesn't work anymore. I tried the following parameters in the corresponding string methods: UTF-8, UTF8, UTF-16, UTF8. None of them work. The resulting byte array differs from the original. Any ideas why this is so?</p>
<p>Encrypter:</p>
<pre><code>public class NewEncrypter
{
private String algorithm = "DESede";
private Key key = null;
private Cipher cipher = null;
public NewEncrypter() throws NoSuchAlgorithmException, NoSuchPaddingException
{
key = KeyGenerator.getInstance(algorithm).generateKey();
cipher = Cipher.getInstance(algorithm);
}
public byte[] encrypt(String input) throws Exception
{
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] inputBytes = input.getBytes("UTF-16");
return cipher.doFinal(inputBytes);
}
public String decrypt(byte[] encryptionBytes) throws Exception
{
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] recoveredBytes = cipher.doFinal(encryptionBytes);
String recovered = new String(recoveredBytes, "UTF-16");
return recovered;
}
}
</code></pre>
<p>This is the test where I try it:</p>
<pre><code>public class NewEncrypterTest
{
@Test
public void canEncryptAndDecrypt() throws Exception
{
String toEncrypt = "FOOBAR";
NewEncrypter encrypter = new NewEncrypter();
byte[] encryptedByteArray = encrypter.encrypt(toEncrypt);
System.out.println("encryptedByteArray:" + encryptedByteArray);
String decoded = new String(encryptedByteArray, "UTF-16");
System.out.println("decoded:" + decoded);
byte[] encoded = decoded.getBytes("UTF-16");
System.out.println("encoded:" + encoded);
String decryptedText = encrypter.decrypt(encoded); //Exception here
System.out.println("decryptedText:" + decryptedText);
assertEquals(toEncrypt, decryptedText);
}
}
</code></pre> | 9,098,905 | 4 | 6 | null | 2012-02-01 14:58:59.363 UTC | 29 | 2016-08-19 07:07:37.227 UTC | null | null | null | null | 319,773 | null | 1 | 61 | java|string|encryption|bytearray | 80,794 | <p>It is not a good idea to store encrypted data in Strings because they are for human-readable text, not for arbitrary binary data. For binary data it's best to use <code>byte[]</code>.</p>
<p>However, if you <strong>must</strong> do it you should use an encoding that has a <em>1-to-1 mapping</em> between bytes and characters, that is, where every byte sequence can be mapped to a unique sequence of characters, and back. One such encoding is <strong>ISO-8859-1</strong>, that is:</p>
<pre><code> String decoded = new String(encryptedByteArray, "ISO-8859-1");
System.out.println("decoded:" + decoded);
byte[] encoded = decoded.getBytes("ISO-8859-1");
System.out.println("encoded:" + java.util.Arrays.toString(encoded));
String decryptedText = encrypter.decrypt(encoded);
</code></pre>
<p>Other common encodings that don't lose data are <strong>hexadecimal</strong> and <strong>base64</strong>, but sadly you need a helper library for them. The standard API doesn't define classes for them.</p>
<p>With UTF-16 the program would fail for two reasons:</p>
<ol>
<li>String.getBytes("UTF-16") adds a byte-order-marker character to the output to identify the order of the bytes. You should use UTF-16LE or UTF-16BE for this to not happen.</li>
<li>Not all sequences of bytes can be mapped to characters in UTF-16. First, text encoded in UTF-16 must have an even number of bytes. Second, UTF-16 has a mechanism for encoding unicode characters beyond U+FFFF. This means that e.g. there are sequences of 4 bytes that map to only one unicode character. For this to be possible the first 2 bytes of the 4 don't encode any character in UTF-16.</li>
</ol> |
9,308,234 | User agent stylesheet overriding my table style? Twitter Bootstrap | <p>I'm using twitter bootstrap. My problem is that font-sizes in tables are wrong. For some reason the User Agent stylesheet is overriding the bootstrap table styles. </p>
<p>On the twitter bootstrap page (<a href="http://twitter.github.com/bootstrap/base-css.html" rel="noreferrer">http://twitter.github.com/bootstrap/base-css.html</a>) everything is of course working correctly. </p>
<p>In my inspector I see the following difference:</p>
<p>My page:</p>
<p><img src="https://i.stack.imgur.com/VLgKh.png" alt="CSS style for my page"></p>
<p>The twitter bootstrap page:</p>
<p><img src="https://i.stack.imgur.com/WuVMq.png" alt="CSS style for twitter bootstrap page"></p>
<p>So definitely the problem is that the user agent stylesheet is overriding the bootstrap styles. </p>
<p>I haven't been able to figure out why this is different on my page and the twitter bootstrap page. </p>
<p>Most of the other CSS is working fine.</p>
<p>My css import: </p>
<pre><code><link href="/media/bootstrap/css/bootstrap.css" rel= "stylesheet">
</code></pre>
<p>CSS import on twitter bootstrap page:</p>
<pre><code><link href="assets/css/bootstrap.css" rel="stylesheet">
</code></pre> | 9,656,558 | 5 | 6 | null | 2012-02-16 09:02:02.85 UTC | 12 | 2016-09-01 18:49:16.167 UTC | null | null | null | null | 258,038 | null | 1 | 67 | css|twitter-bootstrap | 41,595 | <p>I actually figured this out myself. I had the <code><!DOCTYPE html></code> tag wrongly written. So if you have this problem make sure the doctype declaration is correct!</p> |
8,484,722 | Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges? | <p>I've looked at a number of similar questions and so I'm demonstrating that I've checked the basics. Though of course, that doesn't mean I haven't missed something totally obvious. :-)</p>
<p>My question is: why am I denied access on a user with the privileges to do what I'm trying to do and where I have already typed the password and been granted access? (For the sake of completeness, I tried typing the wrong password just to make sure that MySQL client would deny me access at program start.)</p>
<p>Background:</p>
<p>Logged in to the shell of the machine running the MySQL server via ssh, I log in as root:</p>
<pre><code>[myname@host ~]$ mysql -u root -p -hlocalhost
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 62396
Server version: 5.5.18-log MySQL Community Server (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
</code></pre>
<p>Awesome. My reading of the answers to similar questions suggests that I should make sure the the privileges are current with what is in the grant tables</p>
<pre><code>mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)
mysql>
</code></pre>
<p>Next make sure I am who I think I am:</p>
<pre><code>mysql> SELECT user();
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
</code></pre>
<p>...and really <em>really</em> make sure:</p>
<pre><code>mysql> SELECT current_user();
+----------------+
| current_user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
mysql>
</code></pre>
<p>So far so good. Now what privileges do I have?</p>
<pre><code>mysql> SHOW GRANTS FOR 'root'@'localhost';
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, RELOAD, SHUTDOWN, PROCESS, FILE, REFERENCES, INDEX, ALTER, SHOW DATABASES, SUPER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, REPLICATION SLAVE, REPLICATION CLIENT, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, CREATE USER, EVENT, TRIGGER ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '[OBSCURED]' WITH GRANT OPTION |
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
</code></pre>
<p>Now that's a little hard to read, so lets try this way (you will also get to see that there is a non-localhost 'root' user):</p>
<pre><code>mysql> SELECT * FROM mysql.user WHERE User='root'\G
*************************** 1. row ***************************
Host: localhost
User: root
Password: *[OBSCURED]
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
Reload_priv: Y
Shutdown_priv: Y
Process_priv: Y
File_priv: Y
Grant_priv: Y
References_priv: Y
Index_priv: Y
Alter_priv: Y
Show_db_priv: Y
Super_priv: Y
Create_tmp_table_priv: Y
Lock_tables_priv: Y
Execute_priv: Y
Repl_slave_priv: Y
Repl_client_priv: Y
Create_view_priv: Y
Show_view_priv: Y
Create_routine_priv: Y
Alter_routine_priv: Y
Create_user_priv: Y
Event_priv: Y
Trigger_priv: Y
ssl_type:
ssl_cipher:
x509_issuer:
x509_subject:
max_questions: 0
max_updates: 0
max_connections: 0
max_user_connections: 0
*************************** 2. row ***************************
Host: [HOSTNAME].com
User: root
Password: *[OBSCURED]
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
Reload_priv: Y
Shutdown_priv: Y
Process_priv: Y
File_priv: Y
Grant_priv: Y
References_priv: Y
Index_priv: Y
Alter_priv: Y
Show_db_priv: Y
Super_priv: Y
Create_tmp_table_priv: Y
Lock_tables_priv: Y
Execute_priv: Y
Repl_slave_priv: Y
Repl_client_priv: Y
Create_view_priv: Y
Show_view_priv: Y
Create_routine_priv: Y
Alter_routine_priv: Y
Create_user_priv: Y
Event_priv: Y
Trigger_priv: Y
ssl_type:
ssl_cipher:
x509_issuer:
x509_subject:
max_questions: 0
max_updates: 0
max_connections: 0
max_user_connections: 0
2 rows in set (0.00 sec)
</code></pre>
<p>Awesome! MySQL thinks that I am root@localhost and root@localhost has all those privileges. That means I ought to be able to do what I want, right?</p>
<pre><code>mysql> GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]' WITH GRANT OPTION;
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
</code></pre>
<p>How could I have screwed up something this basic?</p>
<p>Side note: for anyone who wants to suggest that I not have a user named root with all privileges, that's great and something I'll consider doing once I can give another user some privileges.</p>
<p>Thank you!</p> | 8,981,464 | 13 | 4 | null | 2011-12-13 05:26:18.7 UTC | 54 | 2019-11-23 16:52:57.007 UTC | 2015-08-01 03:52:26.047 UTC | null | 2,947,415 | null | 482,350 | null | 1 | 187 | mysql|mysql-error-1045 | 615,958 | <p>Notice how the output of</p>
<pre><code>SHOW GRANTS FOR 'root'@'localhost';
</code></pre>
<p>did not say 'ALL PRIVILEGES' but had to spell out what root@localhost has.</p>
<p>GRANT ALL PRIVILEGES will fail, because a user can not grant what he/she does not have,
and the server seem to think something is not here ...</p>
<p>Now, what's missing then ?</p>
<p>On my system, I get this:</p>
<pre><code>mysql> select version();
+------------+
| version() |
+------------+
| 5.5.21-log |
+------------+
1 row in set (0.00 sec)
mysql> SHOW GRANTS FOR 'root'@'localhost';
+---------------------------------------------------------------------+
| Grants for root@localhost |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+
2 rows in set (0.00 sec)
mysql> SELECT * FROM mysql.user WHERE User='root' and Host='localhost'\G
*************************** 1. row ***************************
Host: localhost
User: root
Password:
Select_priv: Y
Insert_priv: Y
Update_priv: Y
Delete_priv: Y
Create_priv: Y
Drop_priv: Y
Reload_priv: Y
Shutdown_priv: Y
Process_priv: Y
File_priv: Y
Grant_priv: Y
References_priv: Y
Index_priv: Y
Alter_priv: Y
Show_db_priv: Y
Super_priv: Y
Create_tmp_table_priv: Y
Lock_tables_priv: Y
Execute_priv: Y
Repl_slave_priv: Y
Repl_client_priv: Y
Create_view_priv: Y
Show_view_priv: Y
Create_routine_priv: Y
Alter_routine_priv: Y
Create_user_priv: Y
Event_priv: Y
Trigger_priv: Y
Create_tablespace_priv: Y <----------------------------- new column in 5.5
ssl_type:
ssl_cipher:
x509_issuer:
x509_subject:
max_questions: 0
max_updates: 0
max_connections: 0
max_user_connections: 0
plugin: <------------------------------- new column in 5.5
authentication_string: <------------------------------- new column in 5.5
1 row in set (0.00 sec)
</code></pre>
<p>There are also new tables in 5.5, such as mysql.proxies_user: make sure you have them.</p>
<p>When installing a brand new mysql server instance, the install script will create all the mysql.* tables with the proper structure.</p>
<p>When upgrading from an old version, make sure the proper upgrade procedure (mysql_upgrade) is used, which will add the missing tables / columns.</p>
<p>It is only a guess, but it seems mysql_upgrade was not done for this instance, causing the behavior seen.</p> |
5,424,520 | How can I call a java static method in clojure? | <p>I wish to call class on the String class. How can I access this static method?</p> | 5,424,589 | 4 | 0 | null | 2011-03-24 19:34:38.307 UTC | 6 | 2013-02-26 15:30:42.74 UTC | null | null | null | null | 190,822 | null | 1 | 36 | clojure | 17,586 | <p>You can call a static method using <code>(ClassName/methodName arguments)</code>.</p>
<p>However <code>class</code> is not a static method, it's a java keyword and you don't need it in clojure. To get the Class object associated with the String class, just use <code>String</code>.</p> |
4,916,701 | How to implement a caching model without violating MVC pattern? | <p>I have an ASP.NET MVC 3 (Razor) Web Application, with a particular page which is <strong>highly database intensive</strong>, and user experience is of the upmost priority.</p>
<p>Thus, i am introducing caching on this particular page.</p>
<p>I'm trying to figure out a way to implement this caching pattern whilst keeping my controller <strong>thin</strong>, like it currently is without caching:</p>
<pre><code>public PartialViewResult GetLocationStuff(SearchPreferences searchPreferences)
{
var results = _locationService.FindStuffByCriteria(searchPreferences);
return PartialView("SearchResults", results);
}
</code></pre>
<p>As you can see, the controller is very thin, as it should be. It doesn't care about how/where it is getting it's info from - that is the job of the service.</p>
<p>A couple of notes on the flow of control:</p>
<ol>
<li>Controllers get DI'ed a particular <strong>Service</strong>, depending on it's area. In this example, this controller get's a <strong>LocationService</strong></li>
<li><strong>Services</strong> call through to an <code>IQueryable<T></code> <strong>Repository</strong> and materialize results into <code>T</code> or <code>ICollection<T></code>.</li>
</ol>
<p>How i want to implement caching:</p>
<ul>
<li><strong>I can't use Output Caching</strong> - for a few reasons. First of all, this action method is invoked from the client-side (jQuery/AJAX), via <code>[HttpPost]</code>, which according to HTTP standards should not be cached as a request. Secondly, i don't want to cache purely based on the HTTP request arguments - the cache logic is a lot more complicated than that - there is actually two-level caching going on.</li>
<li>As i hint to above, i need to use regular data-caching, e.g <code>Cache["somekey"] = someObj;</code>.</li>
<li>I don't want to implement a generic caching mechanism where <em>all</em> calls via the service go through the cache first - <strong>i only want caching on this particular action method</strong>.</li>
</ul>
<p>First thought's would tell me to create another service (which inherits <strong>LocationService</strong>), and provide the caching workflow there (check cache first, if not there call db, add to cache, return result).</p>
<p>That has two problems:</p>
<ol>
<li>The services are basic <strong>Class Libraries</strong> - no references to anything extra. I would need to add a reference to <code>System.Web</code> here.</li>
<li>I would have to access the HTTP Context outside of the web application, which is considered bad practice, not only for testability, but in general - right?</li>
</ol>
<p>I also thought about using the <code>Models</code> folder in the Web Application (which i currently use only for <strong>ViewModels</strong>), but having a cache service in a models folder just doesn't sound right.</p>
<p>So - any ideas? Is there a MVC-specific thing (like Action Filter's, for example) i can use here? </p>
<p>General advice/tips would be greatly appreciated.</p> | 4,916,842 | 5 | 1 | null | 2011-02-06 22:38:08.18 UTC | 14 | 2016-08-06 20:30:01.927 UTC | 2011-02-06 23:24:28.167 UTC | null | 29,407 | null | 321,946 | null | 1 | 29 | c#|asp.net-mvc|caching|architecture|asp.net-mvc-3 | 11,335 | <p>My answer is based on the assumption that your services implement an interface, for example the type of _locationService is actually ILocationService but is injected with a concrete LocationService. Create a CachingLocationService that implements the ILocationService interface and change your container configuration to inject that caching version of the service to this controller. The CachingLocationService would itself have a dependecy on ILocationService which would be injected with the original LocationService class. It would use this to execute the real business logic and concern itself only with pulling and pushing from cache.</p>
<p>You don't need to create CachingLocationService in the same assembly as the original LocationService. It could be in your web assembly. However, personally I'd put it in the original assembly and add the new reference.</p>
<p>As for adding a dependency on HttpContext; you can remove this by taking a dependency on </p>
<pre><code>Func<HttpContextBase>
</code></pre>
<p>and injecting this at runtime with something like </p>
<pre><code>() => HttpContext.Current
</code></pre>
<p>Then in your tests you can mock HttpContextBase, but you may have trouble mocking the Cache object without using something like TypeMock.</p>
<hr>
<p>Edit: On further reading up on the .NET 4 System.Runtime.Caching namespace, your CachingLocationService should take a dependency on ObjectCache. This is the abstract base class for cache implementations. You could then inject that with System.Runtime.Caching.MemoryCache.Default, for instance.</p> |
5,308,584 | How to return text from Native (C++) code | <p>I am using Pinvoke for Interoperability between Native(C++) code and Managed(C#) code. What i want to achieve is get some text from native code into my managed code. For this i try lot lot of things,e.g passing string/stringbuilder by ref, using [IN] and [OUT], Marshaling to LPSTR, returning string from function etc. but nothing works in my case. Any help with some small code would be highly appreciated.</p> | 5,308,793 | 5 | 0 | null | 2011-03-15 07:16:13.103 UTC | 18 | 2022-06-02 06:32:20.677 UTC | 2011-03-29 17:38:41.16 UTC | null | 116,875 | null | 586,528 | null | 1 | 33 | c#|c++|string|pinvoke | 14,080 | <p>I'd do it with a <code>BSTR</code> since it means you don't have to call into native twice per string, once to get the length and then once to get the contents.</p>
<p>With a <code>BSTR</code> the marshaller will take care of deallocating the <code>BSTR</code> with the right memory manager so you can safely pass it out of your C++ code.</p>
<p><strong>C++</strong></p>
<pre><code>#include <comutil.h>
BSTR GetSomeText()
{
return ::SysAllocString(L"Greetings from the native world!");
}
</code></pre>
<p><strong>C#</strong></p>
<pre><code>[DllImport(@"test.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.BStr)]
private static extern string GetSomeText();
</code></pre>
<p>There is one minor drawback of the <code>BSTR</code>, namely that it carries a UTF-16 payload but your source data may well be <code>char*</code>.</p>
<p>To overcome this you can wrap up the conversion from <code>char*</code> to <code>BSTR</code> like this:</p>
<pre><code>BSTR ANSItoBSTR(const char* input)
{
BSTR result = NULL;
int lenA = lstrlenA(input);
int lenW = ::MultiByteToWideChar(CP_ACP, 0, input, lenA, NULL, 0);
if (lenW > 0)
{
result = ::SysAllocStringLen(0, lenW);
::MultiByteToWideChar(CP_ACP, 0, input, lenA, result, lenW);
}
return result;
}
</code></pre>
<p>That's the hardest one out of the way, and now it's easy to add other wrappers to convert to <code>BSTR</code> from <code>LPWSTR</code>, <code>std::string</code>, <code>std::wstring</code> etc.</p> |
5,107,651 | Android: Disable text selection in a webview | <p>I am using a webview to present some formatted stuff in my app. For some interaction (which are specific to certain dom elements) I use javascript and <code>WebView.addJavascriptInterface()</code>. Now, I want to recognize a long touch. Unfortunately, <code>onLongTouch</code>, in Android 2.3 the handles for text selection are displayed. </p>
<p>How can I turn off this text selection <em>without</em> setting the <code>onTouchListener</code> and return true? (Then, the interaction with the "website" doesn't work anymore.</p> | 5,108,800 | 7 | 1 | null | 2011-02-24 16:41:40.993 UTC | 29 | 2020-06-01 07:38:50.81 UTC | 2017-12-01 11:58:21.387 UTC | null | 3,885,376 | null | 169,748 | null | 1 | 60 | android|webview | 63,731 | <p>I figured it out!! This is how you can implement your own longtouchlistener. In the function longTouch you can make a call to your javascript interface.</p>
<pre><code>var touching = null;
$('selector').each(function() {
this.addEventListener("touchstart", function(e) {
e.preventDefault();
touching = window.setTimeout(longTouch, 500, true);
}, false);
this.addEventListener("touchend", function(e) {
e.preventDefault();
window.clearTimeout(touching);
}, false);
});
function longTouch(e) {
// do something!
}
</code></pre>
<p>This works.</p> |
5,443,166 | How to Convert UIView to PDF within iOS? | <p>There are a lot of resources about how to display a PDF in an App's <code>UIView</code>. What I am working on now is to create a PDF from <code>UIViews</code>. </p>
<p>For example, I have a <code>UIView</code>, with subviews like Textviews, <code>UILabels</code>, <code>UIImages</code>, so how can I convert a <strong>big</strong> <code>UIView</code> as a whole including all its subviews and subsubviews to a PDF?</p>
<p>I have checked <a href="https://developer.apple.com/library/archive/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html" rel="noreferrer">Apple's iOS reference</a>. However, it only talks about writing pieces of text/image to a PDF file.</p>
<p>The problem I am facing is that the content I want to write to a file as PDF is a lot. If I write them to the PDF piece by piece, it is going to be huge work to do.
That's why I am looking for a way to write <code>UIViews</code> to PDFs or even bitmaps.</p>
<p>I have tried the source code I copied from other Q/A within Stack Overflow. But it only gives me a blank PDF with the <code>UIView</code> bounds size.</p>
<pre><code>-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView drawRect:aView.bounds];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}
</code></pre> | 6,566,696 | 7 | 0 | null | 2011-03-26 15:06:29.723 UTC | 71 | 2019-12-30 10:57:24.823 UTC | 2019-12-30 10:57:24.823 UTC | null | 1,033,581 | null | 663,645 | null | 1 | 90 | ios|pdf|uiview|uiimage|core-graphics | 55,404 | <p>Note that the following method creates <strong>just a bitmap</strong> of the view; it does not create actual typography.</p>
<pre><code>(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView.layer renderInContext:pdfContext];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}
</code></pre>
<p>Also make sure you import:
QuartzCore/QuartzCore.h </p> |
5,035,132 | How to Sync iPhone Core Data with web server, and then push to other devices? | <p>I have been working on a method to sync core data stored in an iPhone application between multiple devices, such as an iPad or a Mac. There are not many (if any at all) sync frameworks for use with Core Data on iOS. However, I have been thinking about the following concept:</p>
<ol>
<li>A change is made to the local core data store, and the change is saved. (a) If the device is online, it tries to send the changeset to the server, including the device ID of the device which sent the changeset. (b) If the changeset does not reach the server, or if the device is not online, the app will add the change set to a queue to send when it does come online.</li>
<li>The server, sitting in the cloud, merges the specific change sets it receives with its master database.</li>
<li>After a change set (or a queue of change sets) is merged on the cloud server, the server pushes all of those change sets to the other devices registered with the server using some sort of polling system. (I thought to use Apple's Push services, but apparently according to the comments this is not a workable system.)</li>
</ol>
<p>Is there anything fancy that I need to be thinking about? I have looked at REST frameworks such as <a href="http://iphoneonrails.com/" rel="noreferrer">ObjectiveResource</a>, <a href="http://coreresource.org/" rel="noreferrer">Core Resource</a>, and <a href="https://github.com/lukeredpath/RestfulCoreData" rel="noreferrer">RestfulCoreData</a>. Of course, these are all working with Ruby on Rails, which I am not tied to, but it's a place to start. The main requirements I have for my solution are:</p>
<ol>
<li>Any changes should be sent in the background without pausing the main thread.</li>
<li>It should use as little bandwidth as possible.</li>
</ol>
<p>I have thought about a number of the challenges:</p>
<ol>
<li>Making sure that the object IDs for the different data stores on different devices are attached on the server. That is to say, I will have a table of object IDs and device IDs, which are tied via a reference to the object stored in the database. I will have a record (DatabaseId [unique to this table], ObjectId [unique to the item in the whole database], Datafield1, Datafield2), the ObjectId field will reference another table, AllObjects: (ObjectId, DeviceId, DeviceObjectId). Then, when the device pushes up a change set, it will pass along the device Id and the objectId from the core data object in the local data store. Then my cloud server will check against the objectId and device Id in the AllObjects table, and find the record to change in the initial table.</li>
<li>All changes should be timestamped, so that they can be merged.</li>
<li>The device will have to poll the server, without using up too much battery.</li>
<li>The local devices will also need to update anything held in memory if/when changes are received from the server.</li>
</ol>
<p>Is there anything else I am missing here? What kinds of frameworks should I look at to make this possible?</p> | 5,164,878 | 8 | 6 | null | 2011-02-17 21:52:25.837 UTC | 311 | 2017-12-14 15:30:38.27 UTC | 2012-07-28 11:28:24.457 UTC | null | 992,887 | null | 353,137 | null | 1 | 303 | iphone|ios|core-data|sync|data-synchronization | 89,980 | <p>I suggest carefully reading and implementing the sync strategy discussed by Dan Grover at iPhone 2009 conference, available <a href="http://iphone2009.crowdvine.com/talk/presentation_file/5104/Grover_Syncing.pdf" rel="noreferrer">here</a> as a pdf document.</p>
<p>This is a viable solution and is not that difficult to implement (Dan implemented this in several of its applications), overlapping the solution described by Chris. For an in-depth, theoretical discussion of syncing, see the paper from Russ Cox (MIT) and William Josephson (Princeton):</p>
<p><a href="http://publications.csail.mit.edu/tmp/MIT-CSAIL-TR-2005-014.pdf" rel="noreferrer">File Synchronization with Vector Time Pairs</a></p>
<p>which applies equally well to core data with some obvious modifications. This provides an overall much more robust and reliable sync strategy, but requires more effort to be implemented correctly.</p>
<p>EDIT:</p>
<p>It seems that the Grover's pdf file is no longer available (broken link, March 2015). UPDATE: the link is available through the Way Back Machine <a href="https://web.archive.org/web/20120324051431/http://iphone2009.crowdvine.com/talk/presentation_file/5104/Grover_Syncing.pdf" rel="noreferrer">here</a></p>
<p>The Objective-C framework called <a href="https://github.com/mzarra/ZSync" rel="noreferrer">ZSync</a> and developed by Marcus Zarra has been deprecated, given that iCloud finally seems to support correct core data synchronization. </p> |
5,505,515 | How do I embed source code or HTML in Open Office Org Presentations without using screenshots? | <p>I need to write a lot of class courses <strong>presentations</strong> to my programming class, and I constantly need to show <strong>source code</strong> (mainly <strong>C</strong> code).</p>
<p><img src="https://i.stack.imgur.com/W2c1U.png" alt="enter image description here"></p>
<p>I don't find a easy way to:</p>
<ol>
<li>Copy my <strong>source code</strong> from my editor (kate) and </li>
<li>Paste it formated and with source <strong>highlighted</strong> to an <strong>Open Office Presentation</strong> (OOP). </li>
</ol>
<p>What I use to do is a <strong>snapshot</strong> if the code is small, or to stop presentation and open Kate in the datashow if it is too big.</p>
<p>In this <a href="https://stackoverflow.com/questions/281025/how-to-format-a-block-of-code-within-a-presentation">other question</a> some suggest to embed <strong>HTML</strong> code. So I installed <strong>QSource-Highlight</strong> that easily <strong>convert C code to HTML</strong> (also gnu source-highlight, code2html, and so on). None of them can convert source code to a version of a highlighted <strong>RTF</strong> (rich text format), that would be another way to go.</p>
<p>Having HTML doesn't help, because I can't find a easy way to <strong>insert HTML into a presentation</strong> either. This site show a very trick windows <a href="http://www.fauskes.net/nb/syntaxms/" rel="noreferrer">solution</a>. It needs to convert c code to HTML using an specific windows program that has an option to copy the HTML as RTF, after that you need to past the RTF in Word or Wordpad, and after that you special past RTF to PowerPoint. All good, but I'm a <strong>linux</strong> user, and I think there might be a better way.</p>
<p>Also, there is another possible solution, installing <strong>coooder</strong> extension to openoffice. I don't know why, but trying to install this extension in my system gives me an error. Synaptic tell's me that openoffice.org-core and a lot of other should be marked. I click next, and it tells me it wants to remove all the packages, and that coooder needs this packages to work, and so it is not going to be installed. Well...</p>
<p><em>I'm using linux UBUNTU 10.04, and Open Office 3.2</em></p>
<p>Thanks!
Beco.</p>
<p>PS.:
This question is debated in <a href="https://meta.stackexchange.com/questions/85493/question-meta-question-meta-meta-question">meta-so</a> as possible duplication of the question cited above. But it is my understanding that the older question doesn't solve this <strong>specific</strong> problem.</p>
<p>PPS.: About the coooder bug, I've launched a bug report <a href="https://bugs.launchpad.net/ubuntu/+source/ooo-build-extensions/+bug/577434" rel="noreferrer">here</a></p>
<hr>
<p>Edit (2015-08-19)</p>
<p>To insert a RTF text to presentation LibreOffice you can use menu <code>insert</code>, <code>file</code>, and <code>rtf</code> (or <code>HTML</code>).</p> | 5,645,181 | 9 | 6 | null | 2011-03-31 19:51:35.23 UTC | 13 | 2017-06-07 01:26:27.52 UTC | 2017-05-23 12:34:22.307 UTC | null | -1 | null | 670,521 | null | 1 | 52 | syntax-highlighting|openoffice.org|libreoffice|presentation | 64,156 | <p>Some people says that copying code from <a href="http://www.eclipse.org/downloads/" rel="noreferrer">Eclipse</a> editor works well (UPDATE: Proven <strong>FALSE</strong>). Another alternative is exporting to RTF (can also export line numbers), or to clipboard, from <a href="http://www.andre-simon.de/doku/highlight/en/highlight_langs.html" rel="noreferrer">Highlight</a> and then opening/pasting it in OpenOffice.org. (UPDATE: Proven <strong>TRUE</strong>)</p>
<p>Here is a Highlight GUI screen shot:
<img src="https://i.stack.imgur.com/6fB3F.png" alt="Highlight GUI (KDE)"></p>
<p>You can also switch from OpenOffice.org to <a href="http://www.omgubuntu.co.uk/2011/01/libreoffice-3-3-released/" rel="noreferrer">LibreOffice</a>, and get COOoder from <a href="http://libreplanet.org/wiki/Group:OpenOfficeExtensions/List" rel="noreferrer">here</a>.</p> |
29,498,976 | How to return a smart pointer to a member variable? | <p>I'm attempting to create an accessor for a class member variable using smart pointers. Here's the code:</p>
<pre><code>class MyResource
{
};
class MyClass
{
public:
std::unique_ptr<MyResource> getResource();
private:
std::unique_ptr<MyResource> resource;
};
std::unique_ptr<MyResource> MyClass::getResource()
{
return this->resource;
}
</code></pre>
<p>The error I get trying to compile this:</p>
<blockquote>
<p>cannot access private member declared in class 'std::unique_ptr<_Ty>'</p>
</blockquote>
<p>Adding <code>.get</code> to <code>this->resource</code> of course doesn't work because the return type changes.</p>
<p>Should I not be using a unique_ptr here? Is this just a syntax issue? Am I totally on the wrong track?</p>
<p><strong>my background with smart pointers:</strong>
I've been using plain-old-pointers for a couple of years now in part because I can't find a solid explanation of when to use which types of smart pointers and how to go about using them. I'm tired of making excuses, so I'm just diving in. I think I understand what smart pointers are and why to use them, but I understand very little of the details. At the moment I'm totally lost in <a href="https://stackoverflow.com/questions/1119962/smart-pointers-when-where-and-how">the</a> <a href="https://stackoverflow.com/questions/8242320/smart-pointers-why-use-them-and-which-to-use">endless</a> <a href="https://stackoverflow.com/questions/417481/pointers-smart-pointers-or-shared-pointers">Q&A</a> <a href="https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one">about</a> <a href="https://stackoverflow.com/questions/6876751/differences-between-unique-ptr-and-shared-ptr">smart</a> <a href="https://stackoverflow.com/questions/5576922/pimpl-shared-ptr-or-unique-ptr">pointers</a>.</p> | 29,499,122 | 2 | 5 | null | 2015-04-07 18:49:29.9 UTC | 8 | 2015-04-07 18:59:49.453 UTC | 2015-04-07 18:59:49.453 UTC | null | 2,069,064 | null | 921,739 | null | 1 | 20 | c++|c++11|smart-pointers | 5,327 | <p>The most important thing to understand about smart pointers is that the "pointer" aspect is not the fundamental part of their semantics. Smart pointers exist to represent <strong>ownership</strong>. Ownership is defined as the responsibility for cleanup.</p>
<p>A unique pointer says: "I am the sole owner of the pointee. I will destroy it when I go out of scope."</p>
<p>A shared pointer says: "I am one of a group of friends who share the responsibility for the pointee. The last of us to go out of scope will destroy it."</p>
<p>(In a modern C++ program,) A raw pointer or reference says: "I do not own the pointee, I merely observe it. Someone else is responsible for destroying it."</p>
<p>In your case, using a <code>unique_ptr</code> for the member type means that <code>MyClass</code> owns the <code>MyResource</code> object. If the getter is supposed to transfer ownership (that is, if the <code>MyClass</code> is giving up the resource to whoever called the getter), returning a <code>unique_ptr</code> is appropriate (and you'll have to <code>return std::move(resource);</code> to make the ownership transfer explicit).</p>
<p>If the getter is <em>not</em> supposed to give up the ownership (which I consider the likely scenario), just return a plain old pointer (if returning a null pointer is an option) or a plain old reference (if returning null is not an option).</p> |
41,588,306 | Laravel : To rename an uploaded file automatically | <p>I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, <strong>in the database and in the folder after upload</strong>, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded.
I tried:</p>
<pre><code>if (Input::hasFile('file')){
echo "Uploaded</br>";
$file = Input::file('file');
$file ->move('uploads');
$fileName = Input::get('rename_to');
}
</code></pre>
<p>But, the name gets changed to something like:</p>
<blockquote>
<p>php5DEB.php</p>
<p>phpCFEC.php</p>
</blockquote>
<p><strong>What can I do to maintain the file in the same type and format and just change its name?</strong></p>
<p><strong>I also want to know how can I show the recently uploaded file on the page and make other users download it??</strong></p> | 42,079,251 | 7 | 3 | null | 2017-01-11 10:26:02.053 UTC | 1 | 2019-08-24 01:55:07.567 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 6,869,112 | null | 1 | 9 | laravel | 50,383 | <p>For unique file Name saving</p>
<p>In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):</p>
<pre><code>public function saveFile(Request $request) {
$file = $request->file('your_input_name')->store('your_path','your_disk');
}
</code></pre>
<p>In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:</p>
<pre><code>public function saveFile(Request $request) {
$md5Name = md5_file($request->file('your_input_name')->getRealPath());
$guessExtension = $request->file('your_input_name')->guessExtension();
$file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension ,'your_disk');
}
</code></pre> |
12,309,800 | Tomcat and proxy settings | <p>There is a servlet running on tomcat7 and it makes a webservice call to a third party website.
The call works fine from the windows machine but when run from tomcat it fails.
Wont Tomcat automatically use the Windows' proxy settings?
I added </p>
<pre><code>set JAVA_OPTS=%JAVA_OPTS% "-Dhttp.proxySet=true"
set JAVA_OPTS=%JAVA_OPTS% "-Dhttp.proxyHost=IP"
set JAVA_OPTS=%JAVA_OPTS% "-Dhttp.proxyPort=8080"
</code></pre>
<p>to CATALINA.BAT
and</p>
<pre><code>http.proxyHost=IP
http.proxyPort=8080
</code></pre>
<p>to catalina.properties
But still there is no change.
How do we set Tomcat to use the proxy settings of windows and is there a way to check if tomcat is picking up the proxy settings specified?</p> | 12,317,932 | 6 | 3 | null | 2012-09-06 23:24:58.963 UTC | 3 | 2019-03-25 04:28:01.943 UTC | null | null | null | null | 975,882 | null | 1 | 11 | jakarta-ee|tomcat|proxy|tomcat7 | 73,580 | <p>No, Tomcat won't automatically use the system proxy settings.</p>
<p>I suggest you look into the facilities provided by <code>java.net.Proxy</code>. This allows you to dynamically specifiy a proxy at runtime. The system properties work but they are only read once, and if Tomcat has already used an <code>HttpURLConnection</code> for its own purposes prior to you setting them that's the end of that: the setting has no effect.</p> |
12,232,187 | Concise pattern match on single case discriminated union in F# | <p>Say I have the following single case discriminated union:</p>
<pre class="lang-ml prettyprint-override"><code>type OrderId = OrderId of string
</code></pre>
<p>At some point I need the actual string. The way I've found for extracting it is:</p>
<pre class="lang-ml prettyprint-override"><code>let id = match orderId with OrderId x -> x
</code></pre>
<p>Is there a more concise way of doing this?</p>
<p>I understand that my use is a special case and the match makes sense in order to make sure you've covered the possibilities, just wondering if there's a way of doing something like:</p>
<pre class="lang-ml prettyprint-override"><code>let OrderId id = orderId
</code></pre> | 12,232,219 | 2 | 0 | null | 2012-09-01 23:14:31.273 UTC | 7 | 2012-12-19 19:34:10.847 UTC | 2012-09-03 21:02:31.427 UTC | null | 634,025 | null | 300,106 | null | 1 | 34 | f#|pattern-matching|discriminated-union | 2,278 | <p>You're almost there. Parentheses are required in order that the compiler interprets a let-bound as pattern matching:</p>
<pre><code>let (OrderId id) = orderId
</code></pre>
<p>If <code>orderId</code> is a parameter of a function, you can also use pattern matching directly there:</p>
<pre><code>let extractId (OrderId id) = id
</code></pre> |
12,451,431 | Loading and parsing a JSON file with multiple JSON objects | <p>I am trying to load and parse a JSON file in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a>. But I'm stuck trying to load the file:</p>
<pre><code>import json
json_data = open('file')
data = json.load(json_data)
</code></pre>
<p>Yields:</p>
<pre class="lang-none prettyprint-override"><code>ValueError: Extra data: line 2 column 1 - line 225116 column 1 (char 232 - 160128774)
</code></pre>
<p>I looked at <em><a href="http://docs.python.org/library/json.html" rel="noreferrer">18.2. <code>json</code> — JSON encoder and decoder</a></em> in the Python documentation, but it's pretty discouraging to read through this horrible-looking documentation.</p>
<p>First few lines (anonymized with randomized entries):</p>
<pre class="lang-json prettyprint-override"><code>{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
</code></pre> | 12,451,465 | 4 | 0 | null | 2012-09-16 23:00:56.853 UTC | 58 | 2022-03-04 15:35:37.653 UTC | 2019-10-27 23:55:53.367 UTC | null | 355,230 | null | 1,247,224 | null | 1 | 135 | python|json|file|jsonlines | 277,976 | <p>You have a <a href="http://jsonlines.org/" rel="noreferrer">JSON Lines format text file</a>. You need to parse your file line by line:</p>
<pre><code>import json
data = []
with open('file') as f:
for line in f:
data.append(json.loads(line))
</code></pre>
<p>Each <em>line</em> contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.</p>
<p>Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and <em>then</em> process everything if your file is really big.</p>
<p>If you have a file containing individual JSON objects with delimiters in-between, use <a href="https://stackoverflow.com/questions/21708192/how-do-i-use-the-json-module-to-read-in-one-json-object-at-a-time/21709058#21709058">How do I use the 'json' module to read in one JSON object at a time?</a> to parse out individual objects using a buffered method.</p> |
44,117,788 | Performance between String.format and StringBuilder | <p>To concatenate <code>String</code> we often use <code>StringBuilder</code> instead of <code>String</code> + <code>String</code>, but also we can do the same with <code>String.format</code> which returns the formatted string by given locale, format and arguments.</p>
<p>Examples:</p>
<p><strong>Concatenate the string with StringBuilder</strong></p>
<pre><code>String concatenateStringWithStringBuilder(String name, String lName, String nick) {
final StringBuilder sb = new StringBuilder("Contact {");
sb.append(", name='").append(name)
.append(", lastName='").append(lName)
.append(", nickName='").append(nick)
.append('}');
return sb.toString();
}
</code></pre>
<p><strong>Concatenate the string with StringFormat:</strong></p>
<pre><code>String concatenateStringWithStringFormat(String name, String lName, String nick) {
return String.format("Contact {name=%s, lastName=%s, nickName=%s}", name, lName, nick);
}
</code></pre>
<p>In performance, is <code>String.Format</code> as efficient as <code>StringBuilder</code>? Which one is better to concatenate strings and why?</p>
<p><strong>UPDATE</strong></p>
<p>I checked the similar <a href="https://stackoverflow.com/questions/513600/should-i-use-javas-string-format-if-performance-is-important">question</a>, but doesn´t answer my question. So far I have used <code>StringBuilder</code> to concatenate strings, should I follow it using? Or should I use <code>String.format</code>? the question is which one is better and why?</p> | 44,124,045 | 3 | 5 | null | 2017-05-22 16:24:12.117 UTC | 6 | 2017-08-02 20:28:34.797 UTC | 2017-08-02 09:42:57.133 UTC | null | 490,787 | null | 4,296,607 | null | 1 | 40 | java|stringbuilder|string.format | 49,636 | <p>After doing a little test with <code>StringBuilder</code> vs <code>String.format</code> I understood how much time it takes each of them to solve the concatenation. Here the snippet code and the results</p>
<p><strong>Code:</strong></p>
<pre><code>String name = "stackover";
String lName = " flow";
String nick = " stackoverflow";
String email = "[email protected]";
int phone = 123123123;
//for (int i = 0; i < 10; i++) {
long initialTime1 = System.currentTimeMillis();
String response = String.format(" - Contact {name=%s, lastName=%s, nickName=%s, email=%s, phone=%d}",
name, lName, nick, email, phone);
long finalTime1 = System.currentTimeMillis();
long totalTime1 = finalTime1 - initialTime1;
System.out.println(totalTime1 + response);
long initialTime2 = System.currentTimeMillis();
final StringBuilder sb = new StringBuilder(" - Contact {");
sb.append("name=").append(name)
.append(", lastName=").append(lName)
.append(", nickName=").append(nick)
.append(", email=").append(email)
.append(", phone=").append(phone)
.append('}');
String response2 = sb.toString();
long finalTime2 = System.currentTimeMillis();
long totalTime2 = finalTime2 - initialTime2;
System.out.println(totalTime2 + response2);
//}
</code></pre>
<p>After of run the code several times, I saw that <code>String.format</code> takes more time:</p>
<pre><code>String.format: 46: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
String.format: 38: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
String.format: 51: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
</code></pre>
<p>But if I run the same code inside a loop, the result change.</p>
<pre><code>String.format: 43: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
String.format: 1: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
String.format: 1: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
StringBuilder: 0: Contact {name=stackover, lastName= flow, nickName= stackoverflow, [email protected], phone=123123123}
</code></pre>
<p>The first time <code>String.format</code> runs it takes more time, after of that the time is shorter even though it does not become constant as a result of <code>StringBuilder</code></p>
<p>As @G.Fiedler said: "<code>String.format</code> has to parse the format string..."</p>
<p>With these results it can be said that <code>StringBuilder</code> is more efficient than<code>String.format</code></p> |
24,057,756 | Import Framework in Swift Project, Xcode | <p>I'm trying to import <code>myFramework</code> into a project. I've added <code>myFramework</code> in Build Phases->Link Binary With Libraries.</p>
<p>Objective-c works:</p>
<pre><code>#import <UIKit/UIKit.h>
#import <myFramework/myFramework.h>
</code></pre>
<p>But with in Swift, I get a <code>No such module myFramework</code> error:</p>
<pre><code>import UIKit
import myFramework
</code></pre>
<p>According to the <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-ID134" rel="noreferrer">Swift documentation</a>:</p>
<blockquote>
<p><strong>Importing External Frameworks</strong></p>
<p>You can import external frameworks that have a pure Objective-C
codebase, a pure Swift codebase, or a mixed-language codebase. The
process for importing an external framework is the same whether the
framework is written in a single language or contains files from both
languages. When you import an external framework, make sure the
Defines Module build setting for the framework you’re importing is set
to Yes.</p>
<p>You can import a framework into any Swift file within a different
target using the following syntax:</p>
<p><strong>SWIFT</strong></p>
<pre><code>import FrameworkName
</code></pre>
<p>You can import a framework into any Objective-C .m file within a different target using the following
syntax:</p>
<p><strong>OBJECTIVE-C</strong></p>
<pre><code>@import FrameworkName;
</code></pre>
</blockquote>
<p>I created <code>myFramework</code> using Xcode 5. Xcode 5 doesn't have a "Defines Module" build setting.</p>
<p>Where is the problem?</p> | 24,070,871 | 9 | 4 | null | 2014-06-05 10:28:27.393 UTC | 9 | 2021-10-09 18:15:36.253 UTC | 2016-02-15 12:05:28.163 UTC | null | 2,715,054 | null | 2,715,054 | null | 1 | 54 | ios|xcode|swift|frameworks | 103,934 | <p>If I get you correctly you don't have a separate build target for your framework (you already built it with Xcode 5) and included the framework into your project's build target.</p>
<p>The part of the documentation you're referring to is about frameworks within <em><strong>different</strong></em> targets.
Since your framework is in the project's target this part of the documentation doesn't apply here.</p>
<p>In your case you can't do an import of the framework in your Swift file. That's why you get the error message <strong>"No such module myFramework"</strong>.
myFramework is no module -- it is part of your project's module (which is by default determined by your product name). As such the classes in your framework should be accessible.</p>
<p>However your framework is written in Objective-C. So what you have to do is to import the Swift facing classes in your bridging-header as described <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html" rel="nofollow noreferrer">here</a>.</p>
<p>Please note that this has nothing to do with the Swift import of a module. The import directive in the bridging-header file just notifies the compiler to 'translate' Objective-C header files to Swift syntax and makes the public header visible to Swift.</p>
<p><strong>So what should you do now?</strong></p>
<ul>
<li><p>First import the header files you're interested in in the bridging-header. You only need to import the headers you will interact with in Swift.</p>
</li>
<li><p>Try to compile your project in this stage. If Xcode can't find the header files of the framework your problem is probably not related to Swift or Xcode 6 but a problem with including frameworks in general.</p>
</li>
<li><p>After that try to instantiate a class you imported in the bridging-header, maybe in your AppDelegate.swift. Xcode auto-completion should offer you the type names.</p>
</li>
</ul>
<p>Hope this helps.</p> |
3,652,591 | Full height and full width CSS layout | <p>I am looking for a way to create a CSS-only (no JavaScript) layout with 5 regions that looks like this:</p>
<pre><code> ┌────────────────────┐
│ H │
├────┬────────┬──────┤
│ │ │ │
│ │ │ │
│ │ │ │
│ A │ B │ C │
│ │ │ │
│ │ │ │
│ │ │ │
├────┴────────┴──────┤
│ F │
└────────────────────┘
</code></pre>
<p><em>(The above diagram will display correctly only if your font has the Unicode box-line-drawing characters.)</em></p>
<p>The layout must fill the available space in the web browser completely (both height and width).
A, B, C must have the same height; and H and F must have the same width. I.e., there must be no gaps between the regions, except for a fixed margin.
The elements inside the region should know their parents size; that means, if I place </p>
<pre><code> <textarea style="width:100%;height:100%">Just a test</textarea>
</code></pre>
<p>inside a region, it will extend to the full width and height of the region.
There shall be no scroll bar at the right side of the browser window (because the heights of H, C, and F exactly add up to the browser client-area's height).</p>
<p>This is super-easy to do if you are using a <code><table></code> to do the layout. But I keep reading that using tables for formatting is a bad thing and CSS is the way to go.</p>
<p>I am aware that there are W3C working groups that work on extending the CSS standard by features that would make the above layout very easy to implement. These standard extensions, however, are not currently implemented by most browsers; and I need a solution that works with current browsers.</p>
<p>I have been looking around the many web pages that contain sample CSS layouts, but none of them can do what I described above. Most of these layouts either are not full-height, or the columns have different heights, or they require JavaScript.</p>
<p>Therefore, my question is: is it possible to create the above layout, using only CSS (<strong>no JavaScript, no faux columns, no <code><table></code></strong>)? Of course, the solution should work with current web browsers. </p>
<p><strong>EDIT:</strong> Based on the solution provided by Gilsham, I managed to write a sample page that generates the desired CSS-only layout (tested with Firefox 3.5.5 and IE8):</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<style type="text/css">
html,body{
height:100%;
margin:0;
padding:0;
border:0;
}
div{
margin:0;
border:0;
}
textarea {
margin:0;
border:0;
padding:0;
height:100%;
width:100%;
}
.content{
display:table;
width:100%;
border-collapse:separate;
height:80%;
}
.Col{
display:table-cell;
width:30%;
height:100%;
}
#header,#footer{
height:10%;
position:relative;
z-index:1;
}
</style>
</head>
<body>
<div id="header"><textarea style="background-color:orange;">H Just a test</textarea></div>
<div class="content">
<div id="left" class="Col"><textarea style="background-color:lightskyblue;">A Just a test</textarea></div>
<div id="center" class="Col"><textarea style="background-color:green;">B Just a test</textarea></div>
<div id="right" class="Col"><textarea style="background-color:lime;">C Just a test</textarea></div>
</div>
<div id="footer"><textarea style="background-color:yellow;">F Just a test</textarea></div>
</body>
</html>
</code></pre>
<p>One drawback is that the divs must be specified in a particular order which is bad for search-engine optimization and for screen readers; this, however, is not important for the intended web application.</p>
<p>/ Frank</p> | 3,654,818 | 4 | 4 | null | 2010-09-06 15:26:16.69 UTC | 8 | 2010-09-07 10:10:22.59 UTC | 2010-09-07 06:55:35.337 UTC | user128300 | null | user128300 | null | null | 1 | 12 | html|css | 57,960 | <p><a href="http://jsfiddle.net/aGG3V/" rel="noreferrer">http://jsfiddle.net/aGG3V/</a></p>
<p>to set the header and footer height you have to set it in their style and also the .content padding and margin (this the negative version)</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.