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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
813,710 | Java 1.6 - determine symbolic links | <p>In a DirectoryWalker class I want to find out if a File instance is actually a symbolic link to a directory (assuming, the walker walks on UNIX systems). Given, I already know the instance is a directory, would the following be a reliable condition to determine the symbolic link?</p>
<pre><code>File file;
// ...
if (file.getAbsolutePath().equals(file.getCanonicalPath())) {
// real directory ---> do normal stuff
}
else {
// possible symbolic link ---> do link stuff
}
</code></pre> | 813,730 | 7 | 2 | null | 2009-05-01 23:31:36.817 UTC | 20 | 2020-07-17 20:56:20.647 UTC | 2016-07-28 11:30:54.577 UTC | null | 2,442,804 | null | 82,309 | null | 1 | 44 | java|java-6 | 40,766 | <p>The technique used in Apache Commons uses the canonical path to the parent directory, not the file itself. I don't think that you can guarantee that a mismatch is due to a symbolic link, but it's a good indication that the file needs special treatment.</p>
<p>This is <a href="https://github.com/apache/commons-io/blob/master/src/main/java/org/apache/commons/io/FileUtils.java" rel="nofollow noreferrer">Apache code</a> (subject to <a href="http://www.apache.org/licenses/LICENSE-2.0" rel="nofollow noreferrer">their license</a>), modified for compactness.</p>
<pre><code>public static boolean isSymlink(File file) throws IOException {
if (file == null)
throw new NullPointerException("File must not be null");
File canon;
if (file.getParent() == null) {
canon = file;
} else {
File canonDir = file.getParentFile().getCanonicalFile();
canon = new File(canonDir, file.getName());
}
return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}
</code></pre> |
329,613 | Decimal vs Double Speed | <p>I write financial applications where I constantly battle the decision to use a double vs using a decimal.</p>
<p>All of my math works on numbers with no more than 5 decimal places and are not larger than ~100,000. I have a feeling that all of these can be represented as doubles anyways without rounding error, but have never been sure.</p>
<p>I would go ahead and make the switch from decimals to doubles for the obvious speed advantage, except that at the end of the day, I still use the ToString method to transmit prices to exchanges, and need to make sure it always outputs the number I expect. (89.99 instead of 89.99000000001)</p>
<p>Questions:</p>
<ol>
<li>Is the speed advantage really as large as naive tests suggest? (~100 times)</li>
<li>Is there a way to guarantee the output from ToString to be what I want? Is this assured by the fact that my number is always representable?</li>
</ol>
<p>UPDATE: I have to process ~ 10 billion price updates before my app can run, and I have implemented with decimal right now for the obvious protective reasons, but it takes ~3 hours just to turn on, doubles would dramatically reduce my turn on time. Is there a safe way to do it with doubles?</p> | 329,618 | 7 | 2 | null | 2008-11-30 23:42:31.757 UTC | 20 | 2018-10-10 04:47:58.74 UTC | 2008-12-01 01:02:32.173 UTC | null | 10,094 | null | 10,094 | null | 1 | 54 | double|decimal|finance | 27,713 | <ol>
<li>Floating point arithmetic will almost always be significantly faster because it is supported directly by the hardware. So far almost no widely used hardware supports decimal arithmetic (although this is changing, see comments).</li>
<li>Financial applications should <strong>always</strong> use decimal numbers, the number of horror stories stemming from using floating point in financial applications is endless, you should be able to find many such examples with a Google search.</li>
<li>While decimal arithmetic may be significantly slower than floating point arithmetic, unless you are spending a significant amount of time processing decimal data the impact on your program is likely to be negligible. As always, do the appropriate profiling before you start worrying about the difference.</li>
</ol> |
1,167,771 | MethodInvoker vs Action for Control.BeginInvoke | <p>Which is more correct and why?</p>
<pre><code>Control.BeginInvoke(new Action(DoSomething), null);
private void DoSomething()
{
MessageBox.Show("What a great post");
}
</code></pre>
<p>or</p>
<pre><code>Control.BeginInvoke((MethodInvoker) delegate {
MessageBox.Show("What a great post");
});
</code></pre>
<p>I kinda feel like I am doing the same thing, so when is the right time to use <code>MethodInvoker</code> vs <code>Action</code>, or even writing a lambda expression?</p>
<p><em>EDIT:</em> I know that there isn't really much of a difference between writing a lambda vs <code>Action</code>, but <code>MethodInvoker</code> seems to be made for a specific purpose. Is it doing anything different?</p> | 1,167,832 | 7 | 1 | null | 2009-07-22 19:47:11.967 UTC | 25 | 2017-12-20 11:55:55.003 UTC | 2012-08-03 14:00:34.717 UTC | null | 825,024 | null | 52,051 | null | 1 | 65 | c#|.net|delegates|invoke | 63,624 | <p>Both are equally correct, but the documentation for <a href="http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx" rel="noreferrer"><code>Control.Invoke</code></a> states that:</p>
<blockquote>
<p>The delegate can be an instance of
EventHandler, in which case the sender
parameter will contain this control,
and the event parameter will contain
EventArgs.Empty. The delegate can also
be an instance of MethodInvoker, or
any other delegate that takes a void
parameter list. A call to an
EventHandler or MethodInvoker delegate
will be faster than a call to another
type of delegate.</p>
</blockquote>
<p>So <code>MethodInvoker</code> would be a more efficient choice.</p> |
361,468 | Can .NET source code hard-code a debugging breakpoint? | <p>I'm looking for a way in .NET (2.0, C# in particular) for source code to trigger a debugging break as if a breakpoint was set at that point, without having to remember to set a specific breakpoint there in the debugger, and without interfering with production runtime.</p>
<p>Our code needs to swallow exceptions in production so we don't disrupt a client application that links to us, but I'm trying to set it up so that such errors will pop up to be analyzed if it happens to be running in a debugger, and otherwise will be safely ignored.</p>
<p>My attempt to use <code>Debug.Assert(false)</code> has been less than ideal, and I assume that <code>Debug.Fail()</code> would behave the same way. It should theoretically have no effect in production, and it does successfully stop when debugging, but by design there is (as far as I can tell) no way to continue execution if you want to ignore that error, like you could with an actual breakpoint, and like it would do in production where we swallow the error. It also apparently breaks evaluation of variable state because the debugger actually stops down in native system code and not in ours, so it's debugging help is limited. (Maybe I'm missing some way of getting back into things to look at the variables and so on where it happened. ???)</p>
<p>I was hoping for something like <code>Debug.Break()</code>, but it doesn't seem to exist (unless maybe in a later version of .NET?), and no other <code>Debug</code> methods seem applicable, either.</p>
<p><strong>Update:</strong> While ctacke's answer is the best match for what I was looking for, I have since also discovered a trick with Debug.Assert()--when running in the debugger--Pause the debugger, go to the code for the Debug.Assert call pending (highlighted in green because it is down in the framework code) and hit Step-Out (shift-F11), then hit Ignore in the assert dialog box. This will leave the debugger paused upon the return of the assert (and able to continue execution as if it hadn't occurred, because it was ignored). There may be other ways to do much the same thing (does hitting Retry do this more directly?), but this way was intuitive.</p> | 361,483 | 7 | 0 | null | 2008-12-11 23:55:00.757 UTC | 16 | 2019-02-08 16:04:46.563 UTC | 2015-08-17 17:23:57.957 UTC | null | 1,677,912 | Rob Parker | 181,460 | null | 1 | 76 | c#|visual-studio|.net-2.0|breakpoints | 30,541 | <p>You probably are after something like this:</p>
<pre><code>if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
</code></pre>
<p>Of course that will still get compiled in a Release build. If you want it to behave more like the Debug object where the code simply doesn't exist in a Release build, then you could do something like this:</p>
<pre><code> // Conditional("Debug") means that calls to DebugBreak will only be
// compiled when Debug is defined. DebugBreak will still be compiled
// even in release mode, but the #if eliminates the code within it.
// DebuggerHidden is so that, when the break happens, the call stack
// is at the caller rather than inside of DebugBreak.
[DebuggerHidden]
[Conditional("DEBUG")]
void DebugBreak()
{
if(System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
}
</code></pre>
<p>Then add a call to it in your code.</p> |
933,554 | Elmah not working with asp.net site | <p>I've tried to use elmah with my asp.net site but whenever I try to go to <a href="http://localhost:port/elmah.axd" rel="noreferrer">http://localhost:port/elmah.axd</a> I get resource not found exception. My web.config is given below.</p>
<pre><code> <?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="elmah">
<section name="security" requirePermission="false"
type="Elmah.SecuritySectionHandler, Elmah"/>
<section name="errorLog" requirePermission="false"
type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false"
type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false"
type="Elmah.ErrorFilterSectionHandler, Elmah"/>
</sectionGroup>
</configSections>
<elmah>
<security allowRemoteAccess="0" />
<errorLog type="Elmah.SqlErrorLog, Elmah"
connectionStringName="elmah-sql" />
<errorMail
from="my@account"
to="myself"
subject="ERROR From Elmah:"
async="true"
smtpPort="587"
smtpServer="smtp.gmail.com"
userName="my@account"
password="mypassword" />
</elmah>
<connectionStrings>
<add name="elmah-sql" connectionString="data source=(sqlserver);
database=elmahdb;
integrated security=false;User ID=user;Password=password"/>
</connectionStrings>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="Elmah, Version=1.0.10617.0, Culture=neutral,
PublicKeyToken=null"/>
</assemblies>
</compilation>
<authentication mode="Windows"/>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler"
type="System.Web.Handlers.ScriptModule,
System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
PublicKeyToken=31BF3856AD364E35"/>
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx"
preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*"
path="*_AppService.axd" preCondition="integratedMode"
type="System.Web.Script.Services.ScriptHandlerFactory,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode"
verb="GET,HEAD" path="ScriptResource.axd"
type="System.Web.Handlers.ScriptResourceHandler,
System.Web.Extensions, Version=3.5.0.0,
Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="Elmah" verb="POST,GET,HEAD" path="elmah.axd"
preCondition="integratedMode"
type="Elmah.ErrorLogPageFactory, Elmah"/>
</handlers>
</system.webServer>
</configuration>
</code></pre>
<p>EDIT: Elmah = (Error Logging Modules and Handlers)<br>
<a href="http://code.google.com/p/elmah/" rel="noreferrer">http://code.google.com/p/elmah/</a></p> | 933,586 | 7 | 5 | null | 2009-06-01 04:22:48.433 UTC | 44 | 2017-07-21 09:56:21.823 UTC | 2009-06-01 04:35:05.593 UTC | null | 23,574 | null | 13,198 | null | 1 | 80 | asp.net|exception-handling|elmah | 36,062 | <p>Try registering the Modules and Handlers in the sections "httphandlers" and "httpmodules" in the <code><system.web></code> section: </p>
<pre><code> <httpHandlers>
......
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah"/>
.....
</httpHandlers>
<httpModules>
.......
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah"/>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah"/>
.......
</httpModules>
</code></pre> |
514,659 | Does google index pages with hidden divs? | <p>I am starting to redesign and develop a site that contains a lot of text and I am thinking of ways to organize the information on the site so that it looks cleaner. On some parts of the site I would like to implement a jquery toggle effect where some content is placed in a hidden div and that content will show or hide depending on a user's onclick event.</p>
<p>Would this technique of organizing content greatly harm the SEO of the site? At what point would google start viewing this as spam and drop the site from being indexed all together?</p>
<p>//Update - found some answers.</p>
<p>I guess to clarify, as a response to some answers below, the purpose of the hidden divs would be to toggle between showing/hiding the content for organizational purpose where any hidden text would eventually be shown to the user.</p>
<p>However, after much digging around, <a href="http://www.stonetemple.com/articles/interview-matt-cutts.shtml" rel="noreferrer">Matt Cutts</a> from google does pretty much say that as long as you are not keyword stuffing your hidden text and abusing the system by trying to trick the googlebot, you should generally be fine. He also <a href="http://www.mattcutts.com/blog/avoid-keyword-stuffing/" rel="noreferrer">gives a funny example</a> of keyword stuffing gone wrong.</p> | 514,675 | 8 | 0 | null | 2009-02-05 05:09:32.31 UTC | 11 | 2017-01-21 09:15:25.08 UTC | 2013-12-30 21:21:39.313 UTC | null | 881,229 | null | 62,754 | null | 1 | 26 | seo|google-search | 24,682 | <p>It will be indexed but can be frowned upon by Google if you are hiding/showing content for SEO reasons. In other words, what Google sees should be what the user sees when clicking the link.</p> |
297,654 | What is __stdcall? | <p>I'm learning about Win32 programming, and the <code>WinMain</code> prototype looks like:</p>
<pre><code>int WINAPI WinMain ( HINSTANCE instance, HINSTANCE prev_instance, PSTR cmd_line, int cmd_show )
</code></pre>
<p>I was confused as to what this <code>WINAPI</code> identifier was for and found:</p>
<pre><code>#define WINAPI __stdcall
</code></pre>
<p>What does this do? I'm confused by this having something at all after a return type. What is <code>__stdcall</code> for? What does it mean when there is something between the return type and function name?</p> | 297,661 | 8 | 1 | null | 2008-11-18 02:15:39.44 UTC | 68 | 2020-04-19 19:12:05.347 UTC | 2014-01-09 23:57:47.897 UTC | Jay Bazuzi | 132,401 | DrFredEdison | 30,529 | null | 1 | 169 | c|winapi|calling-convention|stdcall | 127,007 | <p><code>__stdcall</code> is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.</p>
<p>There are a number of other calling conventions, <code>__cdecl</code>, <code>__thiscall</code>, <code>__fastcall</code> and the wonderfully named <code>__declspec(naked)</code>. <code>__stdcall</code> is the standard calling convention for Win32 system calls. </p>
<p>Wikipedia covers the <a href="http://en.wikipedia.org/wiki/X86_calling_conventions" rel="noreferrer">details</a>.</p>
<p>It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.</p> |
32,044 | How can I render a tree structure (recursive) using a django template? | <p>I have a tree structure in memory that I would like to render in HTML using a Django template. </p>
<pre><code>class Node():
name = "node name"
children = []
</code></pre>
<p>There will be some object <code>root</code> that is a <code>Node</code>, and <code>children</code> is a list of <code>Node</code>s. <code>root</code> will be passed in the content of the template.</p>
<p>I have found <a href="http://blog.elsdoerfer.name/2008/01/22/recursion-in-django-templates/" rel="noreferrer">this</a> one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.</p>
<p>Does anybody know of a better way?</p> | 32,125 | 10 | 0 | null | 2008-08-28 11:43:10.287 UTC | 19 | 2019-11-06 09:41:23.303 UTC | null | null | null | null | 3,154 | null | 1 | 73 | python|django | 36,880 | <p>I think the canonical answer is: "Don't".</p>
<p>What you should probably do instead is unravel the thing in your <em>view</em> code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert <code><li></code> and <code></li></code> from that list, creating the recursive structure with "understanding" it.)</p>
<p>I'm also pretty sure recursively including template files is really a <em>wrong</em> way to do it...</p> |
809,775 | What does the servlet <load-on-startup> value signify | <p>I am getting a bit confused here. In our application we are having a few servlets defined. Here is the excerpt from the <code>web.xml</code> for one of the servlets:</p>
<pre class="lang-xml prettyprint-override"><code><servlet>
<servlet-name>AxisServlet</servlet-name>
<display-name>Apache-Axis Servlet</display-name>
<servlet-class>com.foo.framework.axis2.http.FrameworkServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
</code></pre>
<p>As per my understanding the value for the <code><load-on-startup></code> has to be a positive integer in order for it to get loaded automatically. I looked up on google but the responses I came across only added to my confusion.</p> | 810,190 | 11 | 0 | null | 2009-05-01 00:45:02.39 UTC | 70 | 2018-09-13 06:22:55.467 UTC | 2015-08-28 11:57:20.237 UTC | null | 157,882 | null | 98,044 | null | 1 | 181 | jakarta-ee|servlets|web.xml | 280,990 | <p><a href="http://www.caucho.com/resin-3.0/config/webapp.xtp" rel="noreferrer">Resin 3.0</a> documents this behavior:</p>
<blockquote>
<p>load-on-startup can specify an (optional) integer value. If the value is 0 or greater,
it indicates an order for servlets to be loaded, servlets with higher numbers get
loaded after servlets with lower numbers.</p>
</blockquote>
<p>The <a href="https://jcp.org/aboutJava/communityprocess/final/jsr340/" rel="noreferrer">JSP 3.1 spec</a> (JSR 340) says this on page 14-160:</p>
<blockquote>
<p>The element <code>load-on-startup</code> indicates that this servlet should be loaded (instantiated
and have its
init() called) on the startup of the Web application. The element content of this
element must be an integer indicating the order in which the servlet should be
loaded. If the value is a negative integer, or the element is not present, the
container is free to load the servlet whenever it chooses. If the value is a positive
integer or 0, the container must load and initialize the servlet as the application is
deployed. The container must guarantee that servlets marked with lower integers
are loaded before servlets marked with higher integers. The container may choose
the order of loading of servlets with the same <code>load-on-startup</code> value. </p>
</blockquote>
<p>You probably want to check not only the JSR, but also the documentation for your web container. There may be differences</p> |
168,593 | Bad habits of your Scrum Master | <p>Scrum is quite popular dev.process these days and often Project Manager suddenly gets new title (Scrum Master). However it should be not just a new title, but new habits and new paradigm. What are the bad habits of your Scrum master?</p> | 168,692 | 12 | 0 | null | 2008-10-03 19:49:47.27 UTC | 12 | 2013-02-25 03:38:32.127 UTC | 2008-10-03 20:17:55.763 UTC | Michael Dubakov | 24,938 | Michael Dubakov | 24,938 | null | 1 | 18 | agile|scrum | 8,720 | <p>The big bad habit our Scrum Master had at first was thinking we would take care of our own impediments. That's one of the things the Scrum Master is supposed to do but she left it to us until it got unmanageable.</p>
<p>The other thing we've dealt with is the Scrum Master thinking they were in charge of riding the developers' backs until tasks were taken care of. This creates a bad atmosphere on the team since they're supposed to be self-managing.</p>
<p>To me and our team, the Scrum Master's job is to be a shield and assistant for the team, blocking impediments and doing what they can to help expedite things. Ken Schwaber's <strong>Agile Software Development with Scrum</strong> is an excellent intro to Scrum, it's what our team used and we've been pretty successful with it. There's also <strong>Agile Project Management with Scrum</strong>, which is more for the Scrum Master and Product Owner roles specifically.</p> |
940,382 | What is the difference between . (dot) and $ (dollar sign)? | <p>What is the difference between the dot <code>(.)</code> and the dollar sign <code>($)</code>?</p>
<p>As I understand it, they are both syntactic sugar for not needing to use parentheses.</p> | 1,290,727 | 13 | 0 | null | 2009-06-02 16:06:36.64 UTC | 267 | 2021-03-15 11:57:06.883 UTC | 2019-07-27 13:04:07.927 UTC | null | 775,954 | null | 50,899 | null | 1 | 781 | haskell|syntax|function-composition | 196,791 | <p>The <code>$</code> operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.</p>
<p>For example, let's say you've got a line that reads:</p>
<pre><code>putStrLn (show (1 + 1))
</code></pre>
<p>If you want to get rid of those parentheses, any of the following lines would also do the same thing:</p>
<pre><code>putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1
</code></pre>
<p>The primary purpose of the <code>.</code> operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.</p>
<p>Going back to the same example:</p>
<pre><code>putStrLn (show (1 + 1))
</code></pre>
<ol>
<li><code>(1 + 1)</code> doesn't have an input, and therefore cannot be used with the <code>.</code> operator.</li>
<li><code>show</code> can take an <code>Int</code> and return a <code>String</code>.</li>
<li><code>putStrLn</code> can take a <code>String</code> and return an <code>IO ()</code>.</li>
</ol>
<p>You can chain <code>show</code> to <code>putStrLn</code> like this:</p>
<pre><code>(putStrLn . show) (1 + 1)
</code></pre>
<p>If that's too many parentheses for your liking, get rid of them with the <code>$</code> operator:</p>
<pre><code>putStrLn . show $ 1 + 1
</code></pre> |
343,899 | How to cache data in a MVC application | <p>I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.</p>
<p>In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.</p>
<p>Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.</p>
<p>I have seen this done in traditional ASP.NET apps , typically for very static data.</p> | 343,935 | 14 | 1 | null | 2008-12-05 13:53:07.34 UTC | 198 | 2020-07-23 13:20:39.58 UTC | null | null | null | Coolcoder | 42,434 | null | 1 | 257 | asp.net-mvc|database|caching | 227,569 | <p>Reference the <code>System.Web</code> dll in your model and use <code>System.Web.Caching.Cache</code></p>
<pre><code> public string[] GetNames()
{
string[] names = Cache["names"] as string[];
if(names == null) //not in cache
{
names = DB.GetNames();
Cache["names"] = names;
}
return names;
}
</code></pre>
<p>A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.</p> |
50,618 | What is the point of the finally block? | <p>Syntax aside, what is the difference between</p>
<pre><code>try {
}
catch() {
}
finally {
x = 3;
}
</code></pre>
<p>and </p>
<pre><code>try {
}
catch() {
}
x = 3;
</code></pre>
<p>edit: in .NET 2.0?</p>
<hr>
<p>so</p>
<pre><code>try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
</code></pre>
<p>is behaviourally equivalent?</p> | 50,627 | 16 | 3 | null | 2008-09-08 20:41:49.307 UTC | 4 | 2022-01-15 13:22:05.293 UTC | 2011-11-20 13:43:08.717 UTC | Chris Bunch | 1,288 | Keshi | 5,278 | null | 1 | 35 | .net|design-patterns|exception|try-catch-finally | 5,627 | <p>Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.</p>
<p>In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.</p>
<p>In the .NET platform, in some cases the execution of the finally block won't occur:
Security Exceptions, Thread suspensions, Computer shut down :), etc.</p> |
1,068,246 | Python unittest: how to run only part of a test file? | <p>I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.</p>
<p>Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "<code>./tests.py --offline</code>" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.</p>
<p>For now, I just use <code>unittest.main()</code> to start the tests.</p> | 1,068,366 | 16 | 0 | null | 2009-07-01 09:40:32.927 UTC | 24 | 2021-07-22 19:46:14.103 UTC | 2021-02-05 18:37:49.59 UTC | null | 63,550 | null | 129,333 | null | 1 | 86 | python|unit-testing|python-unittest | 61,701 | <p>The default <code>unittest.main()</code> uses the default test loader to make a TestSuite out of the module in which main is running.</p>
<p>You don't have to use this default behavior.</p>
<p>You can, for example, make three <a href="http://docs.python.org/library/unittest.html#unittest.TestSuite" rel="nofollow noreferrer">unittest.TestSuite</a> instances.</p>
<ol>
<li><p>The "fast" subset.</p>
<pre><code>fast = TestSuite()
fast.addTests(TestFastThis)
fast.addTests(TestFastThat)
</code></pre>
</li>
<li><p>The "slow" subset.</p>
<pre><code>slow = TestSuite()
slow.addTests(TestSlowAnother)
slow.addTests(TestSlowSomeMore)
</code></pre>
</li>
<li><p>The "whole" set.</p>
<pre><code>alltests = unittest.TestSuite([fast, slow])
</code></pre>
</li>
</ol>
<p>Note that I've adjusted the TestCase names to indicate Fast vs. Slow. You can subclass
unittest.TestLoader to parse the names of classes and create multiple loaders.</p>
<p>Then your main program can parse command-line arguments with <a href="http://docs.python.org/library/optparse.html" rel="nofollow noreferrer">optparse</a> or <a href="https://docs.python.org/dev/library/argparse.html" rel="nofollow noreferrer">argparse</a> (available since 2.7 or 3.2) to pick which suite you want to run, fast, slow or all.</p>
<p>Or, you can trust that <code>sys.argv[1]</code> is one of three values and use something as simple as this</p>
<pre><code>if __name__ == "__main__":
suite = eval(sys.argv[1]) # Be careful with this line!
unittest.TextTestRunner().run(suite)
</code></pre> |
144,735 | Best way to get started with programming other things than your computer? | <p>What is the best way to get started with programming things outside of your computer? </p>
<p>I don't mean mainstream things like cell phones with APIs.</p>
<p>Please assume working knowledge of C/C++</p> | 144,748 | 19 | 0 | null | 2008-09-27 23:30:06.26 UTC | 23 | 2011-10-17 12:22:19.17 UTC | 2008-10-19 14:24:29.39 UTC | freespace | 8,297 | Brian R. Bondy | 3,153 | null | 1 | 25 | c|embedded|microcontroller|device | 3,051 | <p>Brian, you might find the <a href="http://www.arduino.cc/" rel="nofollow noreferrer">Arduino</a> interesting. It is inexpensive and pretty popular. I started playing around with micro controller boards and such a few years back and that lead to an interest in robots. Kind of interesting, at least to me.</p>
<p>If one is interested in a .NET-flavored development environment, there is an analog to the arduino call <a href="http://netduino.com/" rel="nofollow noreferrer">netduino</a> that is worth a look.</p> |
1,002,164 | Write applications in C or C++ for Android? | <p>I'm trying to develop/port a game to Android, but it's in C, and Android supports Java, but I'm sure there must be a way to get a C app on there, anyone knows of a way to accomplish this?</p> | 1,571,635 | 20 | 9 | null | 2009-06-16 15:14:50.017 UTC | 80 | 2019-09-14 10:17:14.27 UTC | 2019-09-14 10:17:14.27 UTC | user166390 | 220,984 | null | 15,124 | null | 1 | 290 | c++|c|android | 326,879 | <p>For anyone coming to this via Google, note that starting from SDK 1.6 Android now has an official native SDK. </p>
<p>You can download the Android NDK (Native Development Kit) from here:
<a href="https://developer.android.com/ndk/downloads/index.html" rel="noreferrer">https://developer.android.com/ndk/downloads/index.html</a></p>
<p>Also there is an blog post about the NDK:<br>
<a href="http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html" rel="noreferrer">http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html</a></p> |
1,325,673 | How to add property to a class dynamically? | <p>The goal is to create a mock class which behaves like a db resultset.</p>
<p>So for example, if a database query returns, using a dict expression, <code>{'ab':100, 'cd':200}</code>, then I would like to see: </p>
<pre><code>>>> dummy.ab
100
</code></pre>
<p>At first I thought maybe I could do it this way:</p>
<pre><code>ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
def __init__(self, ks, vs):
for i, k in enumerate(ks):
self[k] = vs[i]
setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))
def fn_readonly(self, v)
raise "It is ready only"
if __name__ == "__main__":
c = C(ks, vs)
print c.ab
</code></pre>
<p>but <code>c.ab</code> returns a property object instead.</p>
<p>Replacing the <code>setattr</code> line with <code>k = property(lambda x: vs[i])</code> is of no use at all.</p>
<p>So what is the right way to create an instance property at runtime?</p>
<p>P.S. I am aware of an alternative presented in <a href="https://stackoverflow.com/questions/371753/how-is-the-getattribute-method-used"><em>How is the <code>__getattribute__</code> method used?</em></a></p> | 1,355,444 | 25 | 5 | null | 2009-08-25 01:53:33.46 UTC | 120 | 2021-12-01 12:48:20.36 UTC | 2017-03-03 23:55:11.877 UTC | null | 964,243 | null | 58,129 | null | 1 | 285 | python|properties|runtime|monkeypatching | 339,120 | <p>I suppose I should expand this answer, now that I'm older and wiser and know what's going on. Better late than never.</p>
<p>You <em>can</em> add a property to a class dynamically. But that's the catch: you have to add it to the <em>class</em>.</p>
<pre><code>>>> class Foo(object):
... pass
...
>>> foo = Foo()
>>> foo.a = 3
>>> Foo.b = property(lambda self: self.a + 1)
>>> foo.b
4
</code></pre>
<p>A <code>property</code> is actually a simple implementation of a thing called a <a href="http://docs.python.org/2/reference/datamodel.html#implementing-descriptors" rel="noreferrer">descriptor</a>. It's an object that provides custom handling for a given attribute, <em>on a given class</em>. Kinda like a way to factor a huge <code>if</code> tree out of <code>__getattribute__</code>.</p>
<p>When I ask for <code>foo.b</code> in the example above, Python sees that the <code>b</code> defined on the class implements the <em>descriptor protocol</em>—which just means it's an object with a <code>__get__</code>, <code>__set__</code>, or <code>__delete__</code> method. The descriptor claims responsibility for handling that attribute, so Python calls <code>Foo.b.__get__(foo, Foo)</code>, and the return value is passed back to you as the value of the attribute. In the case of <code>property</code>, each of these methods just calls the <code>fget</code>, <code>fset</code>, or <code>fdel</code> you passed to the <code>property</code> constructor.</p>
<p>Descriptors are really Python's way of exposing the plumbing of its entire OO implementation. In fact, there's another type of descriptor even more common than <code>property</code>.</p>
<pre><code>>>> class Foo(object):
... def bar(self):
... pass
...
>>> Foo().bar
<bound method Foo.bar of <__main__.Foo object at 0x7f2a439d5dd0>>
>>> Foo().bar.__get__
<method-wrapper '__get__' of instancemethod object at 0x7f2a43a8a5a0>
</code></pre>
<p>The humble method is just another kind of descriptor. Its <code>__get__</code> tacks on the calling instance as the first argument; in effect, it does this:</p>
<pre><code>def __get__(self, instance, owner):
return functools.partial(self.function, instance)
</code></pre>
<p>Anyway, I suspect this is why descriptors only work on classes: they're a formalization of the stuff that powers classes in the first place. They're even the exception to the rule: you can obviously assign descriptors to a class, and classes are themselves instances of <code>type</code>! In fact, trying to read <code>Foo.bar</code> still calls <code>property.__get__</code>; it's just idiomatic for descriptors to return themselves when accessed as class attributes.</p>
<p>I think it's pretty cool that virtually all of Python's OO system can be expressed in Python. :)</p>
<p>Oh, and I wrote a <a href="http://me.veekun.com/blog/2012/05/23/python-faq-descriptors/" rel="noreferrer">wordy blog post about descriptors</a> a while back if you're interested.</p> |
405,770 | Why are compilers so stupid? | <p>I always wonder why compilers can't figure out simple things that are obvious to the human eye. They do lots of simple optimizations, but never something even a little bit complex. For example, this code takes about 6 seconds on my computer to print the value zero (using java 1.6):</p>
<pre class="lang-java prettyprint-override"><code>int x = 0;
for (int i = 0; i < 100 * 1000 * 1000 * 1000; ++i) {
x += x + x + x + x + x;
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>System.out.println(x);
</code></pre>
<p>It is totally obvious that x is never changed so no matter how often you add 0 to itself it stays zero. So the compiler could in theory replace this with System.out.println(0).</p>
<p>Or even better, this takes 23 seconds:</p>
<pre class="lang-java prettyprint-override"><code>public int slow() {
String s = "x";
for (int i = 0; i < 100000; ++i) {
s += "x";
}
return 10;
}
</code></pre>
<p>First the compiler could notice that I am actually creating a string s of 100000 "x" so it could automatically use s StringBuilder instead, or even better directly replace it with the resulting string as it is always the same. Second, It does not recognize that I do not actually use the string at all, so the whole loop could be discarded!</p>
<p>Why, after so much manpower is going into fast compilers, are they still so relatively dumb?</p>
<p><strong>EDIT</strong>: Of course these are stupid examples that should never be used anywhere. But whenever I have to rewrite a beautiful and very readable code into something unreadable so that the compiler is happy and produces fast code, I wonder why compilers or some other automated tool can't do this work for me.</p> | 414,774 | 29 | 13 | 2010-10-01 04:33:57.9 UTC | 2009-01-02 01:01:36.617 UTC | 27 | 2020-08-14 12:56:19.97 UTC | 2020-08-14 12:56:19.97 UTC | user12581835 | null | martinus | 48,181 | null | 1 | 41 | performance|language-agnostic|compiler-construction | 8,782 | <p>Oh, I don't know. Sometimes compilers are pretty smart. Consider the following C program:</p>
<pre><code>#include <stdio.h> /* printf() */
int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
int main() {
int n = 10;
printf("factorial(%d) = %d\n", n, factorial(n));
return 0;
}
</code></pre>
<p>On my version of <a href="http://en.wikipedia.org/wiki/GNU_Compiler_Collection" rel="nofollow noreferrer">GCC</a> (4.3.2 on <a href="http://en.wikipedia.org/wiki/Debian" rel="nofollow noreferrer">Debian</a> testing), when compiled with no optimizations, or <code>-O1</code>, it generates code for <code>factorial()</code> like you'd expect, using a recursive call to compute the value. But on <code>-O2</code>, it does something interesting: It compiles down to a tight loop:</p>
<pre><code> factorial:
.LFB13:
testl %edi, %edi
movl $1, %eax
je .L3
.p2align 4,,10
.p2align 3
.L4:
imull %edi, %eax
subl $1, %edi
jne .L4
.L3:
rep
ret
</code></pre>
<p>Pretty impressive. The recursive call (not even tail-recursive) has been completely eliminated, so factorial now uses O(1) stack space instead of O(N). And although I have only very superficial knowledge of x86 assembly (actually AMD64 in this case, but I don't think any of the AMD64 extensions are being used above), I doubt that you could write a better version by hand. But what really blew my mind was the code that it generated on <code>-O3</code>. The implementation of factorial stayed the same. But <code>main()</code> changed:</p>
<pre><code> main:
.LFB14:
subq $8, %rsp
.LCFI0:
movl $3628800, %edx
movl $10, %esi
movl $.LC0, %edi
xorl %eax, %eax
call printf
xorl %eax, %eax
addq $8, %rsp
ret
</code></pre>
<p>See the <code>movl $3628800, %edx</code> line? <strong>gcc is pre-computing <code>factorial(10)</code> at compile-time.</strong> It doesn't even call <code>factorial()</code>. Incredible. My hat is off to the GCC development team.</p>
<p>Of course, all the usual disclaimers apply, this is just a toy example, premature optimization is the root of all evil, etc, etc, but it illustrates that compilers are often smarter than you think. If you think you can do a better job by hand, you're almost certainly wrong.</p>
<p>(Adapted from a <a href="http://jcreigh.blogspot.com/2008/12/gcc-is-smarter-than-you.html" rel="nofollow noreferrer">posting on my blog</a>.)</p> |
6,544,564 | URL Encode a string in jQuery for an AJAX request | <p>I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a <code>+</code>, thus breaking the search. How can I either replace the space with a <code>+</code>, or just safely URL Encode the string?</p>
<pre><code>$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
</code></pre> | 6,544,603 | 6 | 1 | null | 2011-07-01 06:48:44.98 UTC | 35 | 2021-09-29 14:35:10.9 UTC | 2016-03-27 07:58:25.74 UTC | null | 3,284,463 | null | 387,064 | null | 1 | 244 | javascript|jquery|ajax|http | 472,662 | <p>Try <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="noreferrer">encodeURIComponent</a>.</p>
<blockquote>
<p>Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).</p>
</blockquote>
<p>Example:</p>
<pre><code>var encoded = encodeURIComponent(str);
</code></pre> |
6,478,875 | Regular expression matching E.164 formatted phone numbers | <p>I need to add a regular expression that matches all possible valid E.164 formatted phone numbers. </p>
<p>This regex works fine for for North American phone numbers, but I need something that will work for international numbers as well:</p>
<blockquote>
<p>^(+1|1)?([2-9]\d\d[2-9]\d{6})$</p>
<p>Example: +13172222222 matches
13172222222 still matches because +1 or 1 are optional
3172222222 still matches because +1 or 1 are optional
3171222222 does not match and is not a valid NANPA number.</p>
</blockquote>
<p>Source: <a href="http://wiki.freeswitch.org/wiki/Regular_Expression" rel="noreferrer">Freeswitch.org</a></p>
<p>I also came across <a href="https://stackoverflow.com/questions/2113908/what-regular-expression-will-match-valid-international-phone-numbers">this related question</a>, but I think that it is way too crazy for my needs. In my case, I am simply validating an entry for a blacklist, which I'm comparing to incoming Twilio data; so, I care much less about weather a country code is valid. I really only need to test if a number matches the general <a href="http://en.wikipedia.org/wiki/E.164" rel="noreferrer">E.164</a> form, rather than assuming it's a NANPA.</p>
<p>To be better understand what I need to match, here is an example from the <a href="https://www.twilio.com/docs/api/rest/response#data-formats" rel="noreferrer">Twilio Documentation</a>:</p>
<blockquote>
<p>All phone numbers in requests from
Twilio are in E.164 format if
possible. For example, (415) 555-4345
would come through as '+14155554345'.
However, there are occasionally cases
where Twilio cannot normalize an
incoming caller ID to E.164. In these
situations Twilio will report the raw
caller ID string.</p>
</blockquote>
<p>I want to match something like +14155554345, but not (415) 555-4345, 415555434, 555-4345 or 5554345. The regex should not restrict itself to only matching the US country code though. Basically, it should match the +xxxxxxxxxxx format. I also think the number could be longer, as there are multi-digit country codes, such as in the UK. T-Mobile's UK number is +447953966150 I'll update this if I can come up with a better example.</p> | 23,299,989 | 8 | 5 | null | 2011-06-25 16:01:29.753 UTC | 16 | 2021-06-29 16:55:44.99 UTC | 2017-05-23 12:26:27.26 UTC | null | -1 | null | 501,333 | null | 1 | 77 | regex | 73,771 | <p>The accepted answer is good, except an E.164 number can have up to 15 digits. The specification also doesn't indicate a minimum, so I wouldn't necessarily count on 10.</p>
<p>It should be <code>^\+?[1-9]\d{1,14}$</code></p>
<p>See <a href="http://en.wikipedia.org/wiki/E.164" rel="noreferrer">http://en.wikipedia.org/wiki/E.164</a></p> |
6,937,519 | How to fill form with JSON? | <p>I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using <code>$(json).each()</code> ?</p>
<p>JSON:</p>
<pre><code>{
"id" : 12,
"name": "Jack",
"description": "Description"
}
</code></pre>
<p>Form to fill</p>
<pre><code><form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>
</code></pre> | 6,937,570 | 11 | 0 | null | 2011-08-04 07:13:55.97 UTC | 9 | 2020-05-28 20:30:36.103 UTC | null | null | null | null | 404,395 | null | 1 | 9 | javascript|jquery|json | 27,906 | <p>You might want to take a look at the <a href="http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html" rel="nofollow">jQuery Populate plugin</a>.</p>
<p>Although if this is the only use case you have, you might as well do it manually.</p> |
6,481,627 | Java Security: Illegal key size or default parameters? | <p>I had asked a question about this earlier, but it didn't get answered right and led nowhere.</p>
<p>So I've clarified few details on the problem and I would really like to hear your ideas on how could I fix this or what should I try. </p>
<p>I have <strong>Java 1.6.0.12</strong> installed on my Linux server and the code below runs just perfectly.</p>
<pre><code>String key = "av45k1pfb024xa3bl359vsb4esortvks74sksr5oy4s5serondry84jsrryuhsr5ys49y5seri5shrdliheuirdygliurguiy5ru";
try {
Cipher c = Cipher.getInstance("ARCFOUR");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "ARCFOUR");
c.init(Cipher.DECRYPT_MODE, secretKeySpec);
return new String(c.doFinal(Hex.decodeHex(data.toCharArray())), "UTF-8");
} catch (InvalidKeyException e) {
throw new CryptoException(e);
}
</code></pre>
<p>Today I installed <strong>Java 1.6.0.26</strong> on my server user and when I try to run my application, I get the following exception. My guess would be that it has something to do with the Java installation configuration because it works in the first one, but doesn't work in the later version.</p>
<pre><code>Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.a(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
at javax.crypto.Cipher.init(DashoA13*..) ~[na:1.6]
at my.package.Something.decode(RC4Decoder.java:25) ~[my.package.jar:na]
... 5 common frames omitted
</code></pre>
<p><em>Line 25</em> is:
<code>c.init(Cipher.DECRYPT_MODE, secretKeySpec);</code></p>
<p><strong>Notes:</strong><br>
* java.security on server's <strong>1.6.0.12</strong> java directory matches almost completely with the <strong>1.6.0.26</strong> java.security file. There are no additional providers in the first one.<br>
* The previous question is <a href="https://stackoverflow.com/questions/5929705/is-it-rc4-or-arcfour-invalidkeyexception-when-using-secretkeyspec">here</a>.</p> | 6,481,658 | 19 | 5 | null | 2011-06-26 01:40:15.943 UTC | 161 | 2021-10-26 17:26:14.68 UTC | 2017-06-08 16:50:55.487 UTC | null | 266,531 | null | 374,476 | null | 1 | 433 | java | 473,803 | <p>Most likely you don't have the unlimited strength file installed now.</p>
<p>You may need to download this file:</p>
<p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html" rel="noreferrer">Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
</a></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html" rel="noreferrer">Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 7 Download</a></p>
<p><a href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html" rel="noreferrer">Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8 Download</a> (only required for versions before Java 8 u162)</p>
<p>Extract the jar files from the zip and save them in <code>${java.home}/jre/lib/security/</code>.</p> |
38,079,853 | How can I implement incremental training for xgboost? | <p>The problem is that my train data could not be placed into RAM due to train data size. So I need a method which first builds one tree on whole train data set, calculate residuals build another tree and so on (like gradient boosted tree do). Obviously if I call <code>model = xgb.train(param, batch_dtrain, 2)</code> in some loop - it will not help, because in such case it just rebuilds whole model for each batch.</p> | 38,260,557 | 10 | 1 | null | 2016-06-28 15:05:08.827 UTC | 28 | 2022-04-05 20:29:44.61 UTC | 2016-07-08 09:52:24.033 UTC | null | 6,021,402 | null | 5,324,819 | null | 1 | 54 | python|machine-learning|xgboost | 51,964 | <p>Try saving your model after you train on the first batch. Then, on successive runs, provide the xgb.train method with the filepath of the saved model.</p>
<p>Here's a small experiment that I ran to convince myself that it works:</p>
<p>First, split the boston dataset into training and testing sets.
Then split the training set into halves.
Fit a model with the first half and get a score that will serve as a benchmark.
Then fit two models with the second half; one model will have the additional parameter <em>xgb_model</em>. If passing in the extra parameter didn't make a difference, then we would expect their scores to be similar..
But, fortunately, the new model seems to perform much better than the first.</p>
<pre><code>import xgboost as xgb
from sklearn.cross_validation import train_test_split as ttsplit
from sklearn.datasets import load_boston
from sklearn.metrics import mean_squared_error as mse
X = load_boston()['data']
y = load_boston()['target']
# split data into training and testing sets
# then split training set in half
X_train, X_test, y_train, y_test = ttsplit(X, y, test_size=0.1, random_state=0)
X_train_1, X_train_2, y_train_1, y_train_2 = ttsplit(X_train,
y_train,
test_size=0.5,
random_state=0)
xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
xg_test = xgb.DMatrix(X_test, label=y_test)
params = {'objective': 'reg:linear', 'verbose': False}
model_1 = xgb.train(params, xg_train_1, 30)
model_1.save_model('model_1.model')
# ================= train two versions of the model =====================#
model_2_v1 = xgb.train(params, xg_train_2, 30)
model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model')
print(mse(model_1.predict(xg_test), y_test)) # benchmark
print(mse(model_2_v1.predict(xg_test), y_test)) # "before"
print(mse(model_2_v2.predict(xg_test), y_test)) # "after"
# 23.0475232194
# 39.6776876084
# 27.2053239482
</code></pre>
<p>reference: <a href="https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/training.py" rel="noreferrer">https://github.com/dmlc/xgboost/blob/master/python-package/xgboost/training.py</a></p> |
15,683,314 | WPF add datagrid image column possible? | <p>Using C#.Net 4.5, Visual Studio 2012 Ulti, WPF.</p>
<p>I've got some old win-forms code that i wanted to do in this new WPF app.</p>
<p>code is the following:</p>
<pre><code>DataGridViewImageCell pNew = new DataGridViewImageCell();
ParetoGrid.Columns.Add(new DataGridViewImageColumn() { CellTemplate = pNew, FillWeight = 1, HeaderText = "pNew", Name = "pNew", Width = 30 });
ParetoGrid.Columns["pNew"].DisplayIndex = 18;
</code></pre>
<p>3 lines of code to add a column that can handle images. In WPF I've seen its a bit different. Do i need to add an "image column"? or does WPF columns support images? or is there another 3 liner solution that is simply different syntax?</p>
<p>Thanks for the help guys</p> | 15,683,394 | 4 | 3 | null | 2013-03-28 13:35:34.047 UTC | 2 | 2019-09-10 09:51:30.093 UTC | null | null | null | null | 1,064,134 | null | 1 | 12 | c#|wpf|datagrid | 55,158 | <p>See this answer: </p>
<p><a href="https://stackoverflow.com/questions/7938779/image-column-in-wpf-datagrid">Image Column in WPF DataGrid</a></p>
<pre><code> <DataGridTemplateColumn Header="Image" Width="SizeToCells"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</code></pre>
<p>To add a column in code after:</p>
<pre><code>DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.Header = "Your header";
textColumn1.Binding = new Binding("YourBindingField");
dg.Columns.Add(textColumn1);
</code></pre>
<p>Use <code>DataGridTemplateColumn</code> to add a custom column
See: <a href="https://stackoverflow.com/questions/1951839/how-do-i-show-image-in-wpf-datagrid-column-programmatically">How do I show image in wpf datagrid column programmatically?</a></p> |
15,519,335 | how to add css file in mpdf | <p>I am trying to convert html into pdf using mpdf. Problem is that i am unable to apply css to pdf file.. </p>
<p>Here is my code of php:</p>
<pre><code><?php
$html = $divPrint;
$mpdf=new mPDF();
$stylesheet = file_get_contents('pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output();
exit;
?>
</code></pre>
<p>What it is doing is taking html through ajax on my this php page. But the output it gives doesn't come with css which i've written for it.. </p>
<p>Please tell me that to do now?</p> | 15,567,033 | 1 | 5 | null | 2013-03-20 09:11:39.917 UTC | 4 | 2016-02-17 11:52:06.33 UTC | 2016-02-17 11:52:06.33 UTC | null | 2,544,762 | null | 2,139,315 | null | 1 | 28 | php|html|ajax|mpdf | 72,279 | <pre><code> <?php
$html = $divPrint;
include('mpdf.php'); // including mpdf.php
$mpdf=new mPDF();
$stylesheet = file_get_contents('pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output();
exit;
?>
</code></pre>
<p>1st assign your html in <code>$html</code> then include <strong>mpdf.php</strong> file.</p> |
15,898,843 | what means new static? | <p>I saw in some frameworks this line of code:</p>
<pre><code>return new static($view, $data);
</code></pre>
<p>how do you understand the <code>new static</code>?</p> | 15,899,052 | 1 | 14 | null | 2013-04-09 09:55:20.997 UTC | 33 | 2013-04-23 10:51:24.09 UTC | 2013-04-18 14:23:25.577 UTC | null | 367,456 | null | 2,072,775 | null | 1 | 76 | php | 34,229 | <p>When you write <code>new self()</code> inside a class's member function, you get an instance of that class. <a href="https://stackoverflow.com/q/5197300/560648">That's the magic of the <code>self</code> keyword</a>.</p>
<p>So:</p>
<pre><code>class Foo
{
public static function baz() {
return new self();
}
}
$x = Foo::baz(); // $x is now a `Foo`
</code></pre>
<p>You get a <code>Foo</code> even if the static qualifier you used was for a derived class:</p>
<pre><code>class Bar extends Foo
{
}
$z = Bar::baz(); // $z is now a `Foo`
</code></pre>
<p>If you want to enable polymorphism (in a sense), and have PHP take notice of the qualifier you used, you can swap the <code>self</code> keyword for the <code>static</code> keyword:</p>
<pre><code>class Foo
{
public static function baz() {
return new static();
}
}
class Bar extends Foo
{
}
$wow = Bar::baz(); // $wow is now a `Bar`, even though `baz()` is in base `Foo`
</code></pre>
<p>This is made possible by the PHP feature known as <a href="http://php.net/manual/en/language.oop5.late-static-bindings.php" rel="noreferrer"><em>late static binding</em></a>; don't confuse it for other, more conventional uses of the keyword <code>static</code>.</p> |
15,487,220 | Typescript primitive types: any difference between the types "number" and "Number" (is TSC case-insensitive)? | <p>I meant to write a parameter of type <code>number</code>, but I misspelled the type, writing <code>Number</code> instead. </p>
<p>On my IDE (JetBrains WebStorm) the type <code>Number</code> is written with the same color that is used for the primitive type <code>number</code>, while if I write a name of a class (known or unknown) it uses a different color, so I guess that somehow it recognizes the misspelled type as a correct/almost-correct/sort-of-correct type.</p>
<p>When I compile the code, instead of complaining for example that the compiler couldn't found a class named <code>Number</code>, TSC writes this error message: </p>
<pre><code>Illegal property access
</code></pre>
<p>Does that mean that <code>number</code> and <code>Number</code> both co-exists as different types?</p>
<p>If this is true, which is the difference between those classes?</p>
<p>If this is not the case, then why it simply didn't write the same error message it displays for unknown classes ("The name 'Number' does not exist in the current scope")</p>
<p>This is the code:</p>
<pre><code>class Test
{
private myArray:string[] = ["Jack", "Jill", "John", "Joe", "Jeff"];
// THIS WORKS
public getValue(index:number):string
{
return this.myArray[index];
}
// THIS DOESN'T WORK: ILLEGAL PROPERTY ACCESS
public getAnotherValue(index:Number):string
{
return this.myArray[index];
}
}
</code></pre> | 15,488,171 | 3 | 0 | null | 2013-03-18 21:24:03.34 UTC | 21 | 2020-03-10 20:46:11.137 UTC | 2013-03-19 00:53:56.573 UTC | null | 920,539 | null | 932,845 | null | 1 | 138 | typescript|tsc | 51,139 | <p>JavaScript has the notion of <em>primitive</em> types (number, string, etc) and <em>object</em> types (Number, String, etc, which are manifest at runtime). TypeScript types <code>number</code> and <code>Number</code> refer to them, respectively. JavaScript will usually coerce an object type to its primitive equivalent, or vice versa: </p>
<pre><code>var x = new Number(34);
> undefined
x
> Number {}
x + 1
> 35
</code></pre>
<p>The TypeScript type system rules deal with this (spec section 3.7) like this:</p>
<blockquote>
<p>For purposes of determining subtype, supertype, and assignment
compatibility relationships, the Number, Boolean, and String primitive
types are treated as object types with the same properties as the
‘Number’, ‘Boolean’, and ‘String’ interfaces respectively.</p>
</blockquote> |
25,371,556 | Swift beta 6 - Confusing linker error message | <p>I'm getting an error message from the linker when building a Swift program with Xcode 6 beta 6, targeting iOS 8. This code compiled and ran correctly with beta 5.</p>
<pre><code>Undefined symbol for architecture x86_64:
__TFSs26_forceBridgeFromObjectiveCU__FTPSs9AnyObject_MQ__Q_", referenced from:
__TFC8RayTrace14RayTracingPlot15drawFocalPointfS0_FT_T_ in RayTracingPlot.o
ld: symbol(s) not found for architecture x86_64
</code></pre>
<p>Here's the code in question:</p>
<pre><code>private func drawFocalPoint() {
var attributes = Dictionary<String, AnyObject>()
let FString: String = "F"
let distance: CGFloat = focalDistance
let centerX = CGRectGetMidX(bounds)
let centerY = CGRectGetMidY(bounds)
let circleRadius: CGFloat = 4.0
let focalPointFrame = CGRectMake(0, 0, circleRadius * 2.0, circleRadius * 2.0)
var path = UIBezierPath(ovalInRect: focalPointFrame)
let color = UIColor.blackColor()
let currentContext = UIGraphicsGetCurrentContext()
CGContextSaveGState(currentContext)
let shadowColor = UIColor(white:0, alpha:0.75).CGColor
CGContextSetShadowWithColor(currentContext, CGSizeMake(0, 4), CGFloat(8), shadowColor)
// Image F
var imageFPath = UIBezierPath(CGPath: path.CGPath)
let imageFTransform = CGAffineTransformMakeTranslation((centerX - distance - circleRadius),
(centerY - circleRadius))
imageFPath.applyTransform(imageFTransform)
color.set()
imageFPath.fill()
FString.drawAtPoint(CGPointMake(centerX - distance - circleRadius, centerY + 5), withAttributes:attributes)
CGContextSetShadowWithColor(currentContext, CGSizeMake(0.0, 0.0), CGFloat(0.0), nil) // Clear shadow
CGContextRestoreGState(currentContext)
}
</code></pre>
<p>I'd appreciate a hint about where in this code to look for the error so I can fix it. Thank you.</p> | 25,376,271 | 3 | 9 | null | 2014-08-18 20:31:33.65 UTC | 7 | 2015-04-15 08:49:42.223 UTC | null | null | null | null | 3,730,849 | null | 1 | 59 | swift|xcode6 | 17,788 | <p>I got this error even with the new version of Beta6 that was release hours after the bad one got pulled.</p>
<p>I've solved this and other similarly illegible errors by deleting the contents of the Derived folder. You can find where that folder is located by going to Preferences > Locations. </p>
<p>The default path is:
/Users/[your username]/Library/Developer/Xcode/DerivedData</p>
<p>You can also hold <code>Option</code> while the Product menu is open in Xcode, which will change <code>Clean</code> to <code>Clean Build Folder</code>... and accomplish the same task without having to folder-hunt. </p> |
13,691,539 | How to include C++ headers in an Objective C++ header? | <p>I have a .cpp/.hpp file combo -> the .hpp file has #include ..</p>
<p>I also have a .mm/.h file combo -> if I include the .hpp file within my .mm Objective C++ file, there are no issues. However, if I try to include the .hpp file within my .h (Objective C header) file, I get a preprocessor issue 'iostream not found'.</p>
<p>Is there any way around this other than doing funky stuff like having a void* in my Objective C .h file and then casting it as the type that is included in the .mm or wrapping every C++ type within an Objective C++ type?</p>
<p>My question is basically the same as Tony's question (but nobody answered his):</p>
<p><a href="https://stackoverflow.com/questions/10163322/how-to-include-c-header-file-in-objective-c-header-file">https://stackoverflow.com/questions/10163322/how-to-include-c-header-file-in-objective-c-header-file</a></p> | 13,704,509 | 3 | 6 | null | 2012-12-03 20:56:12.353 UTC | 8 | 2014-07-04 08:05:34.803 UTC | 2017-05-23 12:25:13.63 UTC | null | -1 | null | 705,061 | null | 1 | 15 | c++|ios|import|include|objective-c++ | 16,652 | <p>The problem is that you have to avoid all C++ semantics in the header to allow normal Objective-C classes to include it. This can be accomplished using <a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">opaque pointers</a>.</p>
<h3>CPPClass.h</h3>
<pre><code>class CPPClass
{
public:
int getNumber()
{
return 10;
}
};
</code></pre>
<h3>ObjCPP.h</h3>
<pre><code>//Forward declare struct
struct CPPMembers;
@interface ObjCPP : NSObject
{
//opaque pointer to store cpp members
struct CPPMembers *_cppMembers;
}
@end
</code></pre>
<h3>ObjCPP.mm</h3>
<pre><code>#import "ObjCPP.h"
#import "CPPClass.h"
struct CPPMembers {
CPPClass member1;
};
@implementation ObjCPP
- (id)init
{
self = [super init];
if (self) {
//Allocate storage for members
_cppMembers = new CPPMembers;
//usage
NSLog(@"%d", _cppMembers->member1.getNumber());
}
return self;
}
- (void)dealloc
{
//Free members even if ARC.
delete _cppMembers;
//If not ARC uncomment the following line
//[super dealloc];
}
@end
</code></pre> |
13,589,390 | How to use numpy.where with logical operators | <p>I'm trying to find the indices of all elements in an array that are greater than a but less than b. It's probably just a problem with my syntax but this doesn't work:</p>
<pre><code>numpy.where((my_array > a) and (my_array < b))
</code></pre>
<p>How should I fix this? Or is there a better way to do it?</p>
<p>Thanks!</p> | 13,589,551 | 1 | 4 | null | 2012-11-27 17:10:18.703 UTC | 9 | 2012-11-27 17:19:36.017 UTC | null | null | null | null | 1,803,782 | null | 1 | 48 | python|numpy|where|logical-operators | 76,451 | <p>Here are two ways:</p>
<pre><code>In [1]: my_array = arange(10)
In [2]: where((my_array > 3) & (my_array < 7))
Out[2]: (array([4, 5, 6]),)
In [3]: where(logical_and(my_array > 3, my_array < 7))
Out[3]: (array([4, 5, 6]),)
</code></pre>
<p>For the first (replacing <code>and</code> with <code>&</code>), be careful to add parentheses appropriately: <code>&</code> has higher precedence than the comparison operators. You can also use <code>*</code>, but I wouldn't recommend it: it's hacky and doesn't make for readable code.</p>
<pre><code>In [4]: where((my_array > 3) * (my_array < 7))
Out[4]: (array([4, 5, 6]),)
</code></pre> |
20,851,452 | z-index is canceled by setting transform(rotate) | <p>Using transform property, z-index is canceled and appeared in the front.
(When commenting out -webkit-transform, z-index is properly working in below code)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
width: 150px;
height: 40px;
margin: 30px;
line-height: 40px;
position: relative;
background: white;
-webkit-transform: rotate(10deg);
}
.test:after {
width: 100px;
height: 35px;
content: "";
position: absolute;
top: 0;
right: 2px;
-webkit-box-shadow: 0 5px 5px #999;
/* Safari and Chrome */
-webkit-transform: rotate(3deg);
/* Safari and Chrome */
transform: rotate(3deg);
z-index: -1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>transform</title>
<link rel="stylesheet" type="text/css" href="transformtest.css">
</head>
<body>
<div class="test">z-index is canceled.</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>How do transform and z-index work together?</p> | 20,852,489 | 7 | 3 | null | 2013-12-31 03:52:23.267 UTC | 30 | 2021-05-04 21:22:21.7 UTC | 2017-08-09 16:45:42.823 UTC | null | 2,660,600 | null | 3,024,432 | null | 1 | 107 | css|z-index|transform | 72,490 | <p>Let's walk through what is occurring. To start, note that <code>z-index</code> on positioned elements and <code>transform</code> by itself create new "<a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context" rel="noreferrer">stacking contexts</a>" on elements. Here's what's going on:</p>
<p>Your <code>.test</code> element has <code>transform</code> set to something other than none, which gives it its own stacking context.</p>
<p>You then add a <code>.test:after</code> pseudo-element, which is a child of <code>.test</code>. This child has <code>z-index: -1</code>, setting the stack level of <code>.test:after</code> <strong>within the stacking context of <code>.test</code></strong> Setting <code>z-index: -1</code> on <code>.test:after</code> does not place it behind <code>.test</code> because <code>z-index</code> only has meaning within a given stacking context.</p>
<p>When you remove <code>-webkit-transform</code> from <code>.test</code> it removes its stacking context, causing <code>.test</code> and <code>.test:after</code> to share a stacking context (that of <code><html></code>) and making <code>.test:after</code> go behind <code>.test</code>. Note that after removing <code>.test</code>'s <code>-webkit-transform</code> rule you can, once again, give it its own stacking context by setting a new <code>z-index</code> rule (any value) on <code>.test</code> (again, because it is positioned)!</p>
<p><strong>So how do we solve your problem?</strong></p>
<p>To get z-index working the way you expect, make sure that <code>.test</code> and <code>.test:after</code> share the same stacking context. The problem is that you want <code>.test</code> rotated with transform, but to do so means creating its own stacking context. Fortunately, placing <code>.test</code> in a wrapping container and rotating that will still allow its children to share a stacking context while also rotating both.</p>
<ul>
<li><p>Here's what you started with: <a href="http://jsfiddle.net/fH64Q/" rel="noreferrer">http://jsfiddle.net/fH64Q/</a></p></li>
<li><p>And here's a way you can get around the stacking-contexts and keep
the rotation (note that the shadow gets a bit cut off because of <code>.test</code>'s white background):</p></li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
-webkit-transform: rotate(10deg);
}
.test {
width: 150px;
height: 40px;
margin: 30px;
line-height: 40px;
position: relative;
background: white;
}
.test:after {
width: 100px;
height: 35px;
content: "";
position: absolute;
top: 0;
right: 2px;
-webkit-box-shadow: 0 5px 5px #999; /* Safari and Chrome */
-webkit-transform: rotate(3deg); /* Safari and Chrome */
transform: rotate(3deg);
z-index: -1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="test">z-index is canceled.</div>
</div></code></pre>
</div>
</div>
</p>
<p>There are other ways to do this, better ways even. I would probably make the "post-it" background the containing element and then put the text inside, that would probably be the easiest method and would reduce the complexity of what you have.</p>
<p>Check out <a href="http://philipwalton.com/articles/what-no-one-told-you-about-z-index/" rel="noreferrer">this article</a> for more details about <code>z-index</code> and stacking order, or <a href="http://www.w3.org/TR/2012/WD-css3-positioning-20120207/#det-stacking-context" rel="noreferrer">the working W3C CSS3 spec on stacking context</a></p> |
20,626,994 | How to calculate the inverse of the normal cumulative distribution function in python? | <p>How do I calculate the inverse of the cumulative distribution function (CDF) of the normal distribution in Python?</p>
<p>Which library should I use? Possibly scipy? </p> | 20,627,638 | 3 | 3 | null | 2013-12-17 05:57:49.157 UTC | 39 | 2022-08-15 14:05:56.963 UTC | 2015-03-31 14:52:45.263 UTC | null | 3,139,711 | null | 1,624,752 | null | 1 | 98 | python|scipy|normal-distribution | 161,697 | <p><a href="http://support.microsoft.com/kb/826772" rel="nofollow noreferrer">NORMSINV</a> (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using <code>scipy</code>, you can compute this with the <code>ppf</code> method of the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html" rel="nofollow noreferrer"><code>scipy.stats.norm</code></a> object. The acronym <code>ppf</code> stands for <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda362.htm#PPF" rel="nofollow noreferrer"><em>percent point function</em></a>, which is another name for the <a href="https://en.wikipedia.org/wiki/Quantile_function" rel="nofollow noreferrer"><em>quantile function</em></a>.</p>
<pre><code>In [20]: from scipy.stats import norm
In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722
</code></pre>
<p>Check that it is the inverse of the CDF:</p>
<pre><code>In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996
</code></pre>
<p>By default, <code>norm.ppf</code> uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the <code>loc</code> and <code>scale</code> arguments, respectively.</p>
<pre><code>In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945
</code></pre>
<p>If you look at the source code for <code>scipy.stats.norm</code>, you'll find that the <code>ppf</code> method ultimately calls <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtri.html" rel="nofollow noreferrer"><code>scipy.special.ndtri</code></a>. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:</p>
<pre><code>In [43]: from scipy.special import ndtri
In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722
</code></pre>
<p><code>ndtri</code> is <em>much</em> faster than <code>norm.ppf</code>:</p>
<pre><code>In [46]: %timeit norm.ppf(0.95)
240 µs ± 1.75 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [47]: %timeit ndtri(0.95)
1.47 µs ± 1.3 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
</code></pre> |
3,760,593 | Implement signature-level security on Android services with more than one allowed signature | <p>I'm developing on an application at the moment which contains quite a lot of personal user information - things like Facebook contacts, etc ... Now, one of the things I want to be able to do (and have done, quite effectively) is open up parts of the application to "3rd Party" applications, using Android's build-in inter-process communication protocol (AIDL). So far so good.</p>
<p>Here's the catch: because we're involved in handling quite a lot of personal information, we have to be quite careful about who can and can't access it; specifically, only "Trusted" applications should be able to do so. So the natural way to do this is to use a custom permission within the AndroidManifest.xml file where we declare the services. My problem is this: I want to be able to enact signature-level protection (similar to the normal "signature" permission level), but with a bit of a catch:</p>
<p>I don't <em>only</em> want application signed with our internal signature to be able to access the services. I'd like to be able to build a list of "trusted signatures" & at runtime (or if there's a better way, then maybe some other time?) be able to check incoming requests against this list of trusted keys.</p>
<p>This would satisfy the security constraints in the same way as the normal "signature" permission level I think - only programs on the "trusted keys list" would be able to access the services, and keys are hard to spoof (if possible at all?) - but with the added bonus that we wouldn't have to sign every application making use of the APIs with our internal team's key.</p>
<p>Is this possible at the moment in Android? And if so, are there any special requirements?</p>
<p>Thanks</p> | 3,825,410 | 2 | 0 | null | 2010-09-21 13:12:08.347 UTC | 16 | 2015-10-24 23:05:14.203 UTC | null | null | null | null | 227,224 | null | 1 | 24 | java|android|security|ipc|aidl | 5,386 | <p>I've now found the answer to this question, but I'll leave it for the sake of anyone looking in the future.</p>
<p>I opened up a discussion on android-security-discuss where it was answered. Link: <a href="http://groups.google.com/group/android-security-discuss/browse_thread/thread/e01f63c2c024a767" rel="noreferrer">http://groups.google.com/group/android-security-discuss/browse_thread/thread/e01f63c2c024a767</a></p>
<p>Short answer:</p>
<pre><code> private boolean checkAuthorised(){
PackageManager pm = getPackageManager();
try {
for (Signature sig :
pm.getPackageInfo(pm.getNameForUid(getCallingUid()),
PackageManager.GET_SIGNATURES).signatures){
LogUtils.logD("Signature: " + sig.toCharsString());
if (Security.trustedSignatures.get(sig.toCharsString()) != null) {
return true;
}
}
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogUtils.logD("Couldn't find signature in list of trusted keys! Possibilities:");
for(String sigString : Security.trustedSignatures.keySet()){
LogUtils.logD(sigString);
}
/* Crash the calling application if it doesn't catch */
throw new SecurityException();
}
</code></pre>
<p>Where Security.trustedSignatures is a Map of the form:</p>
<pre><code>Map<String,String>().put("public key","some description eg. name");
</code></pre>
<p>Put this method inside any code that is being called by the external process (ie. within your interface). Note that this will <em>not</em> have the desired effect inside the onBind() method of your RemoteService.</p> |
3,218,821 | C++0x Lambda overhead | <p>Is there any overhead associated with using lambda expressions in C++0x (under VS2010)?<br>
I know that using <em>function</em> objects incurs overhead, but I'm referring to expressions that are passed to STL algorithms, for example. Does the compiler optimize the expression, eliminating what seems to appear like a function call? I started to really like lambda expressions, but I'm a bit concerned about the speed penalty.</p>
<p>Thanks in advance!</p> | 3,218,853 | 2 | 3 | null | 2010-07-10 10:38:32.027 UTC | 8 | 2010-07-10 11:04:25.02 UTC | null | null | null | null | 121,557 | null | 1 | 28 | c++|visual-studio-2010|lambda|c++11|visual-c++-2010 | 10,661 | <p>You "know" that function objects incur overhead? Perhaps you should recheck your facts. :)</p>
<p>There is typically zero overhead to using a STL algorithm with a function object, compared with a hand-rolled loop. A naive compiler will have to repeatedly call <code>operator()</code> on the functor, but that is trivial to inline and so in effect, the overhead is zero.</p>
<p>A lambda expression is nothing more than syntactic sugar for a function object. The code is transformed into a function object by the compiler, so it too has zero overhead.</p> |
29,609,740 | UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' | <p>I have a database configuration class to connect my spring web service with the database. I'm using spring boot, to make it stand alone application.</p>
<p>Here is my class</p>
<pre><code>@Configuration
@EnableTransactionManagement
public class DatabaseConfig {
@Value("${db.driver}")
private String DB_DRIVER;
@Value("${db.password}")
private String DB_PASSWORD;
@Value("${db.url}")
private String DB_URL;
@Value("${db.username}")
private String DB_USERNAME;
@Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
@Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
@Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
@Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto",
HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
@Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
</code></pre>
<p>Every time I try to run my code, it throws exceptions:</p>
<pre><code>Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder]: : Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.orm.jpa.JpaVendorAdapter]: : Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.orm.jpa.JpaVendorAdapter]: : Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
at org.elsys.internetprogramming.trafficspy.server.Application.main(Application.java:14)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.orm.jpa.JpaVendorAdapter]: : Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:464)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 18 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 32 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 45 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/OptimisticLockException
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.<clinit>(HibernateJpaDialect.java:94)
at org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter.<init>(HibernateJpaVendorAdapter.java:64)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration.createJpaVendorAdapter(HibernateJpaAutoConfiguration.java:93)
at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:88)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$88de780c.CGLIB$jpaVendorAdapter$5(<generated>)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$88de780c$$FastClassBySpringCGLIB$$fe8b7313.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:309)
at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration$$EnhancerBySpringCGLIB$$88de780c.jpaVendorAdapter(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 46 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.OptimisticLockException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 60 more
</code></pre>
<p>As far as I can understand, there is a missing dependency but I don't know which. Or maybe the problem is something else? Here are my dependencies in pom.xml</p>
<pre><code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-cloud-connectors
</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
<packaging>jar</packaging>
</project>
</code></pre>
<p>Do you know what causes the problem and any suggestions how to fix it?</p> | 29,610,303 | 2 | 2 | null | 2015-04-13 15:54:27.94 UTC | 6 | 2020-08-24 10:21:19.173 UTC | 2015-04-13 16:09:32.31 UTC | null | 3,816,260 | null | 3,816,260 | null | 1 | 19 | java|spring|hibernate|maven|spring-boot | 167,401 | <p>Well, you're getting a <code>java.lang.NoClassDefFoundError</code>. In your <code>pom.xml</code>, <code>hibernate-core</code> version is <code>3.3.2.GA</code> and declared after <code>hibernate-entitymanager</code>, so it prevails. You can remove that dependency, since will be inherited version <code>3.6.7.Final</code> from <code>hibernate-entitymanager</code>.</p>
<p>You're using <code>spring-boot</code> as parent, so no need to declare version of some dependencies, since they are managed by <code>spring-boot</code>.</p>
<p>Also, <code>hibernate-commons-annotations</code> is inherited from <code>hibernate-entitymanager</code> and <code>hibernate-annotations</code> is an old version of <code>hibernate-commons-annotations</code>, you can remove both.</p>
<p>Finally, your <code>pom.xml</code> can look like this:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
<artifactId>TrafficSpyService</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.3.RELEASE</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cloud-connectors</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
<java.version>1.7</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/org/codehaus</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
</code></pre>
<p>Let me know if you have a problem.</p> |
16,540,808 | Can I configure multiple plugin executions in pluginManagement, and choose from them in my child POM? | <p>I have 2 common plugin-driven tasks that I want to execute in my projects. Because they're common, I want to move their configuration to the <code>pluginMangement</code> section of a shared parent POM. However, both of the 2 tasks, whilst otherwise completely distinct, use the same plugin. In some of my projects I only want to do 1 of the 2 tasks (I don't always want to run all executions of the plugin).</p>
<p>Is there a way to specify multiple different executions of a plugin, within the <code>pluginManagement</code> section of a parent pom, and choose in my child pom one (and only one) of those executions to actually run? If I configure 2 executions in <code>pluginManagement</code>, it seems that both executions will run.</p>
<p>Note: I think this may, or may not, be a duplicate of question <a href="https://stackoverflow.com/questions/1266226/maven2-problem-with-pluginmanagement-and-parent-child-relationship">Maven2 - problem with pluginManagement and parent-child relationship</a>, but as the question is nearly 4 screenfuls long (TL;DR), a succinct duplicate might be worthwhile.</p> | 16,544,702 | 1 | 1 | null | 2013-05-14 10:29:08.88 UTC | 10 | 2013-05-15 10:27:52.827 UTC | 2017-05-23 12:17:47.897 UTC | null | -1 | null | 37,941 | null | 1 | 42 | maven|maven-3 | 26,291 | <p>You're correct, by default Maven will include all of the executions you have configured. Here's how I've dealt with that situation before.</p>
<pre><code><pluginManagement>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>some-maven-plugin</artifactId>
<version>1.0</version>
<executions>
<execution>
<id>first-execution</id>
<phase>none</phase>
<goals>
<goal>some-goal</goal>
</goals>
<configuration>
<!-- plugin config to share -->
</configuration>
</execution>
<execution>
<id>second-execution</id>
<phase>none</phase>
<goals>
<goal>other-goal</goal>
</goals>
<configuration>
<!-- plugin config to share -->
</configuration>
</execution>
</executions>
</plugin>
</pluginManagement>
</code></pre>
<p>Note, the executions are bound to phase <code>none</code>. In the child, you enable the parts that should execute like this:</p>
<pre><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>some-maven-plugin</artifactId>
<executions>
<execution>
<id>first-execution</id> <!-- be sure to use ID from parent -->
<phase>prepare-package</phase> <!-- whatever phase is desired -->
</execution>
<!-- enable other executions here - or don't -->
</executions>
</plugin>
</code></pre>
<p>If the child doesn't explicitly bind the execution to a phase, it won't run. This allows you to pick and choose the executions desired.</p> |
16,209,623 | IncompatibleClassChangeError: class ClassMetadataReadingVisitor has interface ClassVisitor as super class | <p>I have built a web application using spring-mvc and mongodb as database. I used maven3 to build the application.</p>
<p>Project builds successfully but when application starts I am getting the following error in the logs due to which my application does not start. This used to work few months ago.</p>
<blockquote>
<p>Caused by: java.lang.IncompatibleClassChangeError: class
org.springframework.core.type.classreading.ClassMetadataReadingVisitor
has interface org.springframework.asm.ClassVisitor as super class</p>
</blockquote>
<p>Please let me know if any pointers or if you guys need more information.</p> | 16,209,661 | 5 | 1 | null | 2013-04-25 08:13:56.923 UTC | 6 | 2018-08-09 11:18:35.667 UTC | 2014-03-29 20:40:49.493 UTC | null | 1,391,249 | null | 487,171 | null | 1 | 46 | java|spring-mvc|maven-3 | 67,032 | <p>This error happens when the loaded class i.e. <code>ClassMetadataReadingVisitor</code> does not respect the contract of inherited abstract class or interface i.e. <code>ClassVisitor</code>.</p>
<p>Looks like at load time different versions of the above classes are getting loaded in your case.</p>
<p>Seems you have new spring-core jar and old spring-asm jar in your application. <code>ClassMetadataReadingVisitor</code> class is getting loaded from <strong>spring-core</strong> and <code>ClassVisitor</code> from <strong>spring-asm</strong>.</p>
<p>Please check using maven <code>dependency:tree</code> command to see the dependent jars.</p> |
41,818,089 | reactjs, bootstrap and npm import - jQuery is not defined | <p>I'm trying to use bootstrap in my react app, but it gives me a<code>Error: Bootstrap's JavaScript requires jQuery</code>. I have imported jquery and have tried tried the following from other posts: </p>
<pre><code>import $ from 'jquery';
window.jQuery = $;
window.$ = $;
global.jQuery = $;
</code></pre>
<p>However, I still get the <code>not defined</code> error.</p>
<p>The only way to fix this is to put</p>
<pre><code> src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</code></pre>
<p>into index.html</p>
<p>is there a way to export jquery or have bootstrap be able to detect/read it?</p>
<p>I call my bootstrap via</p>
<pre><code>import bootstrap from 'bootstrap'
</code></pre> | 43,045,671 | 4 | 13 | null | 2017-01-24 00:29:53.143 UTC | 2 | 2018-03-15 15:55:36.65 UTC | 2017-04-28 13:03:58.513 UTC | null | 4,831,179 | null | 6,554,121 | null | 1 | 12 | javascript|twitter-bootstrap|reactjs|npm|create-react-app | 39,529 | <h1><del><code>import bootstrap from 'bootstrap'</code></del></h1>
<h1><code>const bootstrap = require('bootstrap');</code></h1>
<p>I tried to build a project with "create-react-app" and found that the loading order of imported modules is not same with importing order. And this is the reason why boostrap can't find jquery. Generally, you can use "require" in this condition. It works on my pc.</p>
<pre><code>import $ from 'jquery';
window.jQuery = $;
window.$ = $;
global.jQuery = $;
const bootstrap = require('bootstrap');
console.log(bootstrap)
</code></pre>
<p>Relevant things:</p>
<h3><code>imports</code> are hoisted</h3>
<p><a href="https://stackoverflow.com/a/29334761/4831179">https://stackoverflow.com/a/29334761/4831179</a></p>
<h3><code>imports</code> should go first</h3>
<blockquote>
<p>Notably, imports are hoisted, which means the imported modules will be evaluated before any of the statements interspersed between them. Keeping all imports together at the top of the file may prevent surprises resulting from this part of the spec.</p>
</blockquote>
<p>from <a href="https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md" rel="noreferrer">https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md</a></p> |
15,145,929 | 404 error with Ajax request | <p>I need to grab some data from a JSP page that does a select on a database and then put inside a div. I need to do this with ajax.</p>
<p>Here is my code:</p>
<pre><code>$(function() {
teste();
});
function teste() {
var v1 = document.getElementById("selCodigo").value;
alert(v1);
$.ajax({
type : "GET",
data : "turma="+v1,
url : "busca-notas.jsp",
success : function(resposta){
alert("DEU CERTO");
},
error : function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
document.getElementById("notas").innerHTML = "ERRO";
}
});
}
</code></pre>
<p>I tested the variable <code>v1</code> and the value that it receives necessary, and in my JSP page, I do this:</p>
<pre><code>String turmaSelecionada = request.getParameter("turma");
</code></pre>
<p>the problem is that the ajax content that does not feed into the div need, beyond what the <code>xhr.status</code> presents thrownError and a 404 error not found</p>
<p>Can anyone help me?</p> | 15,146,062 | 2 | 2 | null | 2013-02-28 21:24:12.203 UTC | 1 | 2013-02-28 21:33:38.3 UTC | 2013-02-28 21:28:16.643 UTC | null | 707,111 | null | 1,810,523 | null | 1 | 3 | javascript|jquery|ajax|jsp | 41,878 | <p>Either, <code>busca-notas.jsp</code> does not exist, or it is on a different server or path as the HTML calling the Ajax request.</p>
<p>Example: If your HTML and JavaScript is here:</p>
<pre><code>http://www.example.com/somepath/page.html
</code></pre>
<p>and your PHP code is here:</p>
<pre><code>http://www.example.com/otherpath/busca-notas.jsp
</code></pre>
<p>then you'll Need to use <code>url: "../otherpath/busca-notas.jps"</code>. There is an easy way to check: Open your HTML in the browser, remove the last bit of the path, and replace it with "busca-notas.jpg", and see what you're getting.</p>
<p>A 404 also means, your JSP code never gets executed.</p> |
17,220,642 | how to convert bit datatype to varchar in sql | <p>How to convert BIT datatype to Varchar in sql ?</p>
<p>I tried CAST</p>
<blockquote>
<p><code>CAST(IsDeleted as Varchar(512))</code></p>
</blockquote>
<p>But it didn't work....</p>
<p>Note: <strong>IsDeleted</strong> is a BIT datatype and I need to convert it into Varchar or Int</p> | 17,220,802 | 4 | 3 | null | 2013-06-20 18:03:59.23 UTC | null | 2015-03-17 14:08:09.427 UTC | 2015-03-17 14:08:09.427 UTC | null | 2,327,795 | null | 2,327,795 | null | 1 | 3 | c#|mysql | 43,626 | <p>Assuming this is MySQL, you can't cast to <code>VARCHAR</code>. The allowable types are shown <a href="http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast">here</a>; they're listed after the <code>CONVERT</code> function explanation.</p>
<p>You can cast to <code>CHAR(1)</code> though. For example:</p>
<pre><code>CAST(b'11' AS CHAR(1))
</code></pre> |
17,506,038 | Getting the last non-empty cell in a row | <p>I am having a lot of difficulty trying to come up with a way to 'parse' and 'order' my excel spreadsheet. What I essentially need to do is get the last non empty cell from every row and cut / paste it a new column.</p>
<p>I was wondering if there is an easy way to do this? </p>
<p>I appreciate any advice. Many thanks in advance!</p> | 17,507,233 | 3 | 4 | null | 2013-07-06 18:50:59.017 UTC | 5 | 2013-07-11 14:29:09.807 UTC | 2013-07-06 19:04:24.47 UTC | null | 1,316,524 | null | 1,316,524 | null | 1 | 16 | excel|excel-formula | 76,831 | <p>Are your values numeric or text (or possibly both)?</p>
<p>For numbers get last value with this formula in Z2</p>
<p><code>=LOOKUP(9.99E+307,A2:Y2)</code></p>
<p>or for text....</p>
<p><code>=LOOKUP("zzz",A2:Y2)</code></p>
<p>or for either...</p>
<p><code>=LOOKUP(2,1/(A2:Y2<>""),A2:Y2)</code></p>
<p>all the formulas work whether you have blanks in the data or not......</p> |
21,986,194 | How to pass dictionary items as function arguments in python? | <p>My code</p>
<p>1st file:</p>
<pre><code>data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(*data)
</code></pre>
<p>2nd file:</p>
<pre><code>my_function(*data):
schoolname = school
cityname = city
standard = standard
studentname = name
</code></pre>
<p>in the above code, only keys of "data" dictionary were get passed to <code>my_function()</code>, but i want key-value pairs to pass. How to correct this ?</p>
<p>I want the <code>my_function()</code> to get modified like this </p>
<pre><code>my_function(school='DAV', standard='7', name='abc', city='delhi')
</code></pre>
<p>and this is my requirement, give answers according to this </p>
<p><em>EDIT:</em> dictionary key <em>class</em> is changed to <em>standard</em> </p> | 21,986,301 | 3 | 3 | null | 2014-02-24 11:17:21.88 UTC | 31 | 2020-02-25 22:25:00.357 UTC | 2016-08-15 15:39:50.46 UTC | null | 1,391,441 | null | 3,291,873 | null | 1 | 129 | python|function|python-2.7|dictionary | 261,927 | <p>If you want to use them like that, define the function with the variable names as normal:</p>
<pre class="lang-py prettyprint-override"><code>def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name
</code></pre>
<p>Now you can use <code>**</code> when you <em>call</em> the function:</p>
<pre class="lang-py prettyprint-override"><code>data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(**data)
</code></pre>
<p>and it will work as you want.</p>
<p><strong>P.S.</strong> Don't use reserved words such as <code>class</code>.(e.g., use <code>klass</code> instead)</p> |
22,383,820 | Qt - Converting float to QString | <p>This seems like it should be very simple, but I'm going through the docs and not seeing anything. I just need to convert a number that is represented as a <code>float</code> object into a <code>QString</code> object. I know there is the function <code>QString::number()</code> that can be used for other types like <code>int</code> and <code>double</code>, like so:
<code>int a = 1;
QString b = QString::number(a);</code></p>
<p>...however this doesn't seem to work for <code>float</code>. Perhaps there is some way where it is converted first from <code>float</code> to another type, and then from that type to <code>QString</code>? If anyone has any ideas I'd appreciate it. Thanks!</p> | 22,383,874 | 1 | 3 | null | 2014-03-13 15:46:29.64 UTC | 4 | 2014-03-13 15:54:44.533 UTC | null | null | null | null | 2,661,085 | null | 1 | 19 | c++|qt|type-conversion | 65,710 | <p><code>float</code> will auto-promote to <code>double</code> when needed</p>
<pre><code>float pi = 3.14;
QString b = QString::number(pi);
</code></pre>
<p>should work</p>
<p>otherwise you can use setNum:</p>
<pre><code>float pi = 3.14;
QString b;
b.setNum(pi);
</code></pre> |
21,881,362 | Why does ~True result in -2? | <p>In Python console:</p>
<pre><code>~True
</code></pre>
<p>Gives me:</p>
<pre><code>-2
</code></pre>
<p>Why? Can someone explain this particular case to me in binary?</p> | 21,881,463 | 3 | 5 | null | 2014-02-19 13:04:51.307 UTC | 12 | 2019-07-06 07:04:35.427 UTC | 2014-10-10 19:06:32.68 UTC | null | 2,479,481 | null | 1,004,946 | null | 1 | 137 | python|data-conversion|tilde | 6,415 | <p><code>int(True)</code> is <code>1</code>.</p>
<p><code>1</code> is:</p>
<pre><code>00000001
</code></pre>
<p>and <code>~1</code> is:</p>
<pre><code>11111110
</code></pre>
<p>Which is <code>-2</code> in <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">Two's complement</a><sup>1</sup></p>
<p><sup>1</sup> Flip all the bits, add 1 to the resulting number and interpret the result as a <em>binary representation</em> of the magnitude and add a negative sign (since the number begins with 1):</p>
<pre><code>11111110 → 00000001 → 00000010
↑ ↑
Flip Add 1
</code></pre>
<p>Which is 2, but the sign is negative since the <a href="http://en.wikipedia.org/wiki/Most_significant_bit" rel="noreferrer">MSB</a> is 1.</p>
<hr>
<p>Worth mentioning:</p>
<p>Think about <code>bool</code>, you'll find that it's numeric in nature - It has two values, <code>True</code> and <code>False</code>, and they are just "customized" versions of the integers 1 and 0 that only print themselves differently. They are <em>subclasses</em> of the integer type <code>int</code>.</p>
<p>So they behave exactly as 1 and 0, except that <code>bool</code> redefines <code>str</code> and <code>repr</code> to display them differently.</p>
<pre><code>>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True
>>> True == 1
True
>>> True is 1 # they're still different objects
False
</code></pre> |
21,595,289 | IntelliJ IDEA consuming lots of CPU | <p>I upgraded from IntelliJ IDEA from 12 CE to 13 CE few days ago and it has been hogging up CPU. Every few minutes it'll peak to 450-500% and then come down to 100-200%. Also, I've upgraded my Scala plugin to 0.30.380. Not sure what's causing the issue!?</p> | 21,599,618 | 5 | 6 | null | 2014-02-06 06:07:24.04 UTC | 5 | 2022-03-22 15:16:33.193 UTC | 2022-03-22 15:16:33.193 UTC | null | 108,915 | null | 3,117,698 | null | 1 | 47 | scala|intellij-idea | 17,754 | <p>I'm posting this comment by K P as an answer, because K P does not have enough reputation.</p>
<blockquote>
<p>It just needed some more memory to prevent repeated garbage collection. I found the file idea.vmoptions [aka idea64.exe.vmoptions] and increased the memory for InteiiJ to run (Xms = 512m and Xmx = 2048). The CPU usage has come down to 0.2 - 10% when nothing is being done on it.</p>
</blockquote> |
26,540,165 | TypeScript and libraries such as jQuery (with .d.ts files) | <p>I've looked all over the internets but I have yet to find a comprehensive guide that tells me how to take a library such as jquery and use it in a TypeScript project. If there is a guide that exists I would love to know where otherwise these are the things I really need to know:</p>
<ol>
<li>I understand that the .d.ts file is only for intellisense so what do I need to get jquery to actually work (compile to ts?)</li>
<li>Do I need a <code>requires</code> or a <code>//reference</code> when using VS2013 and if so what is that actually doing?</li>
<li>Anything to go from these .d.ts and jquery js files to using the library (or any library) in my ts project.</li>
</ol>
<p>I've been able to figure pretty much everything else out but this one has been rather frustrating.</p> | 26,541,175 | 4 | 2 | null | 2014-10-24 01:34:43.45 UTC | 7 | 2019-01-03 10:51:33.15 UTC | 2014-10-24 03:27:17.147 UTC | null | 2,525,751 | null | 2,525,751 | null | 1 | 34 | javascript|jquery|typescript | 39,300 | <p>You don't need to compile jquery to typescript, you just need to use a definition file that tells Typescript how the JavaScript library works.</p>
<p>Get definitions here:
<a href="https://github.com/DefinitelyTyped/DefinitelyTyped" rel="nofollow noreferrer">https://github.com/DefinitelyTyped/DefinitelyTyped</a></p>
<p>or from NuGet if using Visual Studio.</p>
<p>Then just write your typescript as normal, and declare your library if needed:</p>
<p><code>declare var library : libraryTypedName</code></p>
<p>for example jquery's d.ts file already does this for you (check the bottom):</p>
<pre><code>declare module "jquery" {
export = $;
}
declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;
</code></pre>
<p><a href="https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jquery" rel="nofollow noreferrer">https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jquery</a></p>
<p>Now in your <code>.ts</code> file when you type <code>$</code> it should give you the typescript intellisense.</p>
<p>Now the only things you want to include in your bundleconfig / <code><script></code> are the .js files, both yours and jquery / other libraries. Typescript is COMPILE time only!</p> |
19,750,635 | icon in menu not showing in android | <p>I want to add menu handler to my project. I read <a href="http://developer.android.com/guide/topics/ui/menus.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/menus.html</a> too, its very simple but the icon is not shown. I am very confused. I even added a menu item programmatically.</p>
<p>My code is:</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Quit").setIcon(R.drawable.ic_launcher);
getMenuInflater().inflate(R.layout.menu, menu);
return true;
}
</code></pre>
<p>and in xml:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Single menu item
Set id, icon and Title for each menu item
-->
<item android:id="@+id/menu_bookmark"
android:icon="@drawable/update"
android:title="@string/Update" />
</menu>
</code></pre> | 19,750,717 | 11 | 6 | null | 2013-11-03 07:06:19.15 UTC | 4 | 2020-06-11 02:01:30.3 UTC | 2016-11-04 14:56:39.767 UTC | null | 984,724 | null | 2,580,975 | null | 1 | 43 | android | 88,379 | <p>If you're running your code on Android 3.0+, the icons in the menu are not shown by design. This is a design decision by Google.</p>
<p>You can read more about it in <a href="http://android-developers.blogspot.in/2012/01/say-goodbye-to-menu-button.html" rel="noreferrer">this</a> on Android developers blog.</p> |
21,656,766 | Why isn't setTimeout cancelling my loop? | <p>I wondered how many times can a JavaScript <code>while</code> statement (in Chrome's console) can increment a variable in a millisecond, so I quickly wrote this snippet directly into console:</p>
<pre><code>var run = true, i = 0;
setTimeout(function(){ run = false; }, 1);
while(run){ i++; }
</code></pre>
<p>The problem is that it runs forever.<br>
Why is this happening, and how can I solve it?</p> | 21,656,808 | 6 | 9 | null | 2014-02-09 08:04:37.657 UTC | 10 | 2017-11-06 10:56:00.507 UTC | 2017-11-06 10:56:00.507 UTC | null | 561,309 | null | 3,215,056 | null | 1 | 75 | javascript|infinite-loop|single-threaded | 3,781 | <p>This comes back to the one-threaded nature of JavaScript<sup>1</sup>. What happens is pretty much this:</p>
<ol>
<li>Your variables are assigned.</li>
<li>You schedule a function, to set <code>run = false</code>. This is scheduled to be run <strong>after</strong> the current function is run (or whatever else is currently active).</li>
<li>You have your endless loop and stay inside the current function.</li>
<li>After your endless loop (<strong>never</strong>), the <code>setTimeout()</code> callback will be executed and <code>run=false</code>.</li>
</ol>
<p>As you can see, a <code>setTimeout()</code> approach wont work here. You might work around that by checking the time in the <code>while</code> condition, but this will tamper with your actual measurement.</p>
<p><sup>1</sup> At least for more practical purposes you can see it as single-threaded. Actually there is an so called "event-loop". In that loop all functions get queued until they are executed. If you queue up a new function, it is put at the respective position inside that queue. <em>After</em> the current function has finished, the engine takes the next function from the queue (with respect to timings as introduced, e.g., by <code>setTimeout()</code> and executes it.<br>
As a result at every point in time just one function is executed, thus making the execution pretty much single threaded. There are some exceptions for events, which are discussed in the link below.</p>
<hr>
<p>For reference:</p>
<ul>
<li><p><a href="https://stackoverflow.com/a/16757582/1169798">https://stackoverflow.com/a/16757582/1169798</a></p>
<p>Here a similar scenario was explained in more detail</p></li>
<li><p><a href="https://stackoverflow.com/a/2734311/1169798">https://stackoverflow.com/a/2734311/1169798</a></p>
<p>A more in-depth description on when JS can be seen as single-threaded and when not.</p></li>
</ul> |
17,319,784 | Call angularjs service from simple js code | <p>I have the following angularjs service:</p>
<pre><code>angular.module('app.main').factory('MyService', ["$http", function ($http) {
return new function () {
this.GetName = function () {
return "MyName";
};
};
}]);
</code></pre>
<p>How can I call <code>GetName</code> function from <code>MyService</code> from legacy js code?</p> | 17,328,715 | 4 | 0 | null | 2013-06-26 12:17:35.95 UTC | 13 | 2020-09-09 18:36:41.97 UTC | null | null | null | null | 871,672 | null | 1 | 29 | javascript|angularjs|angularjs-service | 25,730 | <p>Use <a href="https://docs.angularjs.org/api/auto/service/$injector" rel="noreferrer">angular.injector</a>. Using your code you can do something like the following:</p>
<pre><code>angular.module('main.app', []).factory('MyService', ['$http', function ($http) {
return new function () {
this.GetName = function () {
return "MyName";
};
};
}]);
angular.injector(['ng', 'main.app']).get("MyService").GetName();
</code></pre>
<p>Here is the jsfiddle: <a href="http://jsfiddle.net/wGeNG/" rel="noreferrer">http://jsfiddle.net/wGeNG/</a></p>
<p><strong>NOTE</strong> - You need to add "ng" as your first module before loading your custom module since your example code depends upon $http provider which is in the ng module.</p>
<p><strong>EDIT</strong> - Using <code>get()</code> as in OP's answer <strong>but</strong> note this code is fetching the service without relying upon the element being bound to the app module "main.app". </p> |
18,244,110 | Use bash curl with oauth to return google apps user account data? | <p>I am looking for a fairly simple method to use curl to return information about a batch of users accounts (like createddate or lastlogin) in google Apps. I am very inexperienced with curl and the Google Apps api's.</p>
<p>Does anyone know of a good introductory article on how to use curl with Oauth to request user account data? </p>
<p>Thank you in advance! </p> | 18,260,206 | 2 | 0 | null | 2013-08-14 23:40:23.83 UTC | 9 | 2017-11-16 16:05:59.437 UTC | 2017-04-18 18:13:01.343 UTC | null | 436,085 | null | 2,455,949 | null | 1 | 12 | api|curl|oauth-2.0|google-apps|google-admin-sdk | 14,077 | <p>This isn't easily achieved as OAuth 2.0 and JSON aren't easily handled by Bash. Having said that, here's a basic version that'll give you the data you're looking for. The greps could use some cleanup but then again, interpreting JSON with grep is <a href="https://stackoverflow.com/a/1955627/1503886">a really bad idea</a> anyway. This is a perfect example of why the <a href="https://developers.google.com/discovery/libraries" rel="noreferrer">Google API Libraries</a> exist and should be used.</p>
<pre><code>
# Store our credentials in our home directory with a file called .
my_creds=~/.`basename $0`
# create your own client id/secret
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#creatingcred
client_id='YOUR OWN CLIENT ID'
client_secret='YOUR OWN SECRET'
if [ -s $my_creds ]; then
# if we already have a token stored, use it
. $my_creds
time_now=`date +%s`
else
scope='https://www.googleapis.com/auth/admin.directory.user.readonly'
# Form the request URL
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#step-2-send-a-request-to-googles-oauth-20-server
auth_url="https://accounts.google.com/o/oauth2/v2/auth?client_id=$client_id&scope=$scope&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob"
echo "Please go to:"
echo
echo "$auth_url"
echo
echo "after accepting, enter the code you are given:"
read auth_code
# exchange authorization code for access and refresh tokens
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#exchange-authorization-code
auth_result=$(curl -s "https://www.googleapis.com/oauth2/v4/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d code=$auth_code \
-d client_id=$client_id \
-d client_secret=$client_secret \
-d redirect_uri=urn:ietf:wg:oauth:2.0:oob \
-d grant_type=authorization_code)
access_token=$(echo -e "$auth_result" | \
grep -Po '"access_token" *: *.*?[^\\]",' | \
awk -F'"' '{ print $4 }')
refresh_token=$(echo -e "$auth_result" | \
grep -Po '"refresh_token" *: *.*?[^\\]",*' | \
awk -F'"' '{ print $4 }')
expires_in=$(echo -e "$auth_result" | \
grep -Po '"expires_in" *: *.*' | \
awk -F' ' '{ print $3 }' | awk -F',' '{ print $1}')
time_now=`date +%s`
expires_at=$((time_now + expires_in - 60))
echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi
# if our access token is expired, use the refresh token to get a new one
# https://developers.google.com/identity/protocols/OAuth2InstalledApp#offline
if [ $time_now -gt $expires_at ]; then
refresh_result=$(curl -s "https://www.googleapis.com/oauth2/v4/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d refresh_token=$refresh_token \
-d client_id=$client_id \
-d client_secret=$client_secret \
-d grant_type=refresh_token)
access_token=$(echo -e "$refresh_result" | \
grep -Po '"access_token" *: *.*?[^\\]",' | \
awk -F'"' '{ print $4 }')
expires_in=$(echo -e "$refresh_result" | \
grep -Po '"expires_in" *: *.*' | \
awk -F' ' '{ print $3 }' | awk -F',' '{ print $1 }')
time_now=`date +%s`
expires_at=$(($time_now + $expires_in - 60))
echo -e "access_token=$access_token\nrefresh_token=$refresh_token\nexpires_at=$expires_at" > $my_creds
fi
# call the Directory API list users endpoint, may be multiple pages
# https://developers.google.com/admin-sdk/directory/v1/reference/users/list
while :
do
api_data=$(curl -s --get https://www.googleapis.com/admin/directory/v1/users \
-d customer=my_customer \
-d prettyPrint=true \
`if [ -n "$next_page" ]; then echo "-d pageToken=$next_page"; fi` \
-d maxResults=500 \
-d "fields=users(primaryEmail,creationTime,lastLoginTime),nextPageToken" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $access_token")
echo -e "$api_data" | grep -v 'nextPageToken'
next_page=$(echo $api_data | \
grep -Po '"nextPageToken" *: *.*?[^\\]"' | \
awk -F'"' '{ print $4 }')
if [ -z "$next_page" ]
then
break
fi
done
</code></pre> |
18,297,378 | WeakReference/AsyncTask pattern in android | <p>I have a question regarding this simple frequently occurring situation in android . </p>
<p>We have a main activity , we invoke an AsyncTask alongwith the reference of the mainactivity , so that that the AsyncTask can update the views on the MainActivity.</p>
<p>I will break down the event into steps</p>
<ul>
<li>MainActivity creates an AyncTask , passes its reference to it .</li>
<li>AysncTask , starts it's work , downloading ten files for example</li>
<li>The user changed the orientation of the device. This results in an orphan pointer in the AsyncTask </li>
<li>When the AsyncTask completes , and tries to access the activity to update the status , it crashes , because of the null pointer . </li>
</ul>
<p>The solution for the above is to keep a WeakReference in the AsyncTask as recommended by the book "Pro Android 4" </p>
<pre><code>WeakReference<Activity> weakActivity;
in method onPostExecute
Activity activity = weakActivity.get();
if (activity != null) {
// do your stuff with activity here
}
</code></pre>
<p>How does this resolve the situation ?</p>
<p>My question it , if my asynctask is downloading ten files , and upon completion of 5 the activity is restarted (because of an orientation change) then would my FileDownloadingTask be invoked once again ?. </p>
<p>What would happen to the previous AsyncTask that was initially invoked ? </p>
<p>Thank you , and I apologize for the length of the question . </p> | 18,309,382 | 3 | 1 | null | 2013-08-18 08:50:12.783 UTC | 19 | 2017-04-24 06:09:04.967 UTC | null | null | null | null | 1,348,423 | null | 1 | 60 | java|android|android-asynctask|weak-references | 18,639 | <blockquote>
<p>How does this resolve the situation ?</p>
</blockquote>
<p>The <code>WeakReference</code> allows the <code>Activity</code> to be garbage collected, so you don't have a memory leak. </p>
<p>A null reference means that the <code>AsyncTask</code> <em>cannot</em> blindly try to update a user-interface that is no longer attached, which would throw exceptions (e.g. view not attached to window manager). Of course you have to check for null to avoid NPE.</p>
<blockquote>
<p>if my asynctask is downloading ten files , and upon completion of 5 the activity is restarted (because of an orientation change) then would my FileDownloadingTask be invoked once again ?.</p>
</blockquote>
<p>Depends on your implementation, but probably yes - if you don't deliberately do something to make a repeat download unnecessary, such as caching the results somewhere.</p>
<blockquote>
<p>What would happen to the previous <code>AsyncTask</code> that was initially invoked ?</p>
</blockquote>
<p>In earlier versions of Android it would run to completion, downloading all of the files only to throw them away (or perhaps cache them, depending on your implementation).</p>
<p>In newer Android's I am suspicious that <code>AsyncTask</code>'s are being killed along with the <code>Activity</code> that started them, but my basis for suspicion is only that the memory-leak demo's for <a href="https://github.com/octo-online/robospice" rel="noreferrer">RoboSpice</a> (see below) do not actually leak on my JellyBean devices.</p>
<p>If I may offer some advice: <code>AsyncTask</code> is not suitable for performing potentially long running tasks such as networking. </p>
<p><code>IntentService</code> is a better (and still relatively simple) approach, if a single worker thread is acceptable to you. Use a (local) <code>Service</code> if you want control over the thread-pool - and be careful not to do work on the main thread!</p>
<p><a href="https://github.com/octo-online/robospice" rel="noreferrer">RoboSpice</a> seems good if you are looking for a way to reliably perform networking in the background (disclaimer: I have not tried it; I am not affiliated). There is a <a href="https://play.google.com/store/apps/details?id=com.octo.android.robospice.motivations" rel="noreferrer">RoboSpice Motivations demo app</a> in the play store which explains <em>why</em> you should use it by demo-ing all the things that can go wrong with <code>AsyncTask</code> - including the WeakReference workaround.</p>
<p>See also this thread: <a href="https://stackoverflow.com/questions/3357477/is-asynctask-really-conceptually-flawed-or-am-i-just-missing-something">Is AsyncTask really conceptually flawed or am I just missing something?</a></p>
<p>Update: </p>
<p>I created a <a href="https://github.com/steveliles/Android-Download-Service-Example" rel="noreferrer">github project</a> with an example of downloading using <code>IntentService</code> for another SO question (<a href="https://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception">How to fix android.os.NetworkOnMainThreadException?</a>), but it is also relevant here, I think. It has the added advantage that, by returning the result via <code>onActivityResult</code>, a download that is in flight when you rotate the device will deliver to the restarted <code>Activity</code>.</p> |
26,182,460 | JavaFX 8 HiDPI Support | <p>I just tried out the <a href="http://docs.oracle.com/javase/8/javafx/get-started-tutorial/hello_world.htm">JavaFX Hello World Example</a> on a 4k screen on Arch Linux, but unfortunately the GUI does not scale. </p>
<p>The <a href="http://docs.oracle.com/javase/8/javafx/get-started-tutorial/jfx-overview.htm">documentation</a> says</p>
<blockquote>
<p>Hi-DPI support. JavaFX 8 now supports Hi-DPI displays.</p>
</blockquote>
<p>So how can I make my application dpi aware?</p> | 26,184,471 | 2 | 2 | null | 2014-10-03 15:55:41.957 UTC | 9 | 2019-11-26 14:11:36.023 UTC | null | null | null | null | 1,552,242 | null | 1 | 25 | java|javafx-8|hdpi | 16,001 | <p><strong>Hi-DPI support on various devices</strong></p>
<p>For OS X Macs with retina display it should "just work" - JavaFX is aware of Hi-DPI Macs and will scale the UI appropriately. If you set the spacing in a VBox to 8, then that is a device independent unit; on a non-retina display mac it will take up 8 pixels, on a retina display which has double the resolution, the spacing will take up 16 pixels. Because the retina display also has twice the DPI as well as twice the resolution of the non-retina display, the physical screen measurement of the space will be the same regardless of device.</p>
<p>For Windows and Linux devices, your results may be less satisfactory as JavaFX 8u20 does not currently by default work out arbitrary DPI resolutions on such devices and scale to them appropriately. What you could do is perform most of your measurements in <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#typesize" rel="noreferrer">css as em units</a> (which are based on the point size of the scene's root's default font) and <a href="http://mail.openjdk.java.net/pipermail/openjfx-dev/2013-May/007738.html" rel="noreferrer">similarly for fxml</a>, and then set the point size of the scene root's default font appropriately depending on what you determine from querying the screen's DPI resolution. See the discussion in this answer for further information and sample code: <a href="https://stackoverflow.com/questions/23229149/javafx-automatic-resizing-and-button-padding">javafx automatic resizing and button padding</a>.</p>
<p><strong>Specific to Gnome</strong></p>
<p>Gnome 3 has a <a href="https://wiki.archlinux.org/index.php/HiDPI" rel="noreferrer">setting for the scaling factor</a> which can be controlled by this command:</p>
<pre><code>gsettings set org.gnome.desktop.interface scaling-factor 2
</code></pre>
<p>You can query this scaling factor by reading the user's gnome profile settings and use this in conjunction with querying the screen DPI to work out how an appropriate scaling factor then apply the scaling using the techniques described above.</p>
<p>Just a personal anecdote - when I tried using Gnome 3 scaling (CentOS 7 and also a recent Fedora release) on a Hi-DPI display a couple of days back, I found the overall support for Hi-DPI across applications running under Linux to be pretty spotty. Certainly, the support was much improved from CentOS 6 when I attempted that, but there was still quite a way to go to achieve quality Hi-DPI support across windowing toolkit, standard apps and third party apps. For this reason, I believe that running HiDPI Gnome desktops is still quite a bleeding edge thing which is definitely not for everyone - I am sure that this situation will change over time.</p>
<p><strong>Bitmapped Images</strong></p>
<p>From a JavaFX team lead <a href="http://fxexperience.com/2012/11/retina-display-macbook-pro/" rel="noreferrer">blog entry on Hi-DPI</a>:</p>
<blockquote>
<p>In Apple’s applications (starting with the iPhone and iPad with their retina displays), the solution to the problem is for the application developer to supply two images instead of one for each image asset. For example, the splash screen will be supplied with two images, one at normal resolution and one at 2x the resolution. The files are named the same but the 2x one is named according to some convention, such that at runtime the platform will lookup the 2x version on retina behind the scenes. In such a way, your application says “fooImage.png” but “[email protected]” is looked up instead when on a machine with a retina display.</p>
</blockquote>
<p>I do not know whether this bitmapped image choosing functionality for Hi-DPI displays is currently in Java 8u20 or not - you might have to implement it yourself by querying the screen with <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/stage/Screen.html#getDpi--" rel="noreferrer">screen.getDpi()</a>, then loading the appropriate bitmap.</p>
<p><strong>4K Devices</strong></p>
<p>4K is a lot of pixels to push. JavaFX will by default use hardware a accelerated graphics pipeline when such a graphics pipeline is available. Some graphics hardware may not be fully optimized for 4K display (e.g. not enough video ram), which might lead to an application which either does not work or performs poorly. I also don't believe that currently a lot of effort has gone into investigating JavaFX performance on various 4K devices - it might "just work", but it might not either. You will need to test your application on the target hardware to determine the current capabilities of JavaFX applications when running on that hardware. You might also need to tweak the application according to some of the suggestions above.</p>
<p>A user has reported an issue with JavaFX 8u20 when attempting to display a 4K video using JavaFX:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/26160709/javafx-ultra-hd-4k-video">JavaFX Ultra HD (4K) video</a></li>
</ul>
<p><strong>Background</strong></p>
<p>Supporting Hi-DPI under OS X was (likely) simpler than Windows/Linux devices as the target devices are either retina or non-retina display with one being an exact 2x scale of the other and direct support from the OS X system can be leveraged to help achieve the retina scaling. With Windows/Linux, probably what is required is an ability to scale at factors other than just 2x, and that is covered by the (currently outstanding and scheduled) feature request <a href="https://javafx-jira.kenai.com/browse/RT-32521" rel="noreferrer">RT-32521 Support global coordinate scaling with DPI-based default</a>. Scaling by an integral amount usually gives the best visible results.</p>
<p><strong>Additional Resources</strong></p>
<ul>
<li>Kynosarges discussion of <a href="http://news.kynosarges.org/2013/08/09/javafx-dpi-scaling/" rel="noreferrer">JavaFX DPI Scaling</a>. </li>
<li>The JavaFX team load wrote a <a href="http://fxexperience.com/2012/11/retina-display-macbook-pro/" rel="noreferrer">blog on JavaFX on retina Macs</a> (this is a little dated now, as JavaFX now supports retina Macs).</li>
<li>Randahl's perspective on <a href="http://blog.randahl.dk/2012/12/javafx-designing-for-multiple-screen.html" rel="noreferrer">JavaFX: Designing for Multiple Resolutions</a>.</li>
<li>Apple have some nice advice on <a href="https://developer.apple.com/high-resolution/" rel="noreferrer">optimizing applications</a> for high resolution devices, it's not JavaFX specific and some of the advice does not apply to JavaFX, but there are still some useful general principals and techniques there.</li>
</ul>
<p>A complete guide to coding for Hi-DPI devices is outside the scope of this particular answer - you can google various web resources to get more information.</p>
<p>If you have further questions on Hi-DPI support for JavaFX, I suggest you ask them on the <a href="http://mail.openjdk.java.net/mailman/listinfo/openjfx-dev" rel="noreferrer">openjfx-dev JavaFX developer mailing list</a>. </p>
<p><strong>Wiki Answer</strong></p>
<p>This answer may have some possible inconsistencies or errors and may date over time. I have made the answer community wiki. If you are aware of specific corrections, device and OS limitations or support model support for Hi-DPI on JavaFX, please feel free to edit this answer or move it to the <a href="https://wiki.openjdk.java.net/display/OpenJFX/Main" rel="noreferrer">OpenJFX wiki</a> (where it probably belongs anyway).</p> |
26,293,769 | How to parseInt in Angular.js | <p>Probably, it is the simplest thing but I couldn't parse a string to Int in angular..</p>
<p>What I am trying to do:</p>
<pre><code><input type="text" ng-model="num1">
<input type="text" ng-model="num2">
Total: {{num1 + num2}}
</code></pre>
<p>How can I sum these num1 and num2 values?</p>
<p>Thnx!</p> | 26,294,266 | 7 | 3 | null | 2014-10-10 07:08:43.377 UTC | 4 | 2019-01-24 09:36:46.707 UTC | null | null | null | null | 3,927,677 | null | 1 | 25 | angularjs | 156,312 | <p>You cannot (at least at the moment) use <code>parseInt</code> inside angular expressions, as they're not evaluated directly. Quoting <a href="https://docs.angularjs.org/guide/expression"><strong>the doc</strong></a>:</p>
<blockquote>
<p>Angular does not use JavaScript's <code>eval()</code> to evaluate expressions.
Instead Angular's <code>$parse</code> service processes these expressions.</p>
<p>Angular expressions do not have access to global variables like
<code>window</code>, <code>document</code> or <code>location</code>. This restriction is intentional. It
prevents accidental access to the global state – a common source of
subtle bugs.</p>
</blockquote>
<p>So you can define a <code>total()</code> method in your controller, then use it in the expression:</p>
<pre><code>// ... somewhere in controller
$scope.total = function() {
return parseInt($scope.num1) + parseInt($scope.num2)
}
// ... in HTML
Total: {{ total() }}
</code></pre>
<p>Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with <code>-0</code> op:</p>
<pre><code>Total: {{num1-0 + (num2-0)|number}}
</code></pre>
<p>... but that'll obviously won't <em>parseInt</em> values, only <em>cast</em> them to Numbers (<code>|number</code> filter prevents showing <code>null</code> if this cast results in <code>NaN</code>). So choose the approach that suits your particular case.</p> |
23,336,807 | When to use Rabin-Karp or KMP algorithms? | <p>I have generated an string using the following alphabet.
<code>{A,C,G,T}</code>. And my string contains more than 10000 characters. I'm searching the following patterns in it.</p>
<ul>
<li>ATGGA </li>
<li>TGGAC</li>
<li>CCGT</li>
</ul>
<p>I have asked to use a string matching algorithm which has <code>O(m+n)</code> running time. </p>
<pre><code>m = pattern length
n = text length
</code></pre>
<p>Both <code>KMP and Rabin-Karp algorithms</code> have this running time. What is the most suitable algorithm (between Rabin-Carp and KMP) in this situation?</p> | 23,341,452 | 1 | 5 | null | 2014-04-28 09:03:15.457 UTC | 11 | 2018-10-16 09:23:17.197 UTC | 2014-04-28 20:09:26.01 UTC | null | 1,711,796 | null | 2,131,211 | null | 1 | 37 | string|algorithm|matching|knuth-morris-pratt|rabin-karp | 20,457 | <p>When you want to search for multiple patterns, typically the correct choice is to use <a href="http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm" rel="noreferrer">Aho-Corasick</a>, which is somewhat a generalization of <a href="https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm" rel="noreferrer">KMP</a>. Now in your case you are only searching for 3 patterns so it may be the case that KMP is not that much slower(at most three times), but this is the general approach.</p>
<p><a href="https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm" rel="noreferrer">Rabin-Karp</a> is easier to implement if we assume that a collision will never happen, but if the problem you have is a typical string searching KMP will be more stable no matter what input you have. However, Rabin-Karp has many other applications, where KMP is not an option.</p> |
25,552,994 | JQuery Autocomplete from Database | <p>I need to to do autocomplete suggestion for my website and the data should be retrieved from database. I want to use JQuery autocomplete. here is my code but it doesn't work!
This is my php file with the name of gethint.php:</p>
<pre><code><?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$json[]=array(
'value'=> $row['fname'],
'label'=> $row['fname']
);
}
echo json_encode($json);
?>
</code></pre>
<p>and then this is my html file :</p>
<pre><code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#hint").autocomplete({
source:'gethint.php',
minLength:1
});
});
</script>
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" >
<input type="submit" name="submit" value="View">
</form>
</html>
</code></pre>
<p>It took a lot of time but I couldn't find the problem. I was wondering if someone could help me.
Thanks.</p> | 25,553,577 | 3 | 3 | null | 2014-08-28 15:49:40.963 UTC | 4 | 2018-10-05 16:32:16.7 UTC | 2014-08-28 15:55:25.327 UTC | null | 2,011,036 | null | 2,011,036 | null | 1 | 1 | javascript|php|jquery|jquery-ui|autocomplete | 62,181 | <p>I did some changes, maybe you need to fix something but take a look to see if helps...</p>
<p>The php:</p>
<pre><code><?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
array_push($json, $row['fname']);
}
echo json_encode($json);
?>
</code></pre>
<p>The html+jquery:</p>
<pre><code><html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" />
<input type="submit" name="submit" value="View">
</form>
<script type="text/javascript">
$(function() {
$( "#hint" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "gethint.php",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>
</body>
</html>
</code></pre> |
18,253,934 | Set maximum execution time in MYSQL / PHP | <p>I have an XML document that has around 48,000 children (~50MB). I run an INSERT MYSQL query that makes new entries for each one of these children. The problem is that it takes a lot of time due to its size. After it is executed I receive this</p>
<p><code>Fatal error: Maximum execution time of 60 seconds exceeded in /path/test.php on line 18</code></p>
<p>How do I set the Maximum execution time to be unlimited?</p>
<p>Thanks</p> | 18,254,099 | 5 | 1 | null | 2013-08-15 13:39:56.993 UTC | 4 | 2019-06-02 09:01:49.703 UTC | null | null | null | null | 2,519,389 | null | 1 | 11 | php|mysql|execution | 79,756 | <p>You can make it by setting set_time_limit in you php code (set to 0 for no limit)</p>
<pre><code>set_time_limit(0);
</code></pre>
<p>Or modifying the value of max_execution_time directly in your php.ini</p>
<pre><code>;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;
; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 120
</code></pre>
<p>Or changing it with ini_set() </p>
<pre><code>ini_set('max_execution_time', 120); //120 seconds
</code></pre>
<p>but note that for this 3rd option :</p>
<blockquote>
<p>max_execution_time </p>
<p>You can not change this setting with ini_set() when running in safe
mode. The only workaround is to turn off safe mode or by changing the
time limit in the php.ini.</p>
</blockquote>
<p>Source <a href="http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time" rel="noreferrer">www.php.net</a></p> |
18,499,605 | Windows Service Install Ends in Rollback | <p>When I try to install a Windows service:</p>
<p>c:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil </p>
<p>I get, what looks to be, some success messages and some failure messages. Part way down:</p>
<pre><code>An exception occurred during the Install phase.
System.ComponentModel.Win32Exception: The specified service has been marked for deletion
</code></pre>
<p>At the end:</p>
<pre><code>The Rollback phase completed successfully.
The transacted install has completed.
The installation failed, and the rollback has been performed.
</code></pre>
<p>The service is given an entry in the Services applet, but it is marked as "Disabled". When I attempt to change it to another state, I get a "marked for deletion" error message.</p>
<p>There are no messages in the Event Log. There is nothing useful in the log file created by installutil.exe (I believe it's written to the current working directory).</p>
<p>I have no direction to go with this. What do I do?</p> | 18,499,606 | 6 | 1 | null | 2013-08-28 22:53:06.823 UTC | 8 | 2019-04-25 09:07:00.963 UTC | null | null | null | null | 706,421 | null | 1 | 41 | windows-services | 45,464 | <p>It turns out that the install might, or probably will, fail if that service is highlighted in the Services applet. It's safest to just close the Services applet, install the service, and then re-open the Services applet. It's really stupid.</p>
<p>Also, make sure to run the console as admin.</p> |
14,943,439 | how to draw multigraph in networkx using matplotlib or graphviz | <p>when I pass multigraph numpy adjacency matrix to networkx (using from_numpy_matrix function)
and then try to draw the graph using matplotlib, it ignores the multiple edges.</p>
<p>how can I make it draw multiple edges as well ?</p> | 14,945,560 | 4 | 2 | null | 2013-02-18 18:58:00.453 UTC | 12 | 2022-06-08 09:47:23.557 UTC | null | null | null | null | 1,749,223 | null | 1 | 27 | python-2.7|networkx | 26,146 | <p>Graphviz does a good job drawing parallel edges. You can use that with NetworkX by writing a dot file and then processing with Graphviz (e.g. neato layout below). You'll need pydot or pygraphviz in addition to NetworkX</p>
<pre><code>In [1]: import networkx as nx
In [2]: G=nx.MultiGraph()
In [3]: G.add_edge(1,2)
In [4]: G.add_edge(1,2)
In [5]: nx.write_dot(G,'multi.dot')
In [6]: !neato -T png multi.dot > multi.png
</code></pre>
<p><img src="https://i.stack.imgur.com/AAZTf.png" alt="enter image description here"></p>
<p>On NetworkX 1.11 and newer, <code>nx.write_dot</code> doesn't work as per <a href="https://github.com/networkx/networkx/issues/1984" rel="noreferrer">issue on networkx github</a>. The workaround is to call <code>write_dot</code> using</p>
<p><code>from networkx.drawing.nx_pydot import write_dot</code></p>
<p>or</p>
<p><code>from networkx.drawing.nx_agraph import write_dot</code></p> |
15,231,798 | How do you install Rails 4.0 in an RVM gemset? | <p>I am trying to install Rails into a new rvm gemset.
I tried the following: </p>
<pre><code>rvm gemset create rails-4.0
output: gemset created rails-4.0
</code></pre>
<p>Next I did:</p>
<pre><code>rvm [email protected]
</code></pre>
<p>rvm gemset list:</p>
<pre><code>gemsets for ruby-2.0.0-p0 (found in /Users/me/.rvm/gems/ruby-2.0.0-p0)
(default)
global
=> rails-4.0
</code></pre>
<p>rails -v</p>
<blockquote>
<p>Rails is not currently installed on this system. To get the latest
version, simply type:</p>
<pre><code>$ sudo gem install rails
</code></pre>
</blockquote>
<p>Do the rvm commands I listed <strong>not</strong> install rails 4.0? </p> | 15,231,932 | 4 | 2 | null | 2013-03-05 18:53:27.34 UTC | 17 | 2015-11-20 07:44:47.077 UTC | 2015-04-13 20:30:21.353 UTC | null | 3,486,353 | null | 1,096,509 | null | 1 | 28 | ruby-on-rails|rvm | 36,272 | <p>This command:</p>
<pre><code>rvm gemset create rails-4.0
</code></pre>
<p>is creating basically a directory structure to hold the gems. You could have just as easily called it something other than "rails-4.0" like "foo" and it would be the same behavior.</p>
<p>This command:</p>
<pre><code>rvm [email protected]
</code></pre>
<p>Switches to Ruby 2.0.0 and tells it to use the new gemset named rails-4.0. Again, that could be "foo" or whatever you called it.</p>
<p>Now, to get Rails 4.0.x, you'd do:</p>
<pre><code>gem install rails --version=4.0
</code></pre>
<p>As Barrett pointed out earlier, to get a pre/beta/rc release, you can specify the whole version string, e.g. <code>gem install rails --version=4.0.0.rc2</code>.</p>
<p>Don't sudo, because you shouldn't sudo with rvm, even though it tells you to. With the "system ruby" (ruby not installed by rvm), it may be installed as root, so you need superuser (su) access (superuser do or "sudo") to do that. But, rvm has you install things as the current user, therefore you don't need to sudo.</p> |
15,132,174 | Always show map marker title in Android | <p>I'm adding default Marker to GoogleMap the following way:</p>
<pre><code>GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.editMapMap)).getMap();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(currentLocation.getCoordinate());
markerOptions.title(Utils.getLocationString(currentLocation.getCoordinate()));
markerOptions.snippet("Blah");
locationMarker = map.addMarker(markerOptions);
locationMarker.setDraggable(true);
</code></pre>
<p>How can I make marker always show title and snippet without touch? I also would like to disable hiding them on touch.</p> | 16,147,215 | 6 | 0 | null | 2013-02-28 09:42:43.627 UTC | 3 | 2020-05-28 14:36:48.92 UTC | null | null | null | null | 611,206 | null | 1 | 39 | java|android|google-maps | 56,140 | <p>It is very easy:</p>
<pre><code>locationMarker.showInfoWindow();
</code></pre> |
28,232,909 | How to selectively decorate RecyclerView items | <p>I am creating a subclass of <code>ItemDecoration</code> from this gist: <a href="https://gist.github.com/alexfu/0f464fc3742f134ccd1e">https://gist.github.com/alexfu/0f464fc3742f134ccd1e</a> </p>
<p>How to make it only decorate items with certain condition? For instance, only decorate items with certain positions, type of ViewHolder, etc.</p>
<p>I have modified the above mentioned gist (plus some changes on deprecated Android API) with this code, but <strong>all items</strong> get decorated anyway:</p>
<pre><code>public boolean isDecorated(View view, RecyclerView parent) {
RecyclerView.ViewHolder holder = parent.getChildViewHolder(view);
return holder instanceof MenuIconViewHolder || holder instanceof MenuDetailViewHolder;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (isDecorated(view, parent)) {
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
}
} else {
super.getItemOffsets(outRect, view, parent, state);
}
}
</code></pre>
<p>What's wrong with above code?
By the way, can it be considered best practice (in respect of separation of concerns) to place that kind of code in ItemDecoration class?</p> | 28,233,184 | 1 | 3 | null | 2015-01-30 09:33:58.5 UTC | 12 | 2015-01-30 09:50:37.493 UTC | null | null | null | null | 670,623 | null | 1 | 36 | android|android-ui|android-recyclerview | 11,353 | <p>You need to call isDecorated on the draw method as well, because at the moment you don't put the offset on those items but you still draw over it.</p>
<p>The method loops over all the child views currently in the RecyclerView visible on the screen.</p>
<pre><code>public void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft();
final int right = parent.getWidth() - parent.getPaddingRight();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if(isDecorated(child, parent))
{
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
public void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop();
final int bottom = parent.getHeight() - parent.getPaddingBottom();
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if(isDecorated(child, parent))
{
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
</code></pre> |
48,225,673 | Why is std::is_pod deprecated in C++20? | <p><code>std::is_pod</code> will be probably deprecated in C++20.<br>
What's the reason for this choice? What should I use in place of <code>std::is_pod</code> to know if a type is actually a POD?</p> | 48,225,882 | 1 | 6 | null | 2018-01-12 11:46:47.113 UTC | 16 | 2022-08-23 22:27:04.387 UTC | 2018-01-12 11:56:49.537 UTC | null | 4,987,285 | null | 4,987,285 | null | 1 | 112 | c++|typetraits | 15,693 | <p>POD is being replaced with two categories that give more nuances. The <a href="https://botondballo.wordpress.com/2017/11/20/trip-report-c-standards-meeting-in-albuquerque-november-2017/" rel="noreferrer">c++ standard meeting in november 2017</a> had this to say about it:</p>
<blockquote>
<p>Deprecating the notion of “plain old data” (POD). It has been replaced with two more nuanced categories of types, “trivial” and “standard-layout”. “POD” is equivalent to “trivial and standard layout”, but for many code patterns, a narrower restriction to just “trivial” or just “standard layout” is appropriate; to encourage such precision, the notion of “POD” was therefore deprecated. The library trait is_pod has also been deprecated correspondingly.</p>
</blockquote>
<p>For simple data types use the <a href="http://en.cppreference.com/w/cpp/types/is_standard_layout" rel="noreferrer"><code>is_standard_layout</code></a> function, for trivial data types (such as simple structs) use the <a href="http://en.cppreference.com/w/cpp/types/is_trivial" rel="noreferrer"><code>is_trivial</code></a> function.</p> |
23,824,570 | Project Euler #8, I don't understand where I'm going wrong | <p>I'm working on project <a href="https://projecteuler.net/problem=8" rel="nofollow noreferrer">euler problem number eight</a>, in which ive been supplied this ridiculously large number: </p>
<p><code>7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450</code></p>
<p>and am supposed to "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product." EG the product of the first four adjacent digits is 7 * 3 * 1 * 6.
My code is the following: </p>
<pre><code>int main()
{
string num = /* ridiculously large number omitted */;
int greatestProduct = 0;
int product;
for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
}
cout << greatestProduct << endl;
}
</code></pre>
<p>I keep getting 2091059712 as the answer which project euler informs me is wrong and I suspect its too large anyway. Any help would be appreciated.</p>
<p>EDIT: changed to unsigned long int and it worked. Thanks everyone!</p> | 23,824,843 | 21 | 6 | null | 2014-05-23 08:38:17.07 UTC | 2 | 2021-02-17 11:03:39.58 UTC | 2020-05-05 09:51:53.593 UTC | null | 12,357,799 | null | 3,647,111 | null | 1 | 30 | c++ | 43,685 | <p>In fact your solution is too small rather than too big. The answer is what was pointed out in the comments, that there is integer overflow, and the clue is in the fact that your solution is close to the largest possible value for an signed int: 2147483647. You need to use a different type to store the product.</p>
<p>Note that the answer below is still 'correct' in that your code does do this wrong, but it's not what is causing the wrong value. Try taking your (working) code to <a href="http://codereview.stackexchange.com">http://codereview.stackexchange.com</a> if you would like the folks there to tell you what you could improve in your approach and your coding style.</p>
<h2>Previous answer</h2>
<p>You are checking for a new greatest product inside the inner loop instead of outside. This means that your maximum includes all strings of less or equal ton 13 digits, rather than only exactly 13.</p>
<p>This could make a difference if you are finding a string which has fewer than 13 digits which have a large product, but a 0 at either end. You shouldn't count this as the largest, but your code does. (I haven't checked if this does actually happen.)</p>
<pre><code>for (int i=0; i < num.length() -12; i++)
{
product = ((int) num[i] - 48);
for (int j=i+1; j<i+13; j++)
{
product = product * ((int) num[j] - 48);
}
if (greatestProduct <= product)
{
greatestProduct = product;
}
}
</code></pre> |
19,567,060 | Fast compare method of 2 columns | <p><strong>EDIT:</strong> Instead for my solution, use something like</p>
<pre><code> For i = 1 To tmpRngSrcMax
If rngSrc(i) <> rngDes(i) Then ...
Next i
</code></pre>
<p>It is about 100 times faster.</p>
<p>I have to compare two columns containing string data using VBA. This is my approach:</p>
<pre><code>Set rngDes = wsDes.Range("A2:A" & wsDes.Cells(Rows.Count, 1).End(xlUp).Row)
Set rngSrc = wsSrc.Range("I3:I" & wsSrc.Cells(Rows.Count, 1).End(xlUp).Row)
tmpRngSrcMax = wsSrc.Cells(Rows.Count, 1).End(xlUp).Row
cntNewItems = 0
For Each x In rngSrc
tmpFound = Application.WorksheetFunction.CountIf(rngDes, x.Row)
Application.StatusBar = "Processed: " & x.Row & " of " & tmpRngSrcMax & " / " & Format(x.Row / tmpRngSrcMax, "Percent")
DoEvents ' keeps Excel away from the "Not responding" state
If tmpFound = 0 Then ' new item
cntNewItems = cntNewItems + 1
tmpLastRow = wsDes.Cells(Rows.Count, 1).End(xlUp).Row + 1 ' first empty row on target sheet
wsDes.Cells(tmpLastRow, 1) = wsSrc.Cells(x.Row, 9)
End If
Next x
</code></pre>
<p>So, I'm using a For Each loop to iterate trough the 1st (src) column, and the CountIf method to check if the item is already present in the 2nd (des) column. If not, copy to the end of the 1st (src) column. </p>
<p>The code works, but on my machine it takes ~200s given columns with around 7000 rows. I noticed that CountIf works way faster when used directly as a formula.</p>
<p>Does anyone has ideas for code optimization?</p> | 19,570,501 | 7 | 8 | null | 2013-10-24 13:16:46.66 UTC | 11 | 2015-12-14 12:32:12.167 UTC | 2015-07-03 01:55:23 UTC | null | 4,539,709 | null | 1,364,397 | null | 1 | 13 | vba|excel | 57,587 | <p>Ok. Let's clarify a few things. </p>
<p>So column <code>A</code> has <code>10,000</code> randomly generated values , column <code>I</code> has <code>5000</code> randomly generated values. It looks like this</p>
<p><img src="https://i.stack.imgur.com/PPxP6.png" alt="enter image description here"></p>
<p>I have run 3 different codes against 10,000 cells.</p>
<p><strong>the <code>for i = 1 to ... for j = 1 to ...</code></strong> approach, the one you are suggesting</p>
<pre><code>Sub ForLoop()
Application.ScreenUpdating = False
Dim stNow As Date
stNow = Now
Dim lastA As Long
lastA = Range("A" & Rows.Count).End(xlUp).Row
Dim lastB As Long
lastB = Range("I" & Rows.Count).End(xlUp).Row
Dim match As Boolean
Dim i As Long, j As Long
Dim r1 As Range, r2 As Range
For i = 2 To lastA
Set r1 = Range("A" & i)
match = False
For j = 3 To lastB
Set r2 = Range("I" & j)
If r1 = r2 Then
match = True
End If
Next j
If Not match Then
Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = r1
End If
Next i
Debug.Print DateDiff("s", stNow, Now)
Application.ScreenUpdating = True
End Sub
</code></pre>
<p><strong>Sid's appraoch</strong></p>
<pre><code>Sub Sample()
Dim wsDes As Worksheet, wsSrc As Worksheet
Dim rngDes As Range, rngSrc As Range
Dim DesLRow As Long, SrcLRow As Long
Dim i As Long, j As Long, n As Long
Dim DesArray, SrcArray, TempAr() As String
Dim boolFound As Boolean
Set wsDes = ThisWorkbook.Sheets("Sheet1")
Set wsSrc = ThisWorkbook.Sheets("Sheet2")
DesLRow = wsDes.Cells(Rows.Count, 1).End(xlUp).Row
SrcLRow = wsSrc.Cells(Rows.Count, 1).End(xlUp).Row
Set rngDes = wsDes.Range("A2:A" & DesLRow)
Set rngSrc = wsSrc.Range("I3:I" & SrcLRow)
DesArray = rngDes.Value
SrcArray = rngSrc.Value
For i = LBound(SrcArray) To UBound(SrcArray)
For j = LBound(DesArray) To UBound(DesArray)
If SrcArray(i, 1) = DesArray(j, 1) Then
boolFound = True
Exit For
End If
Next j
If boolFound = False Then
ReDim Preserve TempAr(n)
TempAr(n) = SrcArray(i, 1)
n = n + 1
Else
boolFound = False
End If
Next i
wsDes.Cells(DesLRow + 1, 1).Resize(UBound(TempAr) + 1, 1).Value = _
Application.Transpose(TempAr)
End Sub
</code></pre>
<p><strong>my (mehow) approach</strong></p>
<pre><code>Sub Main()
Application.ScreenUpdating = False
Dim stNow As Date
stNow = Now
Dim arr As Variant
arr = Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row).Value
Dim varr As Variant
varr = Range("I3:I" & Range("I" & Rows.Count).End(xlUp).Row).Value
Dim x, y, match As Boolean
For Each x In arr
match = False
For Each y In varr
If x = y Then match = True
Next y
If Not match Then
Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = x
End If
Next
Debug.Print DateDiff("s", stNow, Now)
Application.ScreenUpdating = True
End Sub
</code></pre>
<hr>
<p>the results as follows</p>
<p><img src="https://i.stack.imgur.com/uzYzX.png" alt="enter image description here"></p>
<p>now, you select the <strong>fast compare method</strong> :)</p>
<hr>
<p>filling in of the random values</p>
<pre><code>Sub FillRandom()
Cells.ClearContents
Range("A1") = "Column A"
Range("I2") = "Column I"
Dim i As Long
For i = 2 To 10002
Range("A" & i) = Int((10002 - 2 + 1) * Rnd + 2)
If i < 5000 Then
Range("I" & Range("I" & Rows.Count).End(xlUp).Row + 1) = _
Int((10002 - 2 + 1) * Rnd + 2)
End If
Next i
End Sub
</code></pre> |
19,747,536 | multiple independent R sessions in Mac OS X | <p>I need to run multiple R sessions, and hope that they can be performed in different R sessions. In Windows, I am able to open an arbitrary number of R sessions, and run different codes in each session (both RGui and RStudio). However, in Mac OSX, neither R.app nor RStudio would allow me to open multiple independent sessions -- I have to wait until the first set of R codes are completed in order to run a second set of R codes.</p>
<p>Is there any solution in Mac OSX? This issues had bothered me long ago, so I'd like to hear your suggestions. Thanks!</p> | 19,754,933 | 4 | 9 | null | 2013-11-02 22:20:08.193 UTC | 16 | 2020-06-17 13:22:21.64 UTC | null | null | null | null | 1,510,531 | null | 1 | 26 | r|rstudio | 28,898 | <p>Thank you for all the suggestions. Here is a brief summary of the possible solutions:</p>
<ol>
<li>Using Terminal: Run: <code>open -n /Applications/RStudio.app</code> in Terminal</li>
<li>Install Emacs and ESS which permit multiple sessions</li>
<li>Duplicate the entire R.app package by option-dragging (and you can rename the copies)</li>
<li>Run multiple rstudio sessions using projects</li>
</ol> |
8,653,036 | Check if a specific tab page is selected (active) | <p>I am making an event to check if specific tab page in a tab control is active.</p>
<p>The point is, it will trigger an event if that tab page in a tab control is the currently selected tab. Any code that will give me what I need?</p> | 8,653,093 | 6 | 3 | null | 2011-12-28 07:21:10.33 UTC | 8 | 2019-11-18 19:13:42.017 UTC | 2013-08-26 06:39:25.067 UTC | null | 661,933 | null | 1,118,861 | null | 1 | 67 | c#|winforms|tabcontrol|tabpage | 144,315 | <p>Assuming you are looking out in Winform, there is a <code>SelectedIndexChanged</code> event for the tab</p>
<p>Now in it you could check for your specific tab and proceed with the logic </p>
<pre><code>private void tab1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tab1.SelectedTab == tab1.TabPages["tabname"])//your specific tabname
{
// your stuff
}
}
</code></pre> |
5,218,713 | One liner to convert from list<T> to vector<T> | <p>Is there an one-liner that converts a <code>list<T></code> to <code>vector<T></code>?</p>
<p>A google search returns me a lot of results that use manual, lengthy conversion, which make me puke. Should we go to that much trouble to do something as simple as a list-to-vector conversion?</p> | 5,218,738 | 5 | 2 | null | 2011-03-07 10:48:10.887 UTC | 18 | 2021-12-08 04:02:43.547 UTC | 2020-07-02 11:31:27.907 UTC | null | 3,834 | null | 3,834 | null | 1 | 67 | c++|stl | 45,427 | <p>You can only create a new vector with all the elements from the list:</p>
<pre><code>std::vector<T> v{ std::begin(l), std::end(l) };
</code></pre>
<p>where <code>l</code> is a <code>std::list<T></code>. This will copy all elements from the list to the vector.</p>
<p>Since C++11 this can be made more efficient if you don't need the original list anymore. Instead of copying, you can move all elements into the vector:</p>
<pre><code>std::vector<T> v{ std::make_move_iterator(std::begin(l)),
std::make_move_iterator(std::end(l)) };
</code></pre> |
5,019,834 | Android Admob advert in PreferenceActivity | <p>Is there a way to add an admob advert to a PreferenceActivity? How to?</p> | 5,850,299 | 7 | 0 | null | 2011-02-16 17:27:42.26 UTC | 13 | 2020-01-10 07:15:05.68 UTC | null | null | null | null | 472,537 | null | 1 | 25 | android|admob | 9,252 | <p>What you can also do is to create a custom Preference that can be easily added to any preferences screen.</p>
<p>Add a layout file called ad_layout.xml to your res/layout folder that will be filled later by AdMob.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">
</LinearLayout>
</code></pre>
<p>Create a class called AdPreference like that:</p>
<pre><code>package com.example.adpreference;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import android.app.Activity;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class AdPreference extends Preference {
public AdPreference(Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle);}
public AdPreference(Context context, AttributeSet attrs) {super(context, attrs);}
public AdPreference(Context context) {super(context);}
@Override
protected View onCreateView(ViewGroup parent) {
// this will create the linear layout defined in ads_layout.xml
View view = super.onCreateView(parent);
// the context is a PreferenceActivity
Activity activity = (Activity)getContext();
// Create the adView
AdView adView = new AdView(activity, AdSize.BANNER, "<your add id>");
((LinearLayout)view).addView(adView);
// Initiate a generic request to load it with an ad
AdRequest request = new AdRequest();
adView.loadAd(request);
return view;
}
}
</code></pre>
<p>Now in the preference xml file you can just add add any position you like (at the top or in between any other preferences ).</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
...
<com.example.adpreference.AdPreference android:layout="@layout/ad_layout"/>
...
</PreferenceScreen>
</code></pre> |
5,100,189 | Use PHP to check if page was accessed with SSL | <p>Is there a way to check if the current page was opened with SSL? For example, I want my login page (login.php) to check if it was accessed using SSL (https://mywebserver.com/login.php). If not, redirect them to the SSL version of the page.</p>
<p>Pretty much, I want to enfore that the user uses the page securely.</p> | 5,100,206 | 9 | 2 | null | 2011-02-24 03:55:56.59 UTC | 6 | 2021-01-20 04:52:14.977 UTC | null | null | null | null | 618,551 | null | 1 | 37 | php|ssl | 62,701 | <p>You should be able to check that <code>$_SERVER['HTTPS']</code> is set, e.g.:</p>
<pre><code>if (empty($_SERVER['HTTPS'])) {
header('Location: https://mywebserver.com/login.php');
exit;
}
</code></pre> |
4,993,097 | html5 display audio currentTime | <p>I would like to display the current time of of an html 5 audio element and the duration of that element. I've been looking over the internet but can't find a functional script which allows me to display how long the audio files is and what the time currently is e.g. 1:35 / 3:20.</p>
<p>Any one got any ideas :)?</p> | 4,993,619 | 11 | 3 | null | 2011-02-14 14:08:39.41 UTC | 20 | 2022-01-06 02:41:21.207 UTC | null | null | null | null | 616,176 | null | 1 | 38 | javascript|html|audio|duration|html5-audio | 80,676 | <p>Here's an example:</p>
<pre><code><audio id="track" src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg"
ontimeupdate="document.getElementById('tracktime').innerHTML = Math.floor(this.currentTime) + ' / ' + Math.floor(this.duration);">
<p>Your browser does not support the audio element</p>
</audio>
<span id="tracktime">0 / 0</span>
<button onclick="document.getElementById('track').play();">Play</button>
</code></pre>
<p>This should work in Firefox and Chrome, for other browsers you'll probably need to add alternative encodings.</p> |
5,509,872 | Python append multiple files in given order to one big file | <p>I have up to 8 seperate Python processes creating temp files in a shared folder. Then I'd like the controlling process to append all the temp files in a certain order into one big file. What's the quickest way of doing this at an os agnostic shell level?</p> | 5,509,894 | 12 | 6 | null | 2011-04-01 06:26:13.7 UTC | 8 | 2022-03-19 20:11:03.247 UTC | null | null | null | null | 72,668 | null | 1 | 22 | python|file|append | 68,738 | <p>Just using simple file IO:</p>
<pre><code># tempfiles is a list of file handles to your temp files. Order them however you like
f = open("bigfile.txt", "w")
for tempfile in tempfiles:
f.write(tempfile.read())
</code></pre>
<p>That's about as OS agnostic as it gets. It's also fairly simple, and the performance ought to be about as good as using anything else.</p> |
16,743,782 | How to get the largest and smallest of 3 values with fewest comparisons? | <p>This is a simple introduction course question. I have to write a program that asks the user to input 3 numbers, and determines the largest and smallest number.</p>
<p>I need to only use <code>if</code> statements.</p>
<p>This is what I tried so far: which required 4 comparisons.</p>
<pre><code>int x, y, z;
int smallest, largest;
cout << "Please enter 3 numbers to compare: " ;
cin >> x >> y >> z;
smallest = x;
largest = x;
if (y > largest)
largest = y;
if (z > largest)
largest = z;
if (y < smallest)
smallest = y;
if (z < smallest)
smallest = z;
cout << "largest: " << largest << ", and smallest: " << smallest << endl;
</code></pre>
<p>My question is: Is it possible to only use 3 comparisons, or less? I think when <code>y > largest</code>, it also tells us something else as well?</p> | 16,743,845 | 7 | 3 | null | 2013-05-24 21:17:36.877 UTC | 1 | 2020-11-05 04:29:04.653 UTC | 2020-11-05 04:29:04.653 UTC | null | 8,372,853 | null | 1,276,534 | null | 1 | 5 | c++|if-statement | 45,858 | <p>The issue with your code is that you toss out a lot of information. In "challenges" such as these, you have to make the most of what you have. So when you say, for example </p>
<pre><code>if (y > largest)
</code></pre>
<p>don't just treat the <code>true</code> case. Also try to reason about the case when the condition doesn't hold. </p>
<pre><code>if ( x < y )
{
smallest = x;
biggest = y;
}
else
{
smallest = y;
biggest = x;
}
if ( z < smallest )
smallest = z;
else if ( z > biggest )
biggest = z;
</code></pre>
<p>This contains only 3 comparisons.</p> |
41,557,760 | CodeIgniter HMVC object_to_array() error | <p>HMVC : <a href="https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/downloads" rel="noreferrer">https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/downloads</a></p>
<p>After downloading CI and copying over the HMVC, I'm getting the following error:</p>
<blockquote>
<p>An uncaught Exception was encountered</p>
<p>Type: Error</p>
<p>Message: Call to undefined method MY_Loader::_ci_object_to_array()</p>
<p>Filename:
/Users/k1ut2/Sites/nine.dev/application/third_party/MX/Loader.php</p>
<p>Line Number: 300</p>
<p>Backtrace:</p>
<p>File: /Users/k1ut2/Sites/nine.dev/application/controllers/Welcome.php
Line: 23 Function: view</p>
<p>File: /Users/k1ut2/Sites/nine.dev/index.php Line: 315 Function:
require_once</p>
</blockquote> | 41,786,939 | 5 | 5 | null | 2017-01-09 22:04:53.903 UTC | 15 | 2018-06-18 07:04:30.707 UTC | 2018-06-18 07:04:30.707 UTC | null | 6,529,212 | null | 689,195 | null | 1 | 32 | php|codeigniter|hmvc-codeigniter | 37,230 | <p>Just adding this here as the Link provided by Clasyk isn't currently working...</p>
<p>The short version from that thread boils down to this...</p>
<p>In application/third_party/MX/Loader.php you can do the following...</p>
<p>Under <code>public function view($view, $vars = array(), $return = FALSE)</code> Look for... (Line 300)</p>
<pre><code>return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
</code></pre>
<p>Replace this with</p>
<pre><code>if (method_exists($this, '_ci_object_to_array'))
{
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
} else {
return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return));
}
</code></pre>
<p>It's the result of a "little" undocumented change that the CI Devs implemented, which is fine!</p>
<p>There is a pull request on Wiredesignz awaiting action so he knows about it... </p>
<p>In the meantime, you can implement the above "diddle" and get back to coding :)</p> |
12,140,947 | Using bcp utility to export SQL queries to a text file | <p>I debug a stored procedure (SQL Server 2005) and I need to find out some values in a datatable.</p>
<p>The procedure is run by an event of the application and I watch just the debugging output.</p>
<p>I do the following my stored procedure (SQL Server 2005), I took a system table (master.dbo.spt_values) as example:</p>
<pre><code>set @logtext = 'select name, type from master.dbo.spt_values where number=6'
--set @logtext = 'master.dbo.spt_values'
SET @cmd = 'bcp ' + @logtext + ' out "c:\spt_values.dat" -U uId -P uPass -c'
EXEC master..XP_CMDSHELL @cmd
</code></pre>
<p>So, when I uncomment the second like everything works, a file apprears on the C:\ drive... but if I coment it back leaving only the first line, any output is generated. </p>
<p>How to fix this problem?</p> | 12,140,979 | 1 | 0 | null | 2012-08-27 11:18:13.247 UTC | 4 | 2013-01-27 08:54:00.563 UTC | null | null | null | null | 185,593 | null | 1 | 8 | sql|sql-server|debugging|sql-server-2005|bcp | 70,132 | <p><code>bcp out</code> exports tables.</p>
<p>To export a query use <code>queryout</code> instead - you'll need to wrap your query in "double quotes"</p>
<pre><code>set @logtext = '"select name, type from master.dbo.spt_values where number=6"'
--set @logtext = 'master.dbo.spt_values'
SET @cmd = 'bcp ' + @logtext + ' queryout "c:\spt_values.dat" -U uId -P uPass -c'
EXEC master..XP_CMDSHELL @cmd
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms162802.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms162802.aspx</a></p> |
12,370,326 | Decompile an APK, modify it and then recompile it | <p>I need to modify an existing APK, modify the sources and then recompile it.</p>
<ul>
<li>I can decompile it using dex2jar or apktool, it's working great </li>
<li>From the jar file I can obtain the java sources (using jd-gui)</li>
<li>Then I can modify the java files</li>
</ul>
<p>But now I would like to know how to recompile the java files and put them back into a jar file! (the jar part should be easy, the main problem seems to be how to recompile the java files for android)</p>
<p>I know that an other solution is to use apktool and then modify the smali files, but it seems to be really complicated when we want to add a lot of code!</p>
<p>My application is a basic a HelloWorld whitout obfuscation.</p> | 12,370,973 | 8 | 1 | null | 2012-09-11 13:01:04.53 UTC | 59 | 2021-01-04 09:54:05.237 UTC | null | null | null | null | 1,280,608 | null | 1 | 84 | java|android|decompiling|recompile | 199,814 | <p>Thanks to Chris Jester-Young I managed to make it work!</p>
<p>I think the way I managed to do it will work only on really simple projects:</p>
<ul>
<li>With Dex2jar I obtained the Jar.</li>
<li>With jd-gui I convert my Jar back to Java files.</li>
<li><p>With apktool i got the android manifest and the resources files.</p></li>
<li><p>In Eclipse I create a new project with the same settings as the old one (checking all the information in the manifest file)</p></li>
<li>When the project is created I'm replacing all the resources and the manifest with the ones I obtained with apktool</li>
<li>I paste the java files I extracted from the Jar in the src folder (respecting the packages)</li>
<li>I modify those files with what I need</li>
<li>Everything is compiling! </li>
</ul>
<p>/!\ be sure you removed the old apk from the device an error will be thrown stating that the apk signature is not the same as the old one!</p> |
18,910,134 | GROUP BY but get all values from other column | <p>I''ll explain what I need to do on example. First of all, we have a simple table like this one, named <em>table</em>:</p>
<pre><code>id | name
===+=====
1 | foo
1 | bar
1 | foobar
2 | foo
2 | bar
2 | foobar
</code></pre>
<p>Now the query:</p>
<pre><code>SELECT t.* FROM table t GROUP BY t.id
</code></pre>
<p>Will get us result similar to this one:</p>
<pre><code>id | name
===+=====
1 | foo
2 | foo
</code></pre>
<p>But is it possible, to collect all values of <em>name</em> to have result like this?</p>
<pre><code>id | name
===+=================
1 | foo, bar, foobar
2 | foo, bar, foobar
</code></pre> | 18,910,206 | 4 | 5 | null | 2013-09-20 06:22:19.97 UTC | 15 | 2021-03-03 18:48:55.853 UTC | null | null | null | null | 1,648,759 | null | 1 | 55 | sql|group-by | 64,668 | <p>Using MySQL you can use <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="noreferrer">GROUP_CONCAT(expr) </a></p>
<blockquote>
<p>This function returns a string result with the concatenated non-NULL
values from a group. It returns NULL if there are no non-NULL values.
The full syntax is as follows:</p>
</blockquote>
<pre><code>GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
</code></pre>
<p>Something like</p>
<pre><code>SELECT ID, GROUP_CONCAT(name) GroupedName
FROM Table1
GROUP BY ID
</code></pre>
<h2><a href="http://www.sqlfiddle.com/#!2/afbca/2" rel="noreferrer">SQL Fiddle DEMO</a></h2> |
3,714,143 | How to align items in a <h:panelGrid> to the right | <p>How would I align everything in my below to the far right?</p>
<pre><code><div id="container">
<h:form id="authenticate">
<h:panelGrid columns="5" cellpadding="6">
<h:inputText id="email" value="" />
<p:watermark for="email" value="Email"/>
<h:inputSecret id="password" value="" />
<p:watermark for="password" value="Password"/>
<p:commandButton id="login" value="Login" align="right"/>
</h:panelGrid>
</h:form>
</div>
</code></pre> | 3,714,168 | 3 | 0 | null | 2010-09-15 01:50:17.913 UTC | 4 | 2020-05-13 20:05:28.11 UTC | null | null | null | null | 376,434 | null | 1 | 12 | css|jsf | 80,001 | <p>The <a href="http://download.oracle.com/docs/cd/E17802_01/j2ee/javaee/javaserverfaces/1.2_MR1/docs/tlddocs/h/panelGrid.html" rel="noreferrer"><code><h:panelGrid></code></a> renders a HTML table. You basically want to apply <code>text-align: right;</code> on every <code><td></code> element it renders. With the current code, easiest would be to apply the following:</p>
<pre><code>#authenticate table td {
text-align: right;
}
</code></pre>
<hr>
<p>You can of course also be more specific, e.g. giving the <code><h:panelGrid></code> its own <code>styleClass</code> and defining a rule in CSS (which would be applied directly on the rendered HTML <code><table></code> element).</p>
<pre><code><h:panelGrid styleClass="className">
</code></pre>
<p>with</p>
<pre><code>.className td {
text-align: right;
}
</code></pre>
<hr>
<p>You can also give each <code><td></code> element its own class by <code>columnClasses</code> attribute which accepts a commaseparated string of CSS classnames which are to be applied repeatedly on the <code><td></code> elements. If you want to apply the same class on every <code><td></code> element, just specify it once:</p>
<pre><code><h:panelGrid columnClasses="className">
</code></pre>
<p>with</p>
<pre><code>.className {
text-align: right;
}
</code></pre>
<hr>
<p>As an extra hint: rightclick the webpage in webbrowser and choose <em>View Source</em>, then you'll understand better what JSF is all exactly generating.</p> |
3,806,788 | Trie data structures - Java | <p>Is there any library or documentation/link which gives more information of implementing Trie data structure in java?</p>
<p>Any help would be great!</p>
<p>Thanks.</p> | 3,806,819 | 3 | 0 | null | 2010-09-27 18:44:22.807 UTC | 8 | 2015-12-10 20:32:45.917 UTC | null | null | null | null | 368,892 | null | 1 | 33 | java|data-structures|trie | 56,486 | <p>You could read up on <a href="https://community.oracle.com/thread/2070706" rel="noreferrer">Java Trie</a> or look at <a href="https://github.com/brianfromoregon/trie" rel="noreferrer">trie</a>.</p> |
3,325,247 | XML validation with XSD: how to avoid caring about the sequence of the elements? | <p>I have following XSD code:</p>
<pre><code><xsd:complexType name="questions">
<xsd:sequence>
<xsd:element name="location" type="location"/>
<xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="pictureInput" type="pictureInput" minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</code></pre>
<p>The problem here is: the elements location, multipleChoiceInput, etc. must appear in the same order they are declared. I don't want this to happen, I want that, in the validation process the sequence should not be relevant. How can I achieve this?</p>
<p>Another possibility I've tried has been:</p>
<pre><code><xsd:complexType name="questions">
<xsd:choice maxOccurs="unbounded">
<xsd:element name="location" type="location"/>
<xsd:element name="multipleChoiceInput" type="multipleChoiceInput" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="textInput" type="textInput" minOccurs="0" maxOccurs="unbounded"/>
<xsd:element name="pictureInput" type="pictureInput" minOccurs="0" maxOccurs="1"/>
</xsd:choice>
</xsd:complexType>
</code></pre>
<p>In this example, the sequence really does not matter anymore, and I can have so much elements as I want (what "all" would not allow me to do). But I still have the Problem with the min- and maxOccurs. In this example, I could have so many "pictureInput"s as possible, what is againt the constraint that I would like to have either 0 or 1.</p>
<p>Thanks a lot for helping!</p> | 3,325,406 | 3 | 0 | null | 2010-07-24 13:23:40.843 UTC | 11 | 2018-08-23 14:44:05.213 UTC | 2010-07-24 15:18:47.237 UTC | null | 401,056 | null | 401,056 | null | 1 | 43 | xml|xsd|xml-validation | 40,715 | <pre><code><xsd:complexType name="questions">
<xsd:all>
<xsd:element name="location" type="location"/>
<xsd:element name="multipleChoiceInput" type="multipleChoiceInput"/>
<xsd:element name="textInput" type="textInput"/>
<xsd:element name="pictureInput" type="pictureInput"/>
</xsd:all>
</xsd:complexType>
</code></pre>
<p>NOTE: I have changed "sequence" to "all"</p>
<p>Sequence forces order (as defined). if order doesn't matter then all is used.</p>
<p>If there are chances of element occurence more than once then xsd:any can be used.</p>
<pre><code><xsd:complexType name="questions">
<xsd:sequence>
<xsd:any minOccurs="0"/>
</xsd:sequence>
</xsd:complexType>
</code></pre>
<p>You can find details of xsd:any at following link:</p>
<p><a href="https://www.w3schools.com/xml/schema_complex_any.asp" rel="noreferrer">https://www.w3schools.com/xml/schema_complex_any.asp</a></p> |
24,254,189 | Make sure that the controller has a parameterless public constructor error | <p>I have followed this <a href="http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver">tutorial</a> which has worked great, until I modified my <code>DbContext</code> to have an additional constructor. I am now having issues with the resolution and not sure what to do to fix this. Is there an easy way to force it to grab the parameterless constructor or I am approaching this incorrectly? </p>
<p><code>DbContext</code> with two constructors:</p>
<pre><code>public class DashboardDbContext : DbContext
{
public DashboardDbContext() : base("DefaultConnection") { }
public DashboardDbContext(DbConnection dbConnection, bool owns)
: base(dbConnection, owns) { }
}
</code></pre>
<p><code>SiteController</code> constructor:</p>
<pre><code>private readonly IDashboardRepository _repo;
public SiteController(IDashboardRepository repo)
{
_repo = repo;
}
</code></pre>
<p>Repository:</p>
<pre><code>DashboardDbContext _context;
public DashboardRepository(DashboardDbContext context)
{
_context = context;
}
</code></pre>
<p><code>UnityResolver</code> code:</p>
<pre><code>public class UnityResolver : IDependencyResolver
{
private readonly IUnityContainer _container;
public UnityResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
try
{
return _container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return _container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = _container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
_container.Dispose();
}
}
</code></pre>
<p>WebApiConfig:</p>
<pre><code>var container = new UnityContainer();
container.RegisterType<IDashboardRepository, DashboardRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
</code></pre>
<p>Error from WebApi Call:</p>
<blockquote>
<p>System.InvalidOperationException: An error occurred when trying to create a controller of type 'SiteController'. Make sure that the controller has a parameterless public constructor.</p>
</blockquote>
<pre><code>at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()
</code></pre>
<blockquote>
<p>InnerException: System.ArgumentException: Type 'Dashboard.Web.Controllers.SiteController' does not have a default constructor.</p>
</blockquote>
<pre><code>at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</code></pre>
<p>The tutorial was great and has been working well for me up until I added the second constructor.</p> | 24,257,085 | 11 | 13 | null | 2014-06-17 00:41:21.913 UTC | 24 | 2022-04-25 07:59:13.02 UTC | 2016-03-13 10:21:04.34 UTC | null | 264,697 | null | 192,204 | null | 1 | 121 | c#|asp.net-mvc|asp.net-web-api|unity-container | 238,280 | <p>What's happening is that you're bitten by <a href="https://stackoverflow.com/questions/15908019/simple-injector-unable-to-inject-dependencies-in-web-api-controllers">this problem</a>. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the <code>IDependencyResolver</code> contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.</p>
<p>You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.</p>
<p>But of course, the configuration error comes from you adding the second constructor to your <code>DbContext</code>. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.</p>
<p>So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the <code>DbContext</code>. <code>DbContext</code> is a special type that shouldn't be auto-wired. It is a framework type and you should <a href="https://cuttingedge.it/blogs/steven/pivot/entry.php?id=97#Framework-types">therefore fallback to registering it using a factory delegate</a>:</p>
<pre><code>container.Register<DashboardDbContext>(
new InjectionFactory(c => new DashboardDbContext()));
</code></pre> |
8,848,779 | Why does Math.min() return positive infinity, while Math.max() returns negative infinity? | <p>When I type in an array into the parameter of the javascript math minimum and maximum functions, it returns the correct value:</p>
<pre><code>console.log( Math.min( 5 ) ); // 5
console.log( Math.max( 2 ) ); // 2
var array = [3, 6, 1, 5, 0, -2, 3];
var minArray = Math.min( array ); // -2
var maxArray = Math.max( array ); // 6
</code></pre>
<p>However, when I use the function with no parameters, it returns an incorrect answer:</p>
<pre><code>console.log( Math.min() ); // Infinity
console.log( Math.max() ); // -Infinity
</code></pre>
<p>This one returns false:</p>
<pre><code>console.log( Math.min() < Math.max() );
</code></pre>
<p>Why does it do this?</p> | 8,848,828 | 10 | 13 | null | 2012-01-13 10:03:54.68 UTC | 10 | 2021-09-15 08:20:59.48 UTC | 2021-09-15 07:50:57.457 UTC | null | 3,840,170 | null | 824,294 | null | 1 | 38 | javascript|math|max|min | 20,604 | <p>Of course it would, because the start number should be <code>Infinity</code> for <code>Math.min</code>. All number that are lower than positive infinity should be the smallest from a list, if there are no smaller.</p>
<p>And for <code>Math.max</code> it's the same; all numbers that are larger than negative infinity should be the biggest if there are no bigger.</p>
<p>So for your first example:</p>
<p><code>Math.min(5)</code> where <code>5</code> is smaller than positive infinity (<code>Infinity</code>) it will return <code>5</code>.</p>
<h3>Update</h3>
<p>Calling <code>Math.min()</code> and <code>Math.max</code> with an array parameter may not work on every platform. You should do the following instead:</p>
<pre><code>Math.min.apply(null, [ 1, 2, 3, 4 , 5 ]);
</code></pre>
<p>Where the first parameter is the scope argument. Because <code>Math.min()</code> and <code>Math.max()</code> are "static" functions, we should set the scope argument to null.</p> |
22,915,939 | What is the difference between while(true) and for(;;) in PHP? | <p>Is there any difference in PHP between <code>while(true)</code> and <code>for(;;)</code> besides syntax and readability?</p> | 22,917,255 | 1 | 14 | null | 2014-04-07 14:53:42.66 UTC | 5 | 2020-03-06 16:23:02.313 UTC | 2020-03-06 16:23:02.313 UTC | null | 536,330 | null | 536,330 | null | 1 | 43 | php|for-loop|while-loop|infinite-loop|php-internals | 3,025 | <p>Ok, so first off, let me say this: <strong>Use <code>while(true)</code>, as it gives the most semantic meaning</strong>. You need to parse <code>for (;;)</code> as it's not something you see often.</p>
<p>With that said, let's analyze:</p>
<h1>Opcodes</h1>
<p>The code</p>
<pre><code>while(true) {
break;
}
echo "hi!";
</code></pre>
<p>Compiles down to the opcodes:</p>
<pre><code>0: JMPZ(true, 3)
1: BRK(1, 3)
2: JMP(0)
3: ECHO("hi!")
</code></pre>
<p>So basically, it does a check if "true", and if not, jumps to the 4th opcode which is the echo opcode). Then it breaks (which is really just a static jump to the 4th opcode). Then the end of the loop would be an unconditional jump back to the original check</p>
<p>Compare that to:</p>
<pre><code>for (;;) {
break;
}
echo "hi!";
</code></pre>
<p>Compiles down to:</p>
<pre><code>0: JMPZNZ(true, 2, 4)
1: JMP(0)
2: BRK(1, 4)
3: JMP(1)
4: ECHO("hi!")
</code></pre>
<p>So we can immediately see that there's an extra opcode in the <code>for(;;)</code> version. </p>
<h1>Opcode Definitions</h1>
<h2>JMPZ(condition, position)</h2>
<p>This opcode jumps if the condition is <code>false</code>. If it is <code>true</code>, it does nothing but advance one opcode.</p>
<h2>JMPZNZ(condition, pos1, pos2)</h2>
<p>This opcode jumps to <code>pos1</code> if the condition is true, and <code>pos2</code> if the condition is false.</p>
<h2>JMP(position)</h2>
<p>This opcode always jumps to the opcode at the specified position.</p>
<h2>BRK(level, position)</h2>
<p>This breaks <code>level</code> levels to the opcode at <code>position</code></p>
<h2>ECHO(string)</h2>
<p>Outputs the string</p>
<h1>Are They The Same</h1>
<p>Well, looking at the opcodes, it's clear that they are not identical. They are <code>==</code>, but not <code>===</code>. The <code>while(true)</code> loop does a conditional jump followed by code followed by an unconditional jump. The <code>for(;;)</code> loop does a conditional jump, followed by code, followed by an unconditional jump, followed by another unconditional jump. So it does an extra jump.</p>
<h1>Opcache</h1>
<p>In 5.5, the Optimizer portion of opcache will <a href="http://lxr.php.net/xref/PHP_TRUNK/ext/opcache/Optimizer/pass2.c#107" rel="noreferrer">optimize static conditional jumps</a>. </p>
<p>So that means the <code>while(true)</code> code will optimize down to:</p>
<pre><code>0: BRK(1, 2)
1: JMP(0)
2: ECHO("hi!")
</code></pre>
<p>And <code>for(;;)</code> loop becomes:</p>
<pre><code>0: BRK(1, 2)
1: JMP(0)
2: ECHO("hi!")
</code></pre>
<p>This is because the optimizer will find and optimize out jump-chains. So if you're using 5.5's built-in opcache, they will be identical...</p>
<h1>Caution</h1>
<p>This is a complete and utter micro-optimization to base a decision on. Use the readable one. Don't use one based on performance. The difference is there, but it's trivial.</p> |
11,337,997 | How to add custom filter after user authorize in spring application | <p>I am a newbie to Spring Security 3. I am using roles for users to login.</p>
<p>I want to add some session value after a user is authorized into the application. Maybe I need some filter so that it redirects to my method which adds some session value. I have configured my security.xml file but I am not sure whether I am doing right things. Any examples in that direction would help. Which Filter Class should I use? How should I configure security.xml file?</p>
<pre><code><custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>
<beans:bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="filterProcessesUrl" value="/j_spring_security_check" />
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationSuccessHandler" ref="successHandler" />
</beans:bean>
<beans:bean id="successHandler" class="org.dfci.sparks.datarequest.security.CustomAuthorizationFilter"/>
</code></pre>
<p>My filter class method I need to add some session value.</p>
<pre><code>public class CustomAuthorizationFilter implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
Set<String> roles = AuthorityUtils.authorityListToSet(authentication
.getAuthorities());
if (roles.contains("ROLE_USER")) {
request.getSession().setAttribute("myVale", "myvalue");
}
}
}
</code></pre>
<p><strong>Edit Code</strong></p>
<p>I have modified my security.xml file and class file</p>
<pre><code><custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>
</code></pre>
<pre class="lang-java prettyprint-override"><code>public class CustomAuthorizationFilter extends GenericFilterBean {
/*
* ServletRequestAttributes attr = (ServletRequestAttributes)
* RequestContextHolder.currentRequestAttributes(); HttpSession
* session=attr.getRequest().getSession(true);
*/
@Autowired
private UserService userService;
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession(true);
Authentication authentication = SecurityContextHolder
.getContext().getAuthentication();
Set<String> roles = AuthorityUtils
.authorityListToSet(authentication.getAuthorities());
User user = null;
if (true) {
session.setAttribute("Flag", "Y");
}
}
} catch (IOException ex) {
throw ex;
}
}
}
</code></pre>
<p>Which invokes each and every URL. Is it any alternative to call filter method only once when a user is authenticated?</p> | 11,360,650 | 2 | 4 | null | 2012-07-05 04:51:51.97 UTC | 3 | 2017-11-28 14:29:52.3 UTC | 2017-11-28 14:29:52.3 UTC | null | 711,006 | null | 765,551 | null | 1 | 7 | spring|spring-security | 44,148 | <p>Finally I was able to resolved my problem. Instead of using filter I have added handler which only invokes for successful login.</p>
<p>Following line is added in security.xml</p>
<pre><code><form-login login-page="/" authentication-failure-url="/?login_error=1" default-target-url="/" always-use-default-target="false"
authentication-success-handler-ref="authenticationSuccessHandler"/>
<logout />
<beans:bean id="authenticationSuccessHandler" class="security.CustomSuccessHandler"/>
</code></pre>
<p>Also I have added one custom handler which add session attribute.</p>
<pre><code>package security;
import java.io.IOException;
import java.security.GeneralSecurityException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
public class CustomSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(final HttpServletRequest request,
final HttpServletResponse response, final Authentication authentication)
throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication);
HttpSession session = request.getSession(true);
try {
if (CurrentUser.isUserInRole("USER")) {
session.setAttribute("Flag", "user");
}
} catch (Exception e) {
logger.error("Error in getting User()", e);
}
}
}
</code></pre> |
10,992,814 | passing grep into a variable in bash | <p>I have a file named email.txt like these one :</p>
<pre><code>Subject:My test
From:my email <[email protected]>
this is third test
</code></pre>
<p>I want to take out only the email address in this file by using bash script.So i put this script in my bash script named myscript:</p>
<pre><code>#!/bin/bash
file=$(myscript)
var1=$(awk 'NR==2' $file)
var2=$("$var1" | (grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'))
echo $var2
</code></pre>
<p>But I failed to run this script.When I run this command manually in bash i can obtain the email address:</p>
<pre><code>echo $var1 | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'
</code></pre>
<p>I need to put the email address to store in a variable so i can use it in other function.Can someone show me how to solve this problem?
Thanks.</p> | 10,993,059 | 5 | 3 | null | 2012-06-12 08:15:28.26 UTC | 8 | 2020-06-21 17:52:03.73 UTC | 2012-06-12 08:25:00.533 UTC | null | 1,017,224 | null | 1,309,384 | null | 1 | 19 | linux|bash|grep | 89,242 | <p>I think this is an overly complicated way to go about things, but if you just want to get your script to work, try this:</p>
<pre><code>#!/bin/bash
file="email.txt"
var1=$(awk 'NR==2' $file)
var2=$(echo "$var1" | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b')
echo $var2
</code></pre>
<p>I'm not sure what <code>file=$(myscript)</code> was supposed to do, but on the next line you want a file name as argument to <code>awk</code>, so you should just assign <code>email.txt</code> as a string value to <code>file</code>, not execute a command called <code>myscript</code>. <code>$var1</code> isn't a command (it's just a line from your text file), so you have to <code>echo</code> it to give <code>grep</code> anything useful to work with. The additional parentheses around <code>grep</code> are redundant.</p> |
11,309,710 | How to Apply the Textchange event on EditText | <p>I developed one simple app, like subtraction, addition.
In this app I use three EditTexts, one for answer and other two for question.
I want to calculate the answer of question on text change event. But when I apply the text change event on both of this the event occur but not properly work. Because when I enter in the text in first EditText of question the event occur but it throws this exception:</p>
<pre><code>07-03 16:39:48.844: E/EduApp Log :=>(12537): Error In Text change Event java.lang.NumberFormatException: unable to parse '' as integer
</code></pre>
<p>What do I do?
I use the <code>TextWatcher</code> for text change event.</p>
<pre><code>txtOne.addTextChangedListener(this);
txtTwo.addTextChangedListener(this);
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
</code></pre> | 11,309,734 | 7 | 0 | null | 2012-07-03 11:12:14.853 UTC | 10 | 2020-02-26 07:43:02.59 UTC | 2012-10-23 03:00:16.25 UTC | null | 1,267,661 | null | 1,197,031 | null | 1 | 29 | android|android-edittext|textwatcher | 75,630 | <p>I think you are receiving empty String <code>" "</code> which is causing this problem. Make sure you get a non-empty String from your <code>EditText</code>. </p>
<p>Consider your <code>EditText</code> doesn't have any value typed in, and you are trying to get its value and convert into int you will run into this kind of problem. </p>
<pre><code>edittext.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if(!s.equals("") ) {
//do your work here
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
</code></pre>
<p>Also check this link for more idea, </p>
<p><a href="https://stackoverflow.com/a/3377648/603744">https://stackoverflow.com/a/3377648/603744</a></p> |
11,062,841 | Start stop Service from Form App c# | <p>How can I start and stop a windows service from a c# Form application?</p> | 11,062,865 | 5 | 0 | null | 2012-06-16 11:01:53.24 UTC | 13 | 2019-11-29 07:16:57.783 UTC | null | null | null | null | 1,083,913 | null | 1 | 43 | c#|.net|windows-services | 57,685 | <p>Add a reference to <code>System.ServiceProcess.dll</code>. Then you can use the <a href="http://msdn.microsoft.com/en-us/library/yb9w7ytd">ServiceController</a> class.</p>
<pre><code>// Check whether the Alerter service is started.
ServiceController sc = new ServiceController();
sc.ServiceName = "Alerter";
Console.WriteLine("The Alerter service status is currently set to {0}",
sc.Status.ToString());
if (sc.Status == ServiceControllerStatus.Stopped)
{
// Start the service if the current status is stopped.
Console.WriteLine("Starting the Alerter service...");
try
{
// Start the service, and wait until its status is "Running".
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
// Display the current service status.
Console.WriteLine("The Alerter service status is now set to {0}.",
sc.Status.ToString());
}
catch (InvalidOperationException)
{
Console.WriteLine("Could not start the Alerter service.");
}
}
</code></pre> |
11,231,862 | Using Bootstrap Modal window as PartialView | <p>I was looking to using the <a href="http://twitter.github.com/bootstrap/javascript.html" rel="noreferrer">Twitter Bootstrap Modal windows</a> as a partial view. However, I do not really think that it was designed to be used in this fashion; it seems like it was meant to be used in a fairly static fashion. Nevertheless, I think it'd be cool to be able to use it as a partial view.</p>
<p>So for example, let's say I have a list of Games. Upon clicking on a link for a given game, I'd like to request data from the server and then display information about that game in a modal window "over the top of" the present page.</p>
<p>I've done a little bit of research and found <a href="https://stackoverflow.com/questions/10626885/passing-data-to-a-bootstrap-modal">this post</a> which is similar but not quite the same. </p>
<p>Has anyone tried this with success or failure? Anyone have something on jsFiddle or some source they'd be willing to share?</p>
<p>Thanks for your help.</p> | 11,234,655 | 6 | 0 | null | 2012-06-27 17:29:03.687 UTC | 40 | 2019-09-27 15:44:27.86 UTC | 2017-05-23 12:02:59.213 UTC | null | -1 | null | 1,380,295 | null | 1 | 68 | javascript|asp.net-mvc|twitter-bootstrap|modal-dialog | 136,533 | <p>Yes we have done this. </p>
<p>In your Index.cshtml you'll have something like..</p>
<pre><code><div id='gameModal' class='modal hide fade in' data-url='@Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
</code></pre>
<p>Then in JS for the same page (inlined or in a separate file you'll have something like this..</p>
<pre><code>$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
</code></pre>
<p>With a method on your controller that looks like this..</p>
<pre><code>[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
</code></pre>
<p>You will of course need a view called GetGameListing.cshtml inside of your Views folder.. </p> |
11,023,998 | "ClickOnce does not support the request execution level 'requireAdministrator.'" | <p>So I was writing an application that requires access to the registry.
I had not touched any build settings, wanting to get the thing working before I added the other touches, such as a description or name.<br /><br />
Out of the blue, I get an error that will not go away. <code>ClickOnce does not support the request execution level 'requireAdministrator'.</code> Now, I hadn't touched ClickOnce in this application. All I had done was include a manifest file requesting these permissions.<br /><br />
My problem now is that this error will not go away, and I cannot compile my program. Any advice on what to do? (Side note: I am about to go to bed, so I will check this tomorrow afternoon).</p> | 11,036,922 | 11 | 6 | null | 2012-06-13 22:04:20.767 UTC | 20 | 2022-04-27 17:40:41.633 UTC | 2012-06-13 22:06:12.307 UTC | null | 222,673 | null | 1,055,881 | null | 1 | 107 | c#|wpf|compiler-errors|clickonce | 78,761 | <p><strong>Edit:</strong> This comment gives a good answer, too.</p>
<blockquote>
<p>Click once appears to get enabled whenever you click "Publish", whether you want it to or not! If you are using "requireAdministrator" then it appears that you cannot use ClickOnce, and therefore cannot "Publish" your project.</p>
</blockquote>
<hr>
<p><strong>Original:</strong></p>
<p>Turns out that under the Security tab, "Enable ClickOnce security settings" was checked. Even though I didn't check it.
Anyway, unchecking that stopped ClickOnce giving me errors. That took a while to find...</p> |
12,977,661 | Is there a way to suppress JSHint warning for one given line? | <p>I have a (single) case in my app were <code>eval</code> is used, and I would like to suppress JSHint warning only for this case.</p>
<p>Is there a way to achieve that? Configuration, magic comment, ...?</p> | 19,635,321 | 3 | 0 | null | 2012-10-19 15:34:52.007 UTC | 64 | 2016-05-25 15:36:25.25 UTC | null | null | null | null | 90,741 | null | 1 | 272 | jshint | 104,416 | <p>Yes, there is a way. Two in fact. In <a href="http://www.jshint.com/blog/new-in-jshint-oct-2013/" rel="noreferrer">October 2013</a> jshint added a way to ignore blocks of code like this: </p>
<pre><code>// Code here will be linted with JSHint.
/* jshint ignore:start */
// Code here will be ignored by JSHint.
/* jshint ignore:end */
// Code here will be linted with JSHint.
</code></pre>
<p>You can also ignore a single line with a trailing comment like this:</p>
<pre><code>ignoreThis(); // jshint ignore:line
</code></pre> |
12,785,001 | Verify Android apk has not been repackaged? | <p>Looking to improved the security of my Android app to flag if the .apk has been extracted, modified, repacked and resigned. Here's article from Zdnet noting the issue <a href="http://www.zdnet.com/android-malwares-dirty-secret-repackaging-of-legit-apps-7000000886/">link1</a>. </p>
<p>The concern is if the app is targeted by hackers they could add malicious code and upload to an alternate app store and dupe users in to downloading it. </p>
<p>So I'm thinking code to verify a checksum of the apk or signing certificate?</p>
<p>I appreciate the app code could be repacked and any security code removed, but it does increase the difficulty of repacking it, maybe enough for them to try another app.</p>
<p>[update]I know the Google Play store licensing module offers something similar but I'm looking for something for non paid apps and other/non marketplaces. </p> | 18,053,836 | 3 | 2 | null | 2012-10-08 15:41:44.813 UTC | 11 | 2019-12-19 08:33:14.347 UTC | 2012-10-08 15:50:28.557 UTC | null | 31,751 | null | 31,751 | null | 1 | 21 | android|security|checksum | 18,731 | <p>I ended up using <a href="http://www.saikoa.com/dexguard" rel="nofollow noreferrer">Dexguard</a> (paid obfuscator for Android). It offers a module that preforms apk verification. It is simple to implement and offers better than average protection. </p>
<p>Here's the code to do the check:</p>
<pre><code>dexguard.util.TamperDetection.checkApk(context)
</code></pre>
<p>The main issue is where to store the checksum of the apk to verify against given that it could to be replaced. The dexguard way is to check it locally but using other features like class/string encryption and api hiding obscure this call. </p> |
13,007,582 | HTML5 drag and copy? | <p>I've seen some working code for HTML5 drag and drop but has anyone an example of a drag and copy? I want to drag an element onto a drop element but only copy the element to this location.</p> | 13,008,017 | 2 | 0 | null | 2012-10-22 08:33:24.107 UTC | 12 | 2015-05-12 22:14:05.407 UTC | null | null | null | null | 1,729,308 | null | 1 | 37 | html | 45,899 | <p>I will stick to the example shown here: <a href="http://www.w3schools.com/html/html5_draganddrop.asp" rel="noreferrer">http://www.w3schools.com/html/html5_draganddrop.asp</a></p>
<p><em>Assuming we have this document:</em></p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<script>
<!-- script comes in the text below -->
</script>
</head>
<body>
<div id="div1" ondrop="drop(event)"
ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true"
ondragstart="drag(event)" width="336" height="69">
</body>
</html>
</code></pre>
<p><strong>Normal Drag & Drop</strong></p>
<p>Normal drag and drop has such functions assigned to the respective elements:</p>
<pre><code>function allowDrop(ev) {
/* The default handling is to not allow dropping elements. */
/* Here we allow it by preventing the default behaviour. */
ev.preventDefault();
}
function drag(ev) {
/* Here is specified what should be dragged. */
/* This data will be dropped at the place where the mouse button is released */
/* Here, we want to drag the element itself, so we set it's ID. */
ev.dataTransfer.setData("text/html", ev.target.id);
}
function drop(ev) {
/* The default handling is not to process a drop action and hand it to the next
higher html element in your DOM. */
/* Here, we prevent the default behaviour in order to process the event within
this handler and to stop further propagation of the event. */
ev.preventDefault();
/* In the drag event, we set the *variable* (it is not a variable name but a
format, please check the reference!) "text/html", now we read it out */
var data=ev.dataTransfer.getData("text/html");
/* As we put the ID of the source element into this variable, we can now use
this ID to manipulate the dragged element as we wish. */
/* Let's just move it through the DOM and append it here */
ev.target.appendChild(document.getElementById(data));
}
</code></pre>
<p><strong>Drag & Copy</strong></p>
<p>Whereas you'll have to alter the drop function so that it copies the DOM element instead of moving it.</p>
<pre><code>/* other functions stay the same */
function drop(ev) {
ev.preventDefault();
var data=ev.dataTransfer.getData("text/html");
/* If you use DOM manipulation functions, their default behaviour it not to
copy but to alter and move elements. By appending a ".cloneNode(true)",
you will not move the original element, but create a copy. */
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "newId"; /* We cannot use the same ID */
ev.target.appendChild(nodeCopy);
}
</code></pre>
<p>Try this page: <a href="http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop" rel="noreferrer">http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop</a><br>
And then append a <code>.cloneNode(true)</code> to <code>getElementById(data)</code>.</p>
<p><strong>Switch between Copy & Paste</strong></p>
<p>You could even do things like in file managers: Ctrl-Key switches from moving to copying:</p>
<pre><code>function drop(ev) {
ev.preventDefault();
var data=ev.dataTransfer.getData("text/html");
/* Within a Mouse event you can even check the status of some Keyboard-Buttons
such as CTRL, ALT, SHIFT. */
if (ev.ctrlKey)
{
var nodeCopy = document.getElementById(data).cloneNode(true);
nodeCopy.id = "newId"; /* We cannot use the same ID */
ev.target.appendChild(nodeCopy);
}
else
ev.target.appendChild(document.getElementById(data));
}
</code></pre> |
60,848,786 | Xcode 11.4. Navigation's Title Color gone BLACK from storyboard | <p>I recently updated my Xcode to 11.4. When I run the app on the device, i've noticed that all my navigations item's titles gone fully black when being set from storyboard.
<a href="https://i.stack.imgur.com/FC4Ei.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FC4Ei.png" alt="enter image description here"></a></p>
<p>You can't change neither from code, the following line of code doesn't work anymore</p>
<pre class="lang-swift prettyprint-override"><code>self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
</code></pre>
<p>I only make it work using some iOS 13 stuffs UINavigationBarAppearance</p>
<pre class="lang-swift prettyprint-override"><code>@available(iOS 13.0, *)
private func setupNavigationBar() {
let app = UINavigationBarAppearance()
app.titleTextAttributes = [.foregroundColor: UIColor.white]
app.backgroundColor = Constants.Color.barColor
self.navigationController?.navigationBar.compactAppearance = app
self.navigationController?.navigationBar.standardAppearance = app
self.navigationController?.navigationBar.scrollEdgeAppearance = app
self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
</code></pre>
<p>Can somebody explain me why??? This is a crucial bug, or some new hidden feature?</p> | 61,238,916 | 8 | 4 | null | 2020-03-25 12:23:45.55 UTC | 10 | 2022-08-20 12:40:15.07 UTC | null | null | null | null | 4,644,852 | null | 1 | 58 | ios|swift|xcode|navigationbar | 5,406 | <p>Apple finally fixed it in version 11.4.1</p>
<p><a href="https://developer.apple.com/documentation/xcode_release_notes/xcode_11_4_1_release_notes" rel="noreferrer">https://developer.apple.com/documentation/xcode_release_notes/xcode_11_4_1_release_notes</a></p> |
16,701,108 | A way of achieving lazy evaluation in C++ | <p>So I was answering a question about lazy evaluation (<a href="https://stackoverflow.com/questions/16657207/laziness-in-c11/16699937#16699937">here</a>, my answer is overkill for that case but the idea seems interesting) and it made me think about how lazy evaluation might be done in C++. I came up with a way but I wasn't sure of all the pitfalls in this. Are there other ways of achieving lazy evaluation? how might this be done? What are the pitfalls and this and other designs?</p>
<p>Here is my idea:</p>
<pre><code>#include <iostream>
#include <functional>
#include <memory>
#include <string>
#define LAZY(E) lazy<decltype((E))>{[&](){ return E; }}
template<class T>
class lazy {
private:
typedef std::function<std::shared_ptr<T>()> thunk_type;
mutable std::shared_ptr<thunk_type> thunk_ptr;
public:
lazy(const std::function<T()>& x)
: thunk_ptr(
std::make_shared<thunk_type>([x](){
return std::make_shared<T>(x());
})) {}
const T& operator()() const {
std::shared_ptr<T> val = (*thunk_ptr)();
*thunk_ptr = [val](){ return val; };
return *val;
}
T& operator()() {
std::shared_ptr<T> val = (*thunk_ptr)();
*thunk_ptr = [val](){ return val; };
return *val;
}
};
void log(const lazy<std::string>& msg) {
std::cout << msg() << std::endl;
}
int main() {
std::string hello = "hello";
std::string world = "world";
auto x = LAZY((std::cout << "I was evaluated!\n", hello + ", " + world + "!"));
log(x);
log(x);
log(x);
log(x);
return 0;
}
</code></pre>
<p>Some things I was concerned about in my design. </p>
<ul>
<li>decltype has some strange rules. Does my usage of decltype have any gotchas? I added extra parentheses around the E in the LAZY macro to make sure that single names got treated fairly, as references just like vec[10] would. Are there other things I'm not accounting for?</li>
<li>There are lots of layers of indirection in my example. It seems like this might be avoidable.</li>
<li>Is this correctly memoizing the result so that no matter what or how many things reference the lazy value, it will only evaluate once(this one I'm pretty confident in but lazy evaluation plus tons of shared pointers might be throwing me a loop)</li>
</ul>
<p>What are your thoughts?</p> | 19,125,422 | 5 | 3 | null | 2013-05-22 20:33:51.297 UTC | 9 | 2018-02-05 12:07:07.693 UTC | 2017-05-23 12:16:50.65 UTC | null | -1 | null | 2,406,646 | null | 1 | 14 | c++|c++11|lazy-evaluation | 9,923 | <ul>
<li>You may want to have <code>thunk_type</code> and reference to it as a separate objects. Right now copy of <code>lazy<T></code> will gain nothing from evaluation of origin. But in that case you'll get additional indirect access.</li>
<li>Sometimes you may get rid of wrapping into std::function by simply using templates.</li>
<li>I'm not sure that value needs to be shared_ptr. Maybe caller should decide that.</li>
<li>You are going to produce new closures on each access.</li>
</ul>
<p>Consider next modification:</p>
<pre><code>template<typename F>
lazy(const F& x) :
thunk_ptr([&x,&this](){
T val = (*x)();
thunk_ptr = [val]() { return val; };
return val;
})
{}
</code></pre>
<p>Or alternative implementation might look like:</p>
<pre><code>template<typename F>
auto memo(const F &x) -> std::function<const decltype(x()) &()> {
typedef decltype(x()) return_type;
typedef std::function<const return_type &()> thunk_type;
auto thunk_ptr = std::make_shared<thunk_type>();
auto *thunk_cptr = thunk_ptr.get();
// note that this lambda is called only from scope which holds thunk_ptr
*thunk_ptr = [thunk_cptr, &x]() {
auto val = std::move(x());
auto &thunk = *thunk_cptr;
thunk = [val]() { return val; };
// at this moment we can't refer to catched vars
return thunk();
};
return [thunk_ptr]() { return (*thunk_ptr)(); };
};
</code></pre> |
17,129,785 | How to match a tree against a large set of patterns? | <p>I have a potentially infinite set of symbols: <code>A, B, C, ...</code> There is also a distinct special placeholder symbol <code>?</code> (its meaning will be explained below).</p>
<p>Consider non-empty finite trees such that every node has a symbol attached to it and 0 or more non-empty sub-trees. The order of sub-trees of a given node is significant (so, for example, if there is a node with 2 sub-trees, we can distinguish which one is left and which one is right). Any given symbol can appear in the tree 0 of more times attached to different nodes. The placeholder symbol <code>?</code> can be attached only to leaf nodes (i.e. nodes having no sub-trees). It follows from the usual definition of a tree that trees are acyclic.</p>
<p>The finiteness requirement means that the total number of nodes in a tree is a positive finite integer. It follows that the total number of attached symbols, the tree depth and the total number of nodes in every sub-tree are all finite.</p>
<p>Trees are given in a functional notation: a node is represented by a symbol attached to it and, if there are any sub-trees, it is followed by parentheses containing comma-separated list of sub-trees represented recursively in the same way. So, for example the tree</p>
<pre><code> A
/ \
? B
/ \
A C
/|\
A C Q
\
?
</code></pre>
<p>is represented as <code>A(?,B(A(A,C,Q(?)),C))</code>.</p>
<p>I have a pre-calculated unchanging set of trees <strong>S</strong> that will be used as patterns to match. The set will typically have ~ 10<sup>5</sup> trees, and every its element will typically have ~ 10-30 nodes. I can use a plenty of time to create beforehand any representation of <strong>S</strong> that will best suit my problem stated below.</p>
<p>I need to write a function that accepts a tree <strong>T</strong> (typically with ~ 10<sup>2</sup> nodes) and checks as fast as possible if <strong>T</strong> contains as a subtree any element of <strong>S</strong>, provided that any node with placeholder symbol <code>?</code> matches any non-empty subtree (both when it appears in <strong>T</strong> or in an element of <strong>S</strong>).</p>
<p>Please suggest a data structure to store the set <strong>S</strong> and an algorithm to check for a match. Any programing language or a pseudo-code is OK.</p> | 17,130,176 | 2 | 7 | null | 2013-06-16 03:02:02.03 UTC | 17 | 2013-06-16 04:28:52.833 UTC | null | null | null | null | 2,410,220 | null | 1 | 20 | algorithm|optimization|data-structures|tree|pattern-matching | 945 | <p><a href="http://www.doiserbia.nb.rs/img/doi/1820-0214/2010/1820-02141002331F.pdf" rel="noreferrer">This paper</a> describes a variant of the <a href="http://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_string_matching_algorithm" rel="noreferrer">Aho–Corasick algorithm</a>, where instead of using a finite state machine (which the standard Aho–Corasick algorithm uses for string matching) the algorithm instead uses a pushdown automaton for subtree matching. Like the Aho-Corasick string-matching algorithm, their variant only requires one pass through the input tree to match against the entire dictionary of <strong>S</strong>.</p>
<p>The paper is quite complex - it may be worth it to <a href="http://webdev.fit.cvut.cz/~flourtom/" rel="noreferrer">contact the author</a> to see if he has any source code available.</p> |
16,949,468 | How does ViewBag in ASP.NET MVC work behind the scenes? | <p>I am reading a book on ASP.NET MVC and I'm wondering how the following example works:</p>
<h2>Example #1</h2>
<h3>Controller</h3>
<pre><code>public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
}
</code></pre>
<h3>View</h3>
<pre><code><h1>@ViewBag.MyProperty</h1>
</code></pre>
<p>Now I understand that <code>ViewBag</code> is a dynamic object, so that's how you can set the property (though I don't know much about dynamic objects, never worked with them.) But how does the view get the specific instance of the <code>ViewBag</code> from the controller, even though we don't pass anything directly?</p>
<p>I thought that the <code>ViewBag</code> could be a <code>public</code> <code>static</code> object, but then any change to it would be global and it wouldn't be specific to a view instance.</p>
<p>Could you elaborate as to how this works behind the scenes?</p>
<h2>Example #2</h2>
<h3>Controller</h3>
<pre><code>public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
public ActionResult Index2()
{
ViewBag.MyProperty = 6;
return View();
}
}
</code></pre>
<p>Now let's say the <code>Index</code> method is called first, and then the <code>Index2</code>. In the end the value of <code>ViewBag.MyProperty</code> will end up as 6 (the value from <code>Index2</code>). I feel that it is not a good thing to do, but at the same time I feel that I'm thinking in desktop development terms. Maybe it doesn't matter when used with ASP.NET MVC, as the web is stateless. <strong>Is this the case?</strong></p> | 16,950,006 | 3 | 17 | null | 2013-06-05 20:40:25.153 UTC | 3 | 2013-06-06 01:35:57.017 UTC | 2013-06-06 00:17:08.417 UTC | null | 811 | null | 494,094 | null | 1 | 34 | c#|asp.net-mvc|dynamic|viewbag | 44,868 | <p><code>ViewBag</code> is a property of <code>ControllerBase</code>, which all controllers must inherit from. It's a <code>dynamic</code> object, that's why you can add new properties to it without getting compile time errors.</p>
<p>It's not <code>static</code>, it's a member of the object. During the request lifetime, the controller instance is created and disposed, so you won't have "concurrency" problems, like overwriting the value.</p>
<p>The <code>View</code> (and its variants) method is not <code>static</code> as well, and this is how the view receives the <code>ViewBag</code> values: during the process of rendering the view, the controller instance has its ViewBag instance as well.</p> |
16,950,394 | Why is a trailing comma a SyntaxError in an argument list that uses *args syntax? | <p>Why can't you use a trailing comma with <code>*args</code> in Python? In other words, this works</p>
<pre><code>>>> f(1, 2, b=4,)
</code></pre>
<p>But this does not</p>
<pre><code>>>> f(*(1, 2), b=4,)
File "<stdin>", line 1
f(*(1, 2), b=4,)
^
SyntaxError: invalid syntax
</code></pre>
<p>This is the case with both Python 2 and Python 3.</p> | 16,950,508 | 2 | 8 | null | 2013-06-05 21:42:18.703 UTC | 8 | 2017-08-17 16:55:10.417 UTC | 2017-08-17 16:55:10.417 UTC | null | 4,116,239 | null | 161,801 | null | 1 | 75 | python|syntax|python-internals | 5,096 | <p>Let's look at the <a href="http://docs.python.org/2.7/reference/expressions.html#calls" rel="nofollow noreferrer">language specification</a>:</p>
<pre><code>call ::= primary "(" [argument_list [","]
| expression genexpr_for] ")"
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression]
| keyword_arguments ["," "*" expression]
["," "**" expression]
| "*" expression ["," "*" expression] ["," "**" expression]
| "**" expression
positional_arguments ::= expression ("," expression)*
keyword_arguments ::= keyword_item ("," keyword_item)*
keyword_item ::= identifier "=" expression
</code></pre>
<p>Let's sift down to the parts we care about:</p>
<pre><code>call ::= primary "(" [argument_list [","]] ")"
argument_list ::= positional_arguments ["," keyword_arguments]
["," "*" expression] ["," keyword_arguments]
["," "**" expression]
positional_arguments ::= expression ("," expression)*
keyword_arguments ::= keyword_item ("," keyword_item)*
keyword_item ::= identifier "=" expression
</code></pre>
<p>So, it looks like after any arguments to a function call, we're allowed an extra <code>,</code>. So this looks like a bug in the cpython implementation.</p>
<p>Something like: <code>f(1, *(2,3,4), )</code> should work according to this grammar, but doesn't in CPython.</p>
<hr>
<p>In an earlier answer, <a href="https://stackoverflow.com/users/102441/eric">Eric</a> linked to the <a href="http://docs.python.org/2/reference/grammar.html" rel="nofollow noreferrer">CPython grammar specification</a>, which includes the CPython implementation of the above grammar. Here it is below:</p>
<pre><code>arglist: (argument ',')* ( argument [',']
| '*' test (',' argument)* [',' '**' test]
| '**' test
)
</code></pre>
<p>Note, that this grammar is <strong>not the same</strong> as the one proposed by the language specification. I'd consider this an implementation bug.</p>
<hr>
<p>Note that there are additional issues with the CPython implementation. This should also be supported: <code>f(*(1,2,3), *(4,5,6))</code></p>
<p>Oddly though, the specification does not allow <code>f(*(1,2,3), *(4,5,6), *(7,8,9))</code></p>
<p><strong>As I look at this more,</strong> I think this part of the specification needs some fixing. This is allowed: <code>f(x=1, *(2,3))</code>, but this isn't: <code>f(x=1, 2, 3)</code>.</p>
<hr>
<p>And to perhaps be helpful to the original question, in CPython, you can have a trailing comma if you don't use the <code>*args</code> or the <code>**kwargs</code> feature. I agree that this is lame.</p> |
50,897,768 | In Visual Studio, `thread_local` variables' destructor not called when used with std::async, is this a bug? | <p>The following code</p>
<pre><code>#include <iostream>
#include <future>
#include <thread>
#include <mutex>
std::mutex m;
struct Foo {
Foo() {
std::unique_lock<std::mutex> lock{m};
std::cout <<"Foo Created in thread " <<std::this_thread::get_id() <<"\n";
}
~Foo() {
std::unique_lock<std::mutex> lock{m};
std::cout <<"Foo Deleted in thread " <<std::this_thread::get_id() <<"\n";
}
void proveMyExistance() {
std::unique_lock<std::mutex> lock{m};
std::cout <<"Foo this = " << this <<"\n";
}
};
int threadFunc() {
static thread_local Foo some_thread_var;
// Prove the variable initialized
some_thread_var.proveMyExistance();
// The thread runs for some time
std::this_thread::sleep_for(std::chrono::milliseconds{100});
return 1;
}
int main() {
auto a1 = std::async(std::launch::async, threadFunc);
auto a2 = std::async(std::launch::async, threadFunc);
auto a3 = std::async(std::launch::async, threadFunc);
a1.wait();
a2.wait();
a3.wait();
std::this_thread::sleep_for(std::chrono::milliseconds{1000});
return 0;
}
</code></pre>
<p>Compiled and run width clang in macOS:</p>
<pre><code>clang++ test.cpp -std=c++14 -pthread
./a.out
</code></pre>
<p>Got result</p>
<blockquote>
<pre><code>Foo Created in thread 0x70000d9f2000
Foo Created in thread 0x70000daf8000
Foo Created in thread 0x70000da75000
Foo this = 0x7fd871d00000
Foo this = 0x7fd871c02af0
Foo this = 0x7fd871e00000
Foo Deleted in thread 0x70000daf8000
Foo Deleted in thread 0x70000da75000
Foo Deleted in thread 0x70000d9f2000
</code></pre>
</blockquote>
<p>Compiled and run in Visual Studio 2015 Update 3:</p>
<blockquote>
<pre><code>Foo Created in thread 7180
Foo this = 00000223B3344120
Foo Created in thread 8712
Foo this = 00000223B3346750
Foo Created in thread 11220
Foo this = 00000223B3347E60
</code></pre>
</blockquote>
<p>Destructor are not called.</p>
<p>Is this a bug or some undefined grey zone?</p>
<p>P.S.</p>
<p>If the sleep <code>std::this_thread::sleep_for(std::chrono::milliseconds{1000});</code> at the end is not long enough, you may not see all 3 "Delete" messages sometimes.</p>
<p>When using <code>std::thread</code> instead of <code>std::async</code>, the destructors get called on both platform, and all 3 "Delete" messages will always be printed.</p> | 50,898,570 | 2 | 6 | null | 2018-06-17 14:53:30.173 UTC | 9 | 2018-06-27 18:30:54.97 UTC | 2018-06-17 14:58:35.413 UTC | null | 358,242 | null | 358,242 | null | 1 | 26 | c++|multithreading|visual-studio|memory-leaks | 2,690 | <p><strong>Introductory Note:</strong> I have now learned a lot more about this and have therefore re-written my answer. Thanks to @super, @M.M and (latterly) @DavidHaim and @NoSenseEtAl for putting me on the right track.</p>
<p><strong>tl;dr</strong> Microsoft's implementation of <code>std::async</code> is non-conformant, but they have their reasons and what they have done can actually be useful, once you understand it properly.</p>
<p>For those who don't want that, it is not too difficult to code up a drop-in replacement replacement for <code>std::async</code> which works the same way on all platforms. I have posted one <a href="https://stackoverflow.com/questions/50898954/possible-stdasync-implementation-bug-windows">here</a>.</p>
<p><strong>Edit:</strong> Wow, how <em>open</em> MS are being these days, I like it, see: <a href="https://github.com/MicrosoftDocs/cpp-docs/issues/308" rel="noreferrer">https://github.com/MicrosoftDocs/cpp-docs/issues/308</a></p>
<hr>
<p>Let's being at the beginning. <a href="http://en.cppreference.com/w/cpp/thread/async" rel="noreferrer">cppreference</a> has this to say (emphasis and strikethrough mine): </p>
<blockquote>
<p>The template function <code>async</code> runs the function <code>f</code> asynchronously (<strike>potentially</strike> optionally in a separate thread <strong>which may be part of a thread pool</strong>).</p>
</blockquote>
<p>However, the <a href="http://eel.is/c++draft/futures.async#3.1" rel="noreferrer">C++ standard</a> says this:</p>
<blockquote>
<p>If <code>launch::async</code> is set in <code>policy</code>, [<code>std::async</code>] calls [the function f] <strong>as if in a new thread of execution</strong> ...</p>
</blockquote>
<p>So which is correct? The two statements have very different semantics as the OP has discovered. Well of course the standard is correct, as both clang and gcc show, so why does the Windows implementation differ? And like so many things, it comes down to history.</p>
<p>The (oldish) <a href="https://bartoszmilewski.com/2012/05/11/the-future-of-c-concurrency-and-parallelism/" rel="noreferrer">link that M.M dredged up</a> has this to say, amongst other things:</p>
<blockquote>
<p>... Microsoft has its implementation of [<code>std::async</code>] in the form of <a href="https://msdn.microsoft.com/en-us/library/dd492418.aspx" rel="noreferrer">PPL</a> (Parallel Pattern Library) ... [and] I can understand the eagerness of those companies to bend the rules and make these libraries accessible through <code>std::async</code>, especially if they can dramatically improve performance...</p>
<p>... Microsoft wanted to change the semantics of <code>std::async</code> when called with <code>launch_policy::async.</code> I think this was pretty much ruled out in the ensuing discussion ... (rationale follows, if you want to know more then read the link, it's well worth it).</p>
</blockquote>
<p>And PPL is based on Windows' built-in support for <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms686766%28v=vs.85%29.aspx" rel="noreferrer">ThreadPools</a>, so @super was right.</p>
<p>So what does the Windows thread pool do and what is it good for? Well, it's intended to manage frequently-sheduled, short-running tasks in an efficient way so point 1 is <strong>don't abuse it</strong>, but my simple tests show that if this is your use-case then it can offer significant efficiencies. It does, essentially, two things</p>
<ul>
<li>It recycles threads, rather than having to always start a new one for each asynchronous task you launch.</li>
<li>It limits the total number of background threads it uses, after which a call to <code>std::async</code> will block until a thread becomes free. On my machine, this number is 768.</li>
</ul>
<p>So knowing all that, we can now explain the OP's observations:</p>
<ol>
<li><p>A new thread is created for each of the three tasks started by <code>main()</code> (because none of them terminates immediately).</p></li>
<li><p>Each of these three threads creates a new thread-local variable <code>Foo some_thread_var</code>.</p></li>
<li><p>These three tasks all run to completion but the <em>threads</em> they are running on remain in existence (sleeping).</p></li>
<li><p>The program then sleeps for a short while and then exits, leaving the 3 thread-local variables un-destructed.</p></li>
</ol>
<p>I ran a number of tests and in addition to this I found a few key things:</p>
<ul>
<li>When a thread is recycled, the thread-local variables are re-used. Specifically, they are <strong>not</strong> destroyed and then re-created (you have been warned!).</li>
<li>If all the asynchonous tasks complete and you wait long enough, the thread pool terminates all the associated threads and the thread-local variables <em>are</em> then destroyed. (No doubt the actual rules are more complex than that but that's what I observed).</li>
<li>As new asynchonous tasks are submitted, the thread pool limits the <em>rate</em> at which new threads are created, in the hope that one will become free before it needs to perform all that work (creating new threads is expensive). A call to <code>std::async</code> might therefore take a while to return (up to 300ms in my tests). In the meantime, it's just hanging around, hoping that its ship will come in. This behaviour is documented but I call it out here in case it takes you by surprise.</li>
</ul>
<p><strong>Conclusions:</strong> </p>
<ol>
<li><p>Microsoft's implementation of <code>std::async</code> is non-conformant but it is clearly designed with a specific purpose, and that purpose is to make good use of the Win32 ThreadPool API. You can beat them up for blantantly flouting the standard but it's been this way for a long time and they probably have (important!) customers who rely on it. I will ask them to call this out in their documentation. Not doing <em>that</em> is criminal.</p></li>
<li><p>It is <strong>not</strong> safe to use thread_local variables in <code>std::async</code> tasks on Windows. Just don't do it, it will end in tears.</p></li>
</ol> |
4,529,057 | KnockoutJS, updating ViewModel after ajax call | <p>I am using Knockout and the Knockout Mapping plugin.</p>
<ul>
<li>My MVC3 Action returns a View and not JSON directly as such I convert my Model into JSON.</li>
<li>This is a data entry form and due to the nature of the system validation is all done in the Service Layer, with warnings returned in a Response object within the ViewModel.</li>
<li>The initial bindings and updates work correctly its the "post-update" behavior that is causing me a problem.</li>
</ul>
<p><strong>My problem is after calling the AJAX POST and and receiving my JSON response knockout is not updating all of my bindings... as if the observable/mappings have dropped off</strong></p>
<p>If I include an additional ko.applyBindings(viewModel); in the <strong>success</strong> things do work... however issues then arise with multiple bindings and am certain this is not the correct solution.</p>
<p>This is the HTML/Template/Bindings</p>
<pre><code><!-- Start Form -->
<form action="@Url.Action("Edit")" data-bind="submit: save">
<div id="editListing" data-bind="template: 'editListingTemplate'"></div>
<div id="saveListing" class="end-actions">
<button type="submit">Save Listings</button>
</div>
</form>
<!-- End Form -->
<!-- Templates -->
<script type="text/html" id="editListingTemplate">
<div class="warning message error" data-bind="visible: Response.HasWarning">
<span>Correct the Following to Save</span>
<ul>
{{each(i, warning) Response.BusinessWarnings}}
<li data-bind="text: Message"></li>
{{/each}}
</ul>
</div>
<fieldset>
<legend>Key Information</legend>
<div class="editor-label">
<label>Project Name</label>
</div>
<div class="editor-field">
<input data-bind="value: Project_Name" class="title" />
</div>
</fieldset>
</script>
<!-- End templates -->
</code></pre>
<p>And this is the Knockout/Script</p>
<pre><code><script type="text/javascript">
@{ var jsonData = new HtmlString(new JavaScriptSerializer().Serialize(Model)); }
var initialData = @jsonData;
var viewModel = ko.mapping.fromJS(initialData);
viewModel.save = function ()
{
this.Response = null;
var data = ko.toJSON(this);
$.ajax({
url: '@Url.Action("Edit")',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function (result) {
ko.mapping.updateFromJS(viewModel, result);
}
});
}
$(function() {
ko.applyBindings(viewModel);
});
</script>
</code></pre>
<p>And this is the response JSON returned from the successful request including validation messages.</p>
<pre><code>{
"Id": 440,
"Project_Name": "",
"Response": {
"HasWarning": true,
"BusinessWarnings": [
{
"ExceptionType": 2,
"Message": "Project is invalid."
}, {
"ExceptionType": 1,
"Message": "Project_Name may not be null"
}
]
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p><a href="http://jsfiddle.net/galenp/etRAJ/12/" rel="noreferrer">Fiddler Demo</a> Is a trimmed live example of what I am experiencing. I have the Project_Name updating with the returned JSON but the viewModel.Response object and properties are not being updated through their data bindings. Specifically Response.HasWarning().</p>
<p>I've changed back to ko.mapping.updateFromJS because in my controller I am specifically returning Json(viewModel).</p>
<p>Cleaned up my initial code/question to match the demo.</p> | 4,590,802 | 2 | 0 | null | 2010-12-25 02:07:02.97 UTC | 10 | 2011-01-04 05:06:04.46 UTC | 2011-01-04 03:41:57.227 UTC | null | 262,758 | null | 262,758 | null | 1 | 10 | asp.net|jquery|asp.net-mvc-3|knockout.js | 21,321 | <p>I guess Response is reserved, when I change "Response" to "resp", everything went fine. See <a href="http://jsfiddle.net/BBzVm/" rel="noreferrer">http://jsfiddle.net/BBzVm/</a></p> |
4,115,228 | Heroku - How can I undo a push on heroku? | <p>After pushing my app on heroku, my app crashes.
I don't want to make a git rebase before getting heroku last version (if I do so, I'll get fast-forward errors...)</p>
<p>I would be pleased to know if there is a command to do it (I don't find it on the heroku doc)</p>
<p>Thank you!</p> | 4,115,281 | 2 | 1 | null | 2010-11-06 21:20:06.793 UTC | 6 | 2020-11-28 02:59:27.173 UTC | null | null | null | null | 348,386 | null | 1 | 37 | heroku | 17,780 | <p>Use <code>git push heroku --force</code> to push your local <code>HEAD</code>.</p> |
26,796,634 | Using jQuery, how can I find if a form has changed? | <p>I want to know if a form has changed at all. The form can contain any form element, such as input, select, textarea etc. Basically I want a way to display to the user that they have unsaved changed made to a form.</p>
<p>How can I do this using jQuery? </p>
<p><strong>To clarify: I want to catch ANY change to the form, not only to input elements but to all other form elements as well, textarea, select etc.</strong></p> | 26,796,840 | 1 | 5 | null | 2014-11-07 07:57:56.917 UTC | 11 | 2014-11-07 08:17:18.603 UTC | 2014-11-07 08:08:16.33 UTC | null | 703,569 | null | 703,569 | null | 1 | 29 | javascript|jquery | 29,789 | <p>The approach I usually take in such a case is that I check serialized form value. So the idea is that you calculate initial form state with <a href="http://api.jquery.com/serialize/" rel="noreferrer"><code>$.fn.serialize</code></a> method. Then when needed you just compare current state with the original serialized string.</p>
<p>To target all input elements (select, textarea, checkbox, input-text, etc.) within a form you can use pseudo selector <code>:input</code>.</p>
<p>For example:</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-js lang-js prettyprint-override"><code>var $form = $('form'),
origForm = $form.serialize();
$('form :input').on('change input', function() {
$('.change-message').toggle($form.serialize() !== origForm);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.change-message {
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class="change-message">You have unsaved changes.</div>
<div>
<textarea name="description" cols="30" rows="3"></textarea>
</div>
<div>Username: <input type="text" name="username" /></div>
<div>
Type:
<select name="type">
<option value="1">Option 1</option>
<option value="2" selected>Option 2</option>
<option value="3">Option 3</option>
</select>
</div>
<div>
Status: <input type="checkbox" name="status" value="1" /> 1
<input type="checkbox" name="status" value="2" /> 2
</div>
</form></code></pre>
</div>
</div>
</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.