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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
151,407 | How to get an X11 Window from a Process ID? | <p>Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works.</p>
<p>Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance.</p>
<p>I have the process ID of each instance, how can I find the X11 Window from that ?</p>
<hr>
<p><strong>UPDATE</strong> - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community.</p>
<p>Unfortunately Open Office does not seem to set the _NET_WM_PID property so this doesn't ultimately solve my problem but it does answer the question.</p>
<pre><code>// Attempt to identify a window by name or attribute.
// by Adam Pierce <[email protected]>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <iostream>
#include <list>
using namespace std;
class WindowsMatchingPid
{
public:
WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid)
: _display(display)
, _pid(pid)
{
// Get the PID property atom.
_atomPID = XInternAtom(display, "_NET_WM_PID", True);
if(_atomPID == None)
{
cout << "No such atom" << endl;
return;
}
search(wRoot);
}
const list<Window> &result() const { return _result; }
private:
unsigned long _pid;
Atom _atomPID;
Display *_display;
list<Window> _result;
void search(Window w)
{
// Get the PID for the current Window.
Atom type;
int format;
unsigned long nItems;
unsigned long bytesAfter;
unsigned char *propPID = 0;
if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL,
&type, &format, &nItems, &bytesAfter, &propPID))
{
if(propPID != 0)
{
// If the PID matches, add this window to the result set.
if(_pid == *((unsigned long *)propPID))
_result.push_back(w);
XFree(propPID);
}
}
// Recurse into child windows.
Window wRoot;
Window wParent;
Window *wChild;
unsigned nChildren;
if(0 != XQueryTree(_display, w, &wRoot, &wParent, &wChild, &nChildren))
{
for(unsigned i = 0; i < nChildren; i++)
search(wChild[i]);
}
}
};
int main(int argc, char **argv)
{
if(argc < 2)
return 1;
int pid = atoi(argv[1]);
cout << "Searching for windows associated with PID " << pid << endl;
// Start with the root window.
Display *display = XOpenDisplay(0);
WindowsMatchingPid match(display, XDefaultRootWindow(display), pid);
// Print the result.
const list<Window> &result = match.result();
for(list<Window>::const_iterator it = result.begin(); it != result.end(); it++)
cout << "Window #" << (unsigned long)(*it) << endl;
return 0;
}
</code></pre> | 151,542 | 8 | 2 | null | 2008-09-30 01:23:59.777 UTC | 31 | 2019-04-30 13:14:39.24 UTC | 2008-09-30 06:40:25.383 UTC | Adam Pierce | 5,324 | Adam Pierce | 5,324 | null | 1 | 61 | x11 | 45,513 | <p>The only way I know to do this is to traverse the tree of windows until you find what you're looking for. Traversing isn't hard (just see what xwininfo -root -tree does by looking at xwininfo.c if you need an example).
<p>
But how do you identify the window you are looking for? <b>Some</b> applications set a window property called _NET_WM_PID.
<p>
I believe that OpenOffice <em>is</em> one of the applications that sets that property (as do most Gnome apps), so you're in luck.</p> |
1,066,933 | How to extract top-level domain name (TLD) from URL | <p>how would you extract the domain name from a URL, excluding any subdomains?</p>
<p>My initial simplistic attempt was:</p>
<pre><code>'.'.join(urlparse.urlparse(url).netloc.split('.')[-2:])
</code></pre>
<p>This works for <a href="http://www.foo.com" rel="noreferrer">http://www.foo.com</a>, but not <a href="http://www.foo.com.au" rel="noreferrer">http://www.foo.com.au</a>.
Is there a way to do this properly without using special knowledge about valid TLDs (Top Level Domains) or country codes (because they change).</p>
<p>thanks</p> | 1,066,947 | 8 | 3 | null | 2009-07-01 01:42:03.947 UTC | 32 | 2021-07-06 17:20:54.087 UTC | 2015-01-22 04:26:42.01 UTC | null | 8,331 | null | 105,066 | null | 1 | 65 | python|url|parsing|dns|extract | 81,358 | <p>No, there is no "intrinsic" way of knowing that (e.g.) <code>zap.co.it</code> is a subdomain (because Italy's registrar DOES sell domains such as <code>co.it</code>) while <code>zap.co.uk</code> <em>isn't</em> (because the UK's registrar DOESN'T sell domains such as <code>co.uk</code>, but only like <code>zap.co.uk</code>).</p>
<p>You'll just have to use an auxiliary table (or online source) to tell you which TLD's behave peculiarly like UK's and Australia's -- there's no way of divining that from just staring at the string without such extra semantic knowledge (of course it can change eventually, but if you can find a good online source that source will also change accordingly, one hopes!-).</p> |
862,804 | How to improve my math skills to become a better programmer | <p>Even though I consider myself one of the better programmers on my CompSci course, I am fascinated by people who are really good at math. I have to say whenever I had a math-type assignment or exam my approach has been very formulaic, i.e. if I encounter a problem that looks like A I must use method B and the result should look like C, or else I made a mistake. I only really know how to solve the problems I revised.</p>
<p>I'd really like to devote some time this summer to understand mathematical problems and their solutions better in order to dive deeper into fields of algorithmics and computational complexity.</p>
<p>Any tips?</p> | 862,825 | 10 | 0 | null | 2009-05-14 11:24:34.823 UTC | 24 | 2013-01-20 14:12:15.587 UTC | 2009-05-14 11:37:50.937 UTC | null | 99,022 | null | 99,022 | null | 1 | 9 | math | 12,954 | <p>It sounds like you have decent math skills -- you understand the mechanics and maybe a little bit of the intuition behind what you've learned -- but that you're a little short on <strong>good problem-solving skills</strong>, especially since you say "I only really know how to solve the problems I [previously encountered]".</p>
<p>To fix that, I'd take a look at <a href="http://projecteuler.net/" rel="noreferrer"><strong>Project Euler</strong></a>. There is definitely no prescribed way to solve these problems, and they often require a synthesis of multiple knowledge areas to tackle each one successfully. You'll have your cake and eat it too -- becoming a better programmer/mathematician <em>and</em> a better general problem-solver, by seeing how to bring many things to bear against a particular problem. And you'll gain deeper insights into how things that seem completely different can actually fit together in a unified whole. (This is particularly true of many areas of math.)</p>
<p>Finally, kudos to you for your desire to become a better practitioner of your craft! If everyone displayed the same level of ambition, I can't help thinking that software in general would be a lot better.</p> |
122,316 | Template Constraints C++ | <p>In C# we can define a generic type that imposes constraints on the types that can be used as the generic parameter. The following example illustrates the usage of generic constraints:</p>
<pre><code>interface IFoo
{
}
class Foo<T> where T : IFoo
{
}
class Bar : IFoo
{
}
class Simpson
{
}
class Program
{
static void Main(string[] args)
{
Foo<Bar> a = new Foo<Bar>();
Foo<Simpson> b = new Foo<Simpson>(); // error CS0309
}
}
</code></pre>
<p>Is there a way we can impose constraints for template parameters in C++.</p>
<hr>
<p>C++0x has native support for this but I am talking about current standard C++.</p> | 122,368 | 10 | 1 | null | 2008-09-23 17:03:14.05 UTC | 27 | 2022-02-13 12:41:29.493 UTC | 2008-09-29 15:29:25.557 UTC | Leon Timmermans | 4,727 | Jorge Ferreira | 6,508 | null | 1 | 82 | c++|templates|constraints | 57,570 | <p>As someone else has mentioned, C++0x is getting this built into the language. Until then, I'd recommend <a href="http://en.wikipedia.org/wiki/Bjarne_Stroustrup" rel="noreferrer">Bjarne Stroustrup</a>'s <a href="http://www.stroustrup.com/bs_faq2.html#constraints" rel="noreferrer">suggestions for template constraints</a>.</p>
<p>Edit: <a href="http://boost.org" rel="noreferrer">Boost</a> also has an <a href="http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm" rel="noreferrer">alternative of its own</a>.</p>
<p>Edit2: Looks like <a href="http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=441" rel="noreferrer">concepts have been removed from C++0x</a>.</p> |
270,445 | Maven compile with multiple src directories | <p>Is there a way to compile multiple java source directories in a single maven project? </p> | 270,490 | 10 | 0 | null | 2008-11-06 21:50:12.637 UTC | 65 | 2021-12-12 22:06:46.983 UTC | null | null | null | sal | 13,753 | null | 1 | 210 | java|maven-2 | 186,323 | <p>You can add a new source directory with build-helper:</p>
<pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre> |
179,723 | What is the best way of implementing assertion checking in C++? | <p>By that I mean, what do I need to do to have useful assertions in my code?</p>
<p>MFC is quite easy, i just use ASSERT(something).</p>
<p>What's the non-MFC way?</p>
<p><strong>Edit:</strong> Is it possible to stop assert breaking in assert.c rather than than my file which called assert()?</p>
<p><strong>Edit:</strong> What's the difference between <code><assert.h></code> & <code><cassert></code>?</p>
<p><strong>Accepted Answer:</strong> Loads of great answers in this post, I wish I could accept more than one answer (or someone would combine them all). So answer gets awarded to Ferruccio (for first answer).</p> | 179,733 | 11 | 2 | null | 2008-10-07 18:21:18.413 UTC | 10 | 2014-11-20 07:40:24.743 UTC | 2008-10-08 08:07:21.197 UTC | Mark Ingram | 986 | Mark Ingram | 986 | null | 1 | 21 | c++|debugging|assert|debugbreak | 16,990 | <pre><code>#include <cassert>
assert(something);
</code></pre>
<p>and for compile-time checking, Boost's static asserts are pretty useful:</p>
<pre><code>#include <boost/static_assert.hpp>
BOOST_STATIC_ASSERT(sizeof(int) == 4); // compile fails if ints aren't 32-bit
</code></pre> |
140,750 | Is it possible to compile .NET IL code to machine code? | <p>I would like to distribute my .NET programs without the .NET framework. Is it possible to compile a .NET program to machine code?</p> | 140,777 | 12 | 0 | null | 2008-09-26 17:18:32.84 UTC | 11 | 2014-05-01 07:12:01.067 UTC | 2008-09-26 19:23:45.317 UTC | Dima | 13,313 | null | 13,301 | null | 1 | 30 | .net|visual-studio|compiler-construction | 17,897 | <p>Yes, you can precompile using Ngen.exe, however this does not remove the CLR dependence.</p>
<p>You must still ship the IL assemblies as well, the only benefit of Ngen is that your application can start without invoking the JIT, so you get a real fast startup time. </p>
<p>According to CLR Via C#:</p>
<blockquote>
<p>Also, assemblies precompiled using
Ngen are usually slower than JIT'ed
assemblies because the JIT compiler
can optimize to the targets machine
(32-bit? 64-bit? Special registers?
etc), while NGEN will just produce a
baseline compilation.</p>
</blockquote>
<p>EDIT:</p>
<p>There is some debate on the above info from CLR Via C#, as some say that you are required to run Ngen on the target machine only as part of the install process.</p> |
459,554 | How can I tell if another instance of my program is already running? | <p>How do i tell if one instance of my program is running?
I thought I could do this with a data file but it would just be messy :(</p>
<p>I want to do this as I only want 1 instance to ever be open at one point.</p> | 460,480 | 12 | 0 | null | 2009-01-19 23:07:20.677 UTC | 11 | 2018-10-10 16:56:19.243 UTC | 2013-01-21 23:41:34.583 UTC | Arthur | 6,244 | Arthur | 53,915 | null | 1 | 32 | delphi|persistence|mutex|instance|semaphore | 24,450 | <p>You can create a Semaphore and stop execution (put the code into your *.dpr file) and bring you running application to the screen.</p>
<pre><code>var
Semafor: THandle;
begin
{ Don't start twice ... if already running bring this instance to front }
Semafor := CreateSemaphore(nil, 0, 1, 'MY_APPLICATION_IS_RUNNING');
if ((Semafor <> 0) and { application is already running }
(GetLastError = ERROR_ALREADY_EXISTS)) then
begin
RestoreWindow('TMyApplication');
CloseHandle(Semafor);
Halt;
end;
Application.CreateForm(....);
Application.Initialize;
Application.Run;
CloseHandle(Semafor);
end;
</code></pre>
<p><strong>EDIT</strong> (added the <code>RestoreWindow</code> method):</p>
<p>The <code>aFormName</code> is the name of your main form class in your application.</p>
<pre><code>procedure RestoreWindow(aFormName: string);
var
Wnd,
App: HWND;
begin
Wnd := FindWindow(PChar(aFormName), nil);
if (Wnd <> 0) then
begin { Set Window to foreground }
App := GetWindowLong(Wnd, GWL_HWNDPARENT);
if IsIconic(App) then
ShowWindow(App, SW_RESTORE);
SetForegroundwindow(App);
end;
end;
</code></pre> |
199,470 | What's the main difference between int.Parse() and Convert.ToInt32 | <ul>
<li>What is the main difference between <code>int.Parse()</code> and <code>Convert.ToInt32()</code>?</li>
<li>Which one is to be preferred</li>
</ul> | 199,484 | 13 | 0 | null | 2008-10-13 23:48:33.857 UTC | 121 | 2019-03-27 15:06:43.867 UTC | 2017-09-10 04:35:32.57 UTC | null | 1,033,581 | jazzrai | 14,752 | null | 1 | 560 | c# | 332,230 | <ul>
<li><p>If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use <a href="http://msdn.microsoft.com/en-us/library/system.int32.parse.aspx" rel="noreferrer"><strong><code>Int32.Parse()</code></strong></a>.</p>
</li>
<li><p>If you're collecting input from a user, you'd generally use <a href="http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx" rel="noreferrer"><strong><code>Int32.TryParse()</code></strong></a>, since it allows you more fine-grained control over the situation when the user enters invalid input.</p>
</li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/System.Convert.ToInt32.aspx" rel="noreferrer"><strong><code>Convert.ToInt32()</code></strong></a> takes an object as its argument. (See Chris S's answer for how it works)</p>
<p><code>Convert.ToInt32()</code> also does not throw <code>ArgumentNullException</code> when its argument is null the way <code>Int32.Parse()</code> does. That also means that <code>Convert.ToInt32()</code> is probably a wee bit slower than <code>Int32.Parse()</code>, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.</p>
</li>
</ul> |
326,450 | Unit testing with Entity Framework | <p>I want to test my Entities that are built using Entity Framework.
My concern is that using Entity Framework means directly working with data source.
So any ideas how to unit testing Entity Framework based components?</p> | 3,004,576 | 13 | 1 | null | 2008-11-28 19:01:08.177 UTC | 20 | 2014-02-05 00:12:58.65 UTC | 2010-12-10 07:16:14.743 UTC | null | 23,354 | mosessaur | 18,908 | null | 1 | 71 | linq|unit-testing|entity-framework | 27,168 | <p>For Enity Framework 4, this looks promising: <a href="http://msdn.microsoft.com/en-us/ff714955.aspx" rel="noreferrer">Testability and Entity Framework 4.0</a></p> |
55,054 | How to capitalize the first letter of each word in a string in SQL Server | <p>What’s the best way to capitalize the first letter of each word in a string in SQL Server.</p> | 55,057 | 16 | 2 | null | 2008-09-10 19:07:08.363 UTC | 27 | 2022-07-27 02:03:27.61 UTC | 2022-07-27 02:03:27.61 UTC | null | 7,758,804 | null | 5,170 | null | 1 | 62 | sql|sql-server|string | 96,685 | <p>From <a href="http://www.sql-server-helper.com/functions/initcap.aspx" rel="noreferrer">http://www.sql-server-helper.com/functions/initcap.aspx</a></p>
<pre><code>CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @PrevChar CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 1
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InputString, @Index - 1, 1)
END
IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
END
SET @Index = @Index + 1
END
RETURN @OutputString
END
GO
</code></pre>
<p>There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."): </p>
<p><a href="http://www.devx.com/tips/Tip/17608" rel="noreferrer">http://www.devx.com/tips/Tip/17608</a></p> |
454,681 | How to keep the console window open in Visual C++? | <p>I'm starting out in Visual C++ and I'd like to know how to keep the console window.</p>
<p>For instance this would be a typical "hello world" application: </p>
<pre><code>int _tmain(int argc, _TCHAR* argv[])
{
cout << "Hello World";
return 0;
}
</code></pre>
<p>What's the line I'm missing?</p> | 1,152,873 | 23 | 10 | null | 2009-01-18 05:00:22.623 UTC | 64 | 2022-09-23 22:04:32.363 UTC | 2015-05-27 14:57:48.863 UTC | null | 15,168 | Raúl Roa | 53,797 | null | 1 | 207 | visual-c++|console | 302,592 | <p>Start the project with <kbd>Ctrl</kbd>+<kbd>F5</kbd> instead of just <kbd>F5</kbd>.</p>
<p>The console window will now stay open with the <code>Press any key to continue . . .</code> message after the program exits.</p>
<p>Note that this requires the <code>Console (/SUBSYSTEM:CONSOLE)</code> linker option, which you can enable as follows:</p>
<ol>
<li>Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.</li>
<li>Right click on the 'hello" (or whatever your project name is.)</li>
<li>Choose "Properties" from the context menu.</li>
<li>Choose Configuration Properties>Linker>System.</li>
<li>For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.</li>
<li>Choose "Console (/SUBSYSTEM:CONSOLE)"</li>
<li>Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)</li>
</ol>
<p>CTRL-F5 and the subsystem hints work together; they are not separate options.</p>
<p>(Courtesy of DJMorreTX from <a href="http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6</a>)</p> |
2,056 | What are MVP and MVC and what is the difference? | <p>When looking beyond the <a href="https://en.wikipedia.org/wiki/Rapid_application_development" rel="noreferrer">RAD</a> (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">Model-View-Controller</a>, <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="noreferrer">Model-View-Presenter</a> and <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel" rel="noreferrer">Model-View-ViewModel</a>. My question has three parts to it:</p>
<ol>
<li>What issues do these patterns address?</li>
<li>How are they similar?</li>
<li>How are they different?</li>
</ol> | 101,561 | 24 | 5 | null | 2008-08-05 10:06:33.02 UTC | 1,358 | 2022-01-27 06:54:23.653 UTC | 2020-08-29 01:23:49.18 UTC | Steve M | 1,595,451 | null | 358 | null | 1 | 2,319 | user-interface|model-view-controller|design-patterns|terminology|mvp | 550,536 | <h2>Model-View-Presenter</h2>
<p>In <strong>MVP</strong>, the Presenter contains the UI business logic for the View. All invocations from the View delegate directly to the Presenter. The Presenter is also decoupled directly from the View and talks to it through an interface. This is to allow mocking of the View in a unit test. One common attribute of MVP is that there has to be a lot of two-way dispatching. For example, when someone clicks the "Save" button, the event handler delegates to the Presenter's "OnSave" method. Once the save is completed, the Presenter will then call back the View through its interface so that the View can display that the save has completed.</p>
<p>MVP tends to be a very natural pattern for achieving separated presentation in WebForms. The reason is that the View is always created first by the ASP.NET runtime. You can <a href="https://web.archive.org/web/20071211153445/http://www.codeplex.com/websf/Wiki/View.aspx?title=MVPDocumentation" rel="noreferrer">find out more about both variants</a>.</p>
<h3>Two primary variations</h3>
<p><strong>Passive View:</strong> The View is as dumb as possible and contains almost zero logic. A Presenter is a middle man that talks to the View and the Model. The View and Model are completely shielded from one another. The Model may raise events, but the Presenter subscribes to them for updating the View. In Passive View there is no direct data binding, instead, the View exposes setter properties that the Presenter uses to set the data. All state is managed in the Presenter and not the View.</p>
<ul>
<li>Pro: maximum testability surface; clean separation of the View and Model</li>
<li>Con: more work (for example all the setter properties) as you are doing all the data binding yourself.</li>
</ul>
<p><strong>Supervising Controller:</strong> The Presenter handles user gestures. The View binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation, etc.</p>
<ul>
<li>Pro: by leveraging data binding the amount of code is reduced.</li>
<li>Con: there's a less testable surface (because of data binding), and there's less encapsulation in the View since it talks directly to the Model.</li>
</ul>
<h2>Model-View-Controller</h2>
<p>In the <strong>MVC</strong>, the Controller is responsible for determining which View to display in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View correlates with a call to a Controller along with an action. In the web, each action involves a call to a URL on the other side of which there is a Controller who responds. Once that Controller has completed its processing, it will return the correct View. The sequence continues in that manner throughout the life of the application:</p>
<pre>
Action in the View
-> Call to Controller
-> Controller Logic
-> Controller returns the View.
</pre>
<p>One other big difference about MVC is that the View does not directly bind to the Model. The view simply renders and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. This is contrary to MVP where it is absolutely necessary because, if the View does not delegate to the Presenter, it will never get called.</p>
<h2>Presentation Model</h2>
<p>One other pattern to look at is the <strong>Presentation Model</strong> pattern. In this pattern, there is no Presenter. Instead, the View binds directly to a Presentation Model. The Presentation Model is a Model crafted specifically for the View. This means this Model can expose properties that one would never put on a domain model as it would be a violation of separation-of-concerns. In this case, the Presentation Model binds to the domain model and may subscribe to events coming from that Model. The View then subscribes to events coming from the Presentation Model and updates itself accordingly. The Presentation Model can expose commands which the view uses for invoking actions. The advantage of this approach is that you can essentially remove the code-behind altogether as the PM completely encapsulates all of the behavior for the view. This pattern is a very strong candidate for use in WPF applications and is also called <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="noreferrer">Model-View-ViewModel</a>.</p>
<p>There is a <a href="http://msdn.microsoft.com/en-us/library/ff921080.aspx" rel="noreferrer">MSDN article about the Presentation Model</a> and a section in the <a href="http://msdn.microsoft.com/en-us/library/cc707819.aspx" rel="noreferrer">Composite Application Guidance for WPF</a> (former Prism) about <a href="http://msdn.microsoft.com/en-us/library/cc707862.aspx" rel="noreferrer">Separated Presentation Patterns</a></p> |
6,994,947 | How to replace a string in an existing file in Perl | <p>I want to replace the word "blue" with "red" in all text files named as 1_classification.dat, 2_classification.dat and so on. I want to edit the same file so I tried the following code, but it does not work. Where am I going wrong?</p>
<pre><code>@files = glob("*_classification.dat");
foreach my $file (@files)
{
open(IN,$file) or die $!;
<IN>;
while(<IN>)
{
$_ = '~s/blue/red/g';
print IN $file;
}
close(IN)
}
</code></pre> | 6,995,010 | 4 | 0 | null | 2011-08-09 10:45:25.16 UTC | 19 | 2021-04-28 14:38:35.267 UTC | 2021-04-28 14:29:25.33 UTC | null | 63,550 | null | 831,579 | null | 1 | 77 | regex|perl | 136,226 | <p>Use a one-liner:</p>
<pre><code>$ perl -pi.bak -e 's/blue/red/g' *_classification.dat
</code></pre>
<hr />
<p><strong>Explanation</strong></p>
<ul>
<li><code>-p</code> processes, then prints <code><></code> line by line</li>
<li><code>-i</code> activates in-place editing. Files are backed up using the <code>.bak</code> extension</li>
<li>The regex substitution acts on the implicit variable, which are the contents of the file, line-by-line</li>
</ul> |
6,777,734 | How do I add a auto_increment primary key in SQL Server database? | <p>I have a table set up that currently has no primary key. All I need to do is add a <code>primary key, no null, auto_increment</code>.</p>
<p>I'm working with a <code>Microsoft SQL Server</code> database. I understand that it can't be done in a single command but every command I try keeps returning syntax errors.</p>
<p>edit ---------------</p>
<p>I have created the primary key and even set it as not null. However, I can't set up the <code>auto_increment</code>.</p>
<p>I've tried:</p>
<pre><code>ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment
ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment
</code></pre>
<p>I'm using <code>NVARCHAR</code> because it wouldn't let me set <code>NOT NULL</code> under int</p> | 6,777,807 | 6 | 5 | null | 2011-07-21 14:31:38.267 UTC | 14 | 2019-09-24 01:59:44.697 UTC | 2018-03-22 07:25:38.063 UTC | null | 3,876,565 | null | 249,316 | null | 1 | 60 | sql|sql-server|auto-increment | 329,342 | <p>It can be done in a single command. You need to set the IDENTITY property for "auto number":</p>
<pre><code>ALTER TABLE MyTable ADD mytableID int NOT NULL IDENTITY (1,1) PRIMARY KEY
</code></pre>
<p>More precisely, to set a named table level constraint:</p>
<pre><code>ALTER TABLE MyTable
ADD MytableID int NOT NULL IDENTITY (1,1),
CONSTRAINT PK_MyTable PRIMARY KEY CLUSTERED (MyTableID)
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/ms187742.aspx" rel="noreferrer">ALTER TABLE and IDENTITY</a> on MSDN</p> |
6,654,849 | How to split a string in bash delimited by tab | <p>I'm trying to split a tab delimitted field in bash.</p>
<p>I am aware of this answer: <a href="https://stackoverflow.com/questions/3162385/how-to-split-a-string-in-shell-and-get-the-last-field">how to split a string in shell and get the last field</a></p>
<p>But that does not answer for a tab character.</p>
<p>I want to do get the part of a string before the tab character, so I'm doing this:</p>
<pre><code>x=`head -1 my-file.txt`
echo ${x%\t*}
</code></pre>
<p>But the \t is matching on the letter 't' and not on a tab. What is the best way to do this?</p>
<p>Thanks</p> | 6,655,669 | 7 | 1 | null | 2011-07-11 18:39:35.46 UTC | 8 | 2021-07-08 23:49:38.75 UTC | 2017-05-23 11:47:11.987 UTC | null | -1 | null | 107,083 | null | 1 | 42 | bash|string-split | 105,869 | <p>If your file look something like this (with tab as separator):</p>
<pre><code>1st-field 2nd-field
</code></pre>
<p>you can use <code>cut</code> to extract the first field (operates on tab by default):</p>
<pre><code>$ cut -f1 input
1st-field
</code></pre>
<p>If you're using <code>awk</code>, there is no need to use <code>tail</code> to get the last line, changing the input to:</p>
<pre><code>1:1st-field 2nd-field
2:1st-field 2nd-field
3:1st-field 2nd-field
4:1st-field 2nd-field
5:1st-field 2nd-field
6:1st-field 2nd-field
7:1st-field 2nd-field
8:1st-field 2nd-field
9:1st-field 2nd-field
10:1st-field 2nd-field
</code></pre>
<p>Solution using awk:</p>
<pre><code>$ awk 'END {print $1}' input
10:1st-field
</code></pre>
<p>Pure bash-solution:</p>
<pre><code>#!/bin/bash
while read a b;do last=$a; done < input
echo $last
</code></pre>
<p>outputs:</p>
<pre><code>$ ./tab.sh
10:1st-field
</code></pre>
<p>Lastly, a solution using <code>sed</code></p>
<pre><code>$ sed '$s/\(^[^\t]*\).*$/\1/' input
10:1st-field
</code></pre>
<p>here, <code>$</code> is the range operator; i.e. operate on the last line only.</p>
<p>For your original question, use a literal tab, i.e.</p>
<pre><code>x="1st-field 2nd-field"
echo ${x% *}
</code></pre>
<p>outputs:</p>
<pre><code>1st-field
</code></pre> |
6,647,296 | How to check if an integer can be divided by 3 | <p>How to check if my integer can be divided by 3 as below:</p>
<pre><code>for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
</code></pre> | 6,647,324 | 8 | 1 | null | 2011-07-11 08:01:13.217 UTC | 6 | 2011-07-11 09:01:43.23 UTC | null | null | null | null | 740,018 | null | 1 | 27 | java | 87,314 | <p>Use the modulo operator. </p>
<pre><code>if(i % 3 == 0)
</code></pre>
<p>Also see <a href="http://en.wikipedia.org/wiki/Modulo_operation" rel="noreferrer">Modulo operation at Wikipedia</a></p> |
6,711,610 | How to set transform origin in SVG | <p>I need to resize and rotate certain elements in SVG document using javascript. The problem is, by default, it always applies the transform around the origin at <code>(0, 0)</code> – top left.</p>
<p>How can I re-define this transform anchor point?</p>
<p>I tried using the <code>transform-origin</code> attribute, but it does not affect anything. </p>
<p>This is how I did it:</p>
<pre><code>svg.getDocumentById('someId').setAttribute('transform-origin', '75 240');
</code></pre>
<p>It does not seem to set the pivotal point to the point I specified although I can see in Firefox that the attribute is correctly set. I tried things like <code>center bottom</code> and <code>50% 100%</code> with and without parenthesis. Nothing worked so far.</p>
<p>Can anyone help?</p> | 6,714,140 | 8 | 2 | null | 2011-07-15 18:29:28.093 UTC | 47 | 2022-01-23 16:17:55.417 UTC | 2016-10-18 12:36:55.983 UTC | null | 2,337,769 | null | 657,230 | null | 1 | 122 | svg|coordinate-transformation | 116,512 | <p>To rotate use <code>transform="rotate(deg, cx, cy)"</code>, where deg is the degree you want to rotate and (cx, cy) define the centre of rotation.</p>
<p>For scaling/resizing, you have to translate by (-cx, -cy), then scale and then translate back to (cx, cy). You can do this with a <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform" rel="noreferrer">matrix transform</a>:</p>
<pre><code>transform="matrix(sx, 0, 0, sy, cx-sx*cx, cy-sy*cy)"
</code></pre>
<p>Where sx is the scaling factor in the x-axis, sy in the y-axis.</p> |
7,002,429 | How can I extract all values from a dictionary in Python? | <p>I have a dictionary <code>d = {1:-0.3246, 2:-0.9185, 3:-3985, ...}</code>.</p>
<p>How do I extract all of the values of <code>d</code> into a list <code>l</code>?</p> | 7,002,449 | 14 | 0 | null | 2011-08-09 20:22:14.28 UTC | 43 | 2022-04-25 07:48:04.787 UTC | 2014-07-03 23:15:00.623 UTC | null | 562,769 | null | 865,976 | null | 1 | 233 | python|dictionary|extract | 566,379 | <p>If you only need the dictionary keys <code>1</code>, <code>2</code>, and <code>3</code> use: <code>your_dict.keys()</code>.</p>
<p>If you only need the dictionary values <code>-0.3246</code>, <code>-0.9185</code>, and <code>-3985</code> use: <code>your_dict.values()</code>.</p>
<p>If you want both keys and values use: <code>your_dict.items()</code> which returns a list of tuples <code>[(key1, value1), (key2, value2), ...]</code>.</p> |
41,562,288 | Hive - month and year from timestamp column | <p>Hi I am trying to extract the month and year part of a timestamp column in hive using the below query</p>
<pre><code>select from_unixtime(unix_timestamp(upd_gmt_ts,'yyyyMM')) from abc.test;
</code></pre>
<p>The output looks like 2016-05-20 01:08:48</p>
<p>the desired output should be 201605</p>
<p>Appreciate any suggestions.</p> | 41,562,738 | 4 | 1 | null | 2017-01-10 06:18:05.803 UTC | 5 | 2017-10-29 14:59:28.833 UTC | 2017-01-10 07:00:55.273 UTC | null | 1,592,191 | null | 1,939,183 | null | 1 | 14 | date|hadoop|hive|sql-timestamp | 83,697 | <p>I'd prefer to use Hive <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions" rel="noreferrer">date_format()</a> (as of Hive 1.2.0). It support Java <a href="https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a> patterns.</p>
<p><code>date_format()</code> accepts <code>date/timestamp/string</code>. So your final query will be</p>
<pre><code>select date_format(upd_gmt_ts,'yyyyMM') from abc.test;
</code></pre>
<p><strong>Edit:</strong></p>
<blockquote>
<p><code>SimpleDateFormat</code> acceptable patterns examples.</p>
<p><img src="https://i.stack.imgur.com/CmxyT.png" alt="enter image description here" /></p>
</blockquote> |
15,949,855 | AngularJS remove attributes | <p>I have a directive that replaces my custom tag with some regular HTML.
There are some attributes that I'd like to remove. For example, given the syntax </p>
<pre><code><ui mybutton width="30"></mybutton>
</code></pre>
<p>my directive transforms it into </p>
<pre><code><div width="30" class="btn">bla bla </div>
</code></pre>
<p>I want to remove that <code>"width=30"</code> and add <code>style="width:{{old width value here}}"</code></p>
<p>I've been experimenting with the compile and link function. Should I do that in the compile or in the link function?</p>
<p>I thought I had to do it in the compile function because I want to make a modification in the template.</p>
<p>See it live in <a href="http://jsfiddle.net/WptGC/2/">http://jsfiddle.net/WptGC/2/</a> <strong>WARNING: your browser might hang!</strong>
See it live and safely <a href="http://jsfiddle.net/WptGC/3/">http://jsfiddle.net/WptGC/3/</a> the code that makes everything crash is commented.</p>
<pre><code>.directive('mybutton', function($compile) {
return {
restrict: 'A',
//transclude: true,
template: '<div class="this is my subscreen div" style="width:{{width}}"></div>',
replace: false,
/*scope: {
width: '@',
height: '@',
x: '@',
y: '@'
},*/
compile: function($tElement, $tAttrs) {
console.log("subscreen template attrs:");
console.log($tAttrs);
var el = $tElement[0];
//el.getAttribute('width');
var stylewidth = el.getAttribute('width');
el.removeAttribute('width');
return function(scope) {
$compile(el)(scope);
}
}
}
})
</code></pre>
<p>I'm just getting a strange loop (that console.log shows up a few thousand times)</p> | 15,950,161 | 1 | 1 | null | 2013-04-11 13:18:47.78 UTC | 5 | 2013-04-11 15:20:38.71 UTC | null | null | null | null | 1,821,749 | null | 1 | 18 | angularjs|angularjs-directive | 47,472 | <p>Unless I'm missing some other requirement you should just be able to use isolate scope and a template like:</p>
<p><a href="http://jsfiddle.net/WptGC/6/">http://jsfiddle.net/WptGC/6/</a></p>
<pre><code>app.directive('backbutton',function(){
return {
restrict: 'A',
replace:true,
scope: {
x: '@',
y: '@'
},
template:'<button style="width: {{x}}px; height: {{y}}px">A back-button template</button>',
link: function (scope, element, attrs) {
element.removeAttr('x').removeAttr('y');
}
}
});
</code></pre> |
15,526,546 | Confusion about node.js internal asynchronous I/O mechanism | <ol>
<li>I have learned that node.js use libeio internally to perform async <strong>file</strong> I/O, with thread pool, on *nix platform, am I right? </li>
<li>What about async <strong>network</strong> I/O? Is it done by libev? Is there also a thread pool? </li>
<li>If there is thread pool inside, how could it be more efficient than traditional one-thread-per-request model? And is it one thread per I/O request?</li>
<li>And what's the mechanism on windows? I know it's done by IOCP, and there's a kernel level thread pool, right?</li>
<li>Why linux doesn't have a native completely AIO mechanism like windows IOCP yet? Will it have in future?</li>
</ol>
<p>Update according to changchang's answer: </p>
<ol>
<li>I took a quick view at the <a href="https://github.com/libuv/libuv/blob/780c08a63efb65aed65da57c36f1c5b10f25cc1d/src/threadpool.c" rel="nofollow noreferrer">source code</a> @changchang have given, found that the default thread pool size can be reset by <strong>UV_THREADPOOL_SIZE</strong>, I'm wondering in which case this will be used? </li>
<li>I also found getaddrinfo use this thread pool, is there any more except fs? And if all sync jobs will be done in this thread pool, is the default size '4' enough? </li>
<li>As my understanding now, there will be 6 basic threads in node.js process: 1 V8 thread(event loop, where user javascript codes runs), 1 libuv event loop, and 4 in thread pool, am I right? </li>
<li><p>And how can I see these threads in my shell(Ubuntu)? I use <strong>ps -eLf | grep node | grep -v grep</strong> only saw two:</p>
<p>root 16148 7492 16148 0 2 20:43 pts/26 00:00:00 ./bin/node /home/aaron/workspace/test.js<br>
root 16148 7492 16149 0 2 20:43 pts/26 00:00:00 ./bin/node /home/aaron/workspace/test.js</p></li>
</ol> | 15,542,725 | 2 | 4 | null | 2013-03-20 14:36:09.057 UTC | 19 | 2019-11-19 20:24:13.12 UTC | 2019-11-19 20:24:13.12 UTC | null | 5,885,013 | null | 1,246,718 | null | 1 | 25 | javascript|linux|node.js|io|libuv | 7,584 | <ol>
<li><p>First of all, <code>libuv</code> has removed the <code>libeio</code> from it. But it does perform async file I/O with a thread pool like <code>libeio</code> just as you mentioned.</p></li>
<li><p><code>libuv</code> also removes <code>libev</code>. It does the async network I/O based on the async I/O interfaces in different platforms, such as <code>epoll</code>, <code>kqueue</code> and <code>IOCP</code>, without a thread pool. There is a event loop which runs on the main thread of <code>uv</code> which polls the I/O events and processes them.</p></li>
<li><p>The thread pool inside <code>libuv</code> is a fixed size thread pool (<a href="http://docs.libuv.org/en/v1.x/threadpool.html" rel="noreferrer">4 in uinx like system</a>). It performs a task queue role and avoids the exhaustion of the system resources by generating threads indefinitely when the requests increase. </p></li>
</ol> |
15,492,717 | Get Fragment dynamically attached to <FrameLayout>? | <p>Well, i got a simple <code><FrameLayout></code>:</p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/FragmentContainer"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</code></pre>
<p>Then in my code, i added a Fragment to it:</p>
<pre><code>FragClass aFrag = new FragClass();
getSupportFragmentManager().beginTransaction()
.replace(R.id.FragmentContainer, aFrag).commit();
</code></pre>
<p>And somewhere else in my code, i want to get that <code>FragClass (extends Fragment)</code> object from the ID <code>R.id.FragmentContainer</code>.</p>
<p>i have tried</p>
<pre><code>((ViewGroup) findViewById(R.id.FragmentContainer)).getChildAt(0)
</code></pre>
<p>or</p>
<pre><code>((FrameLayout) findViewById(R.id.FragmentContainer)).getChildAt(0)
</code></pre>
<p>but they are returning the <code>View</code>, instead of the <code>Fragment</code> attached to it.</p>
<p><em>i know i can keep the variable <code>aFrag</code> somewhere, so i do not need to find it again. But i believe there should be a way to retieve it.</em></p> | 15,522,479 | 1 | 4 | null | 2013-03-19 06:17:48.983 UTC | 10 | 2019-10-15 00:34:47.953 UTC | null | null | null | null | 1,884,546 | null | 1 | 40 | android|android-layout|android-fragments|android-framelayout | 37,995 | <p>Let me wrap it up by a full answer :)</p>
<p>In this case, the dynamically added <code>Fragment</code> uses the ID of the container <code>View</code> (<code>ViewGroup</code>).</p>
<p>ref: <a href="http://developer.android.com/guide/components/fragments.html#Adding" rel="noreferrer">http://developer.android.com/guide/components/fragments.html#Adding</a></p>
<blockquote>
<p>Note: Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:</p>
<ul>
<li>Supply the android:id attribute with a unique ID.</li>
<li>Supply the android:tag attribute with a unique string.</li>
<li><strong>If you provide neither of the previous two, the system uses the ID of the container view.</strong></li>
</ul>
</blockquote>
<p>It is because it's a <code>Fragment</code> afterall. We have to use <code>getSupportFragmentManager().findFragmentById()</code> to retrieve it, which returns a <code>Fragment</code>, instead of <code>findViewById()</code> which returns a <code>View</code>.</p>
<p>So the answer to this problem would be:</p>
<pre><code>((aFrag) getSupportFragmentManager().findFragmentById(R.id.FragmentContainer))
</code></pre>
<p><em>Thanks to @Luksprog.</em></p> |
15,758,685 | How to write logs in text file when using java.util.logging.Logger | <p>I have a situation in which I want to write all logs created by me into a text file.</p>
<p>We are using java.util.logging.Logger API to generate the logs.</p>
<p>I tried:</p>
<pre><code>private static Logger logger = Logger.getLogger(className.class.getName());
FileHandler fh;
fh = new FileHandler("C:/className.log");
logger.addHandler(fh);
</code></pre>
<p>But still getting my logs on console only.... </p> | 15,758,768 | 10 | 4 | null | 2013-04-02 07:41:17.07 UTC | 60 | 2020-04-03 04:48:49.82 UTC | 2019-01-31 12:19:19.063 UTC | null | 58,848 | null | 1,719,802 | null | 1 | 168 | java|logging | 464,230 | <p>Try this sample. It works for me.</p>
<pre><code>public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
FileHandler fh;
try {
// This block configure the logger with handler and formatter
fh = new FileHandler("C:/temp/test/MyLogFile.log");
logger.addHandler(fh);
SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(formatter);
// the following statement is used to log any messages
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
</code></pre>
<p>Produces the output at MyLogFile.log</p>
<pre><code>Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: My first log
Apr 2, 2013 9:57:08 AM testing.MyLogger main
INFO: Hi How r u?
</code></pre>
<p><strong><em>Edit:</em></strong></p>
<p>To remove the console handler, use</p>
<pre><code>logger.setUseParentHandlers(false);
</code></pre>
<p>since the ConsoleHandler is registered with the parent logger from which all the loggers derive.</p> |
15,551,779 | Open link in new tab or window | <p>Is it possible to open an <code>a href</code> link in a new tab instead of the same tab?</p>
<pre><code><a href="http://your_url_here.html">Link</a>
</code></pre> | 15,551,842 | 4 | 3 | null | 2013-03-21 15:33:40.96 UTC | 147 | 2022-05-19 00:51:15.833 UTC | 2016-09-15 11:14:40.473 UTC | null | 2,947,592 | null | 2,190,971 | null | 1 | 1,275 | html|tabs|hyperlink|window|href | 1,635,495 | <p>You should add the <code>target="_blank"</code> and <code>rel="noopener noreferrer"</code> in the anchor tag.</p>
<p>For example:</p>
<pre><code><a target="_blank" rel="noopener noreferrer" href="http://your_url_here.html">Link</a>
</code></pre>
<p>Adding <code>rel="noopener noreferrer"</code> is not mandatory, but it's a recommended security measure. More information can be found in the links below. </p>
<p>Source: </p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-target" rel="noreferrer">MDN | HTML element <code><a></code> | attribute <code>target</code></a></li>
<li><a href="https://mathiasbynens.github.io/rel-noopener/" rel="noreferrer">About rel=noopener</a></li>
<li><a href="https://developers.google.com/web/tools/lighthouse/audits/noopener" rel="noreferrer">Opens External Anchors Using rel="noopener"</a></li>
</ul> |
32,666,528 | private bytes increase for a javaw process in java 8 | <p>My project has started using java 8 from java 7. </p>
<p>After switching to java 8, we are seeing issues like the memory consumed is getting higher with time.</p>
<p>Here are the investigations that we have done :</p>
<ul>
<li>Issues comes only after migrating from java7 and from java8</li>
<li>As metaspace is the only thing related to memory which is changes from hava 7 to java 8. We monitored metaspace and this does not grow more then 20 MB.</li>
<li>Heap also remains consistent.</li>
</ul>
<p>Now the only path left is to analyze how the memory gets distributes to process in java 7 and java 8, specifically private byte memory. Any thoughts or links here would be appreciated.</p>
<p>NOTE: this javaw application is a swing based application.</p>
<p><strong>UPDATE 1</strong> : After analyzing the native memory with NMT tool and generated a diff of memory occupied as compare to baseline. We found that the heap remained same but <strong>threads are leaking all this memory. So as no change in Heap, I am assuming that this leak is because of native code.</strong></p>
<p>So challenge remains still open. Any thoughts on <strong><em>how to analyze the memory occupied by all the threads</em></strong> will be helpful here.
Below are the snapshots taken from native memory tracking.</p>
<p>In this pic, you can see that 88 MB got increased in threads. Where arena and resource handle count had increased a lot. </p>
<p><a href="https://i.stack.imgur.com/Amkvz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Amkvz.png" alt="enter image description here"></a></p>
<p>in this picture you can see that 73 MB had increased in this Malloc. But no method name is shown here.
<a href="https://i.stack.imgur.com/QifCZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QifCZ.png" alt="enter image description here"></a></p>
<p>So please throw some info in understanding these 2 screenshot.</p> | 48,941,661 | 5 | 16 | null | 2015-09-19 09:28:05.217 UTC | 8 | 2018-02-23 05:26:50.517 UTC | 2017-10-23 06:00:25.557 UTC | null | 3,610,891 | null | 3,610,891 | null | 1 | 19 | multithreading|java-8|java-native-interface|native|java-7 | 2,516 | <p>I encountered the exact same issue.</p>
<p>Heap usage constant, only metaspace increase, NMT diffs showed a slow but steady leak in the memory used by threads specifically in the arena allocation. I had tried to fix it by setting the MALLOC_ARENAS_MAX=1 env var but that was not fruitful. Profiling native memory allocation with jemalloc/jeprof showed no leakage that could be attributed to client code, pointing instead to a JDK issue as the only smoking gun there was the memory leak due to malloc calls which, in theory, should be from JVM code.</p>
<p>Like you, I found that upgrading the JDK fixed the problem. The reason I am posting an answer here is because I know the reason it fixes the issue - it's a JDK bug that was fixed in JDK8 u152: <a href="https://bugs.openjdk.java.net/browse/JDK-8164293" rel="nofollow noreferrer">https://bugs.openjdk.java.net/browse/JDK-8164293</a></p>
<p>The bug report mentions Class/malloc increase, not Thread/arena, but a bit further down one of the comments clarifies that the bug reproduction clearly shows increase in Thread/arena.</p> |
10,458,719 | Efficiency: switch statements over if statements | <p><a href="http://pmd.sourceforge.net/pmd-5.0.0/"><code>PMD</code></a> tells me</p>
<blockquote>
<p>A switch with less than 3 branches is inefficient, use a if statement
instead.</p>
</blockquote>
<p>Why is that? Why 3? How do they define efficiency?</p> | 10,458,750 | 4 | 7 | null | 2012-05-05 03:58:11 UTC | 8 | 2012-05-05 04:15:55.213 UTC | 2012-05-05 04:03:51.793 UTC | null | 359,862 | null | 359,862 | null | 1 | 30 | java|pmd | 2,828 | <p>Because a <code>switch</code> statement is compiled with two special JVM instructions that are <code>lookupswitch</code> and <code>tableswitch</code>. They are useful when working with a lot of cases but they cause an overhead when you have just few branches.</p>
<p>An <code>if/else</code> statement instead is compiled into typical <code>je</code> <code>jne</code> ... chains which are faster but require many more comparisons when used in a long chain of branches.</p>
<p>You can see the difference by looking at byte code, in any case I wouldn't worry about these issues, if anything could become a problem then JIT will take care of it.</p>
<p>Practical example:</p>
<pre><code>switch (i)
{
case 1: return "Foo";
case 2: return "Baz";
case 3: return "Bar";
default: return null;
}
</code></pre>
<p>is compiled into:</p>
<pre><code>L0
LINENUMBER 21 L0
ILOAD 1
TABLESWITCH
1: L1
2: L2
3: L3
default: L4
L1
LINENUMBER 23 L1
FRAME SAME
LDC "Foo"
ARETURN
L2
LINENUMBER 24 L2
FRAME SAME
LDC "Baz"
ARETURN
L3
LINENUMBER 25 L3
FRAME SAME
LDC "Bar"
ARETURN
L4
LINENUMBER 26 L4
FRAME SAME
ACONST_NULL
ARETURN
</code></pre>
<p>While</p>
<pre><code>if (i == 1)
return "Foo";
else if (i == 2)
return "Baz";
else if (i == 3)
return "Bar";
else
return null;
</code></pre>
<p>is compiled into</p>
<pre><code>L0
LINENUMBER 21 L0
ILOAD 1
ICONST_1
IF_ICMPNE L1
L2
LINENUMBER 22 L2
LDC "Foo"
ARETURN
L1
LINENUMBER 23 L1
FRAME SAME
ILOAD 1
ICONST_2
IF_ICMPNE L3
L4
LINENUMBER 24 L4
LDC "Baz"
ARETURN
L3
LINENUMBER 25 L3
FRAME SAME
ILOAD 1
ICONST_3
IF_ICMPNE L5
L6
LINENUMBER 26 L6
LDC "Bar"
ARETURN
L5
LINENUMBER 28 L5
FRAME SAME
ACONST_NULL
ARETURN
</code></pre> |
35,429,801 | This action could not be completed. Try Again (-22421) | <p>I am trying to upload an <strong>Apple TV</strong> App to the App Store for testing purposes, but I got the issue:</p>
<blockquote>
<p>This Action could not be completed. Try Again (-22421)</p>
</blockquote>
<p>as in the below image:</p>
<p><a href="https://i.stack.imgur.com/eV1e7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eV1e7.png" alt="enter image description here" /></a></p>
<p>So what can I do?</p> | 35,663,309 | 45 | 18 | null | 2016-02-16 10:21:09.613 UTC | 93 | 2021-09-17 08:41:33.933 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 5,881,764 | null | 1 | 707 | ios|xcode|app-store-connect | 194,498 | <p>This happens because Apple's servers may not be working correctly. Just wait and try later or next time. It will work for sure eventually.</p> |
33,090,087 | How to inspect websocket traffic with charlesproxy for iOS simulator/devices | <p>I would like to inspect network traffic going through <strong>web sockets</strong>, I have no control over the networking code as this is a binary lib for which I do not have the source code, so <strong>I cannot do any log/breakpoint</strong> in the networking part of the code.</p>
<p>I have tried using the latest version of <strong>CharlesProxy</strong> which claim to be able to sniff websockets however when I tried the url and apis using websockets were not even mentionned in the list of endpoints called from my iPhone.</p>
<p><a href="https://i.stack.imgur.com/x6APp.png"><img src="https://i.stack.imgur.com/x6APp.png" alt="Version 3.11 release notes"></a></p>
<p>I have verified that CharlesProxy is configured correctly as I am able to inspect non-websocket traffic even under SSL.</p>
<p>So my question is: did anyone find a solution to inspect traffic going through websockets with CharlesProxy?</p>
<p><em>Note: I have ATS disabled when using iOS9</em></p>
<p>Thanks!</p> | 35,152,849 | 4 | 6 | null | 2015-10-12 20:57:22.073 UTC | 14 | 2022-06-16 12:38:33.127 UTC | 2015-10-12 21:17:59.617 UTC | null | 2,308,258 | null | 2,308,258 | null | 1 | 42 | ios|sockets|websocket|charles-proxy|cfnetwork | 41,821 | <p>I finally found the answer. </p>
<p><strong>Charles 3.11.2 works perfectly with WebSocket.</strong></p>
<p>I use <a href="http://socket.io/" rel="noreferrer">socketIO</a>, so I've already seen http requests sent during the negotiation phase, but <strong>I missed websockets traffic.</strong></p>
<p>In the beginning, socketIO try to use <em>polling</em> then switches to use <em>websockets</em>.</p>
<p>The websocket traffic is visible when you go to the request with status: <em>"Sending request body"</em> which is actually <em>wss://</em> request.</p>
<p>You even have a dedicated tab for this kind of traffic. The rest of messages will appear right there.</p>
<p><a href="https://i.stack.imgur.com/5UDaw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5UDaw.png" alt="enter image description here"></a></p>
<p>PS1. Ensure you're connected to socket properly then it appears in Charles.<br/>
PS2. I suggest using socketIO it's a great enhancement for full-duplex traffic like websockets. </p> |
22,479,162 | Nested redundant 'if' conditions | <p>Is there a better (or cleaner) way to write the following code?</p>
<pre><code>if(conditionX)
{
if(condition1)
{
// code X1
}
else if(condition2)
{
// code X2
}
}
else if(conditionY)
{
if(condition1)
{
// code Y1
}
else if(condition2)
{
// code Y2
}
}
</code></pre>
<p>I have a few more conditions, but I guess you get the point.</p> | 22,479,569 | 9 | 3 | null | 2014-03-18 12:18:00.903 UTC | 5 | 2018-10-12 17:11:46.153 UTC | 2018-10-12 17:11:46.153 UTC | null | 2,370,483 | null | 1,865,794 | null | 1 | 29 | c++|c|if-statement | 3,022 | <p>There are four approaches to this problem, none of which is universal:</p>
<ol>
<li><strong>Leave everything as is</strong> - There isn't much code duplication here. If computing <code>condition1</code> and <code>condition2</code> is tricky, compute them upfront and store them in <code>bool</code> variables</li>
<li><strong>Make <code>conditionX</code> and <code>conditionY</code> produce a result that lets you unify <code>condition1</code> and <code>condition2</code></strong> - This is not always possible, but in some situations you could prepare a variable that unifies the activities taken in the two branches, say, by using a function pointer or a lambda.</li>
<li><strong>Put the processing logic into subclasses with virtual functions to eliminate conditional logic</strong> - This is possible only when your initial design missed an opportunity to subclass. Essentially, this approach pushes the decision on <code>conditionX</code>/<code>conditionY</code> into a place where a subclass is created, and then "reuses" that decision later on by calling a proper override of a virtual function in the interface.</li>
<li><strong>Create a numeric combination representing all three conditions, and convert to <code>switch</code></strong> - This trick unifies the conditionals, reducing the nesting.</li>
</ol>
<p>Here is an example of the last approach:</p>
<pre><code>int caseNumber = ((conditionX?1:0) << 3)
| ((conditionY?1:0) << 2)
| ((condition2?1:0) << 1)
| ((condition1?1:0) << 0);
switch (caseNumber) {
case 0x09:
case 0x0D:
case 0x0F: // code X1
break;
case 0x0A:
case 0x0E: // code X2
break;
case 0x05:
case 0x07: // code Y1
break;
case 0x06: // code Y2
break;
}
</code></pre> |
13,249,528 | Javascript update/increment variable value on click | <p>I have this following code: <a href="http://jsfiddle.net/TSaaJ/1/">JS Fiddle</a></p>
<pre><code><html>
<head>
<script>
function increase(){
var a = 1;
var textBox = document.getElementById("text");
textBox.value = a;
a++;
}
</script>
</head>
<body>
<button type="button" onclick="increase()">show</button>
<input type="text" id="text">
</body>
</html>
</code></pre>
<p>What I am trying to do is:</p>
<ol>
<li>On clicking the button the value of 'a' will be displayed in the textbox and 'a' will be incremented.</li>
<li>On clicking again now the incremented value should be displayed but this doesn't happen.</li>
</ol>
<p>Where am I going wrong?</p> | 13,249,559 | 10 | 0 | null | 2012-11-06 10:58:23.15 UTC | 2 | 2021-05-30 03:56:22.69 UTC | null | null | null | null | 1,688,606 | null | 1 | 10 | javascript|increment | 56,608 | <p>You're only incrementing a local variable that goes away at end of function. You may do this :</p>
<pre><code> var a = 1;
function increase(){
var textBox = document.getElementById("text");
textBox.value = a;
a++;
}
</code></pre> |
13,513,936 | Oracle Sequence value are not ordered | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4866959/oracle-rac-and-sequences">Oracle RAC and sequences</a> </p>
</blockquote>
<p>I have a Oracle RAC configured in my local environment. I analyzed a problem with Sequnce that the number generated by nextVal are not ordered. Suppose First time I get value as 1 , the second time get get value as 21 (I have configured the sequence as with default CACHE 20 and NOORDER ).</p>
<p>On searching I found the solution that, I need to Order the sequence. I have question which is better option to go with,</p>
<p>1) CACHE and ORDER </p>
<p>2) NOCACHE and ORDER</p>
<p>I want to know which one of the above is better option and why?</p>
<p>Secondly, Can I achieve the ordering if I alter the sequence to be NOCACHE irrespective of ORDER/NOORDER.</p>
<p>Thanks</p> | 13,515,836 | 1 | 0 | null | 2012-11-22 13:39:38.22 UTC | 8 | 2012-11-22 15:27:22.323 UTC | 2017-05-23 12:07:14.7 UTC | null | -1 | null | 1,061,518 | null | 1 | 14 | oracle|oracle10g|oracle11g | 22,863 | <blockquote>
<p>Secondly, Can I achieve the ordering if I alter the sequence to be
NOCACHE irrespective of ORDER/NOORDER.</p>
</blockquote>
<p>yes as NOCACHE is effectively order as you're forcing a write to the sys.seq$ table on each increment, which has to serialise over nodes too.</p>
<p>--</p>
<p>I would dispute the accepted answer in that possible duplicate. there is a huge difference in CACHE + ORDER and NOCACHE in RAC. You are not negating the CACHE with ORDER; just reducing its effectiveness. I've personally seen performance of a middle tier application degrade drastically as they used NOCACHE on a sequence and were accessing on multiple nodes at once. We switched their sequence to ORDER CACHE (as they wanted an cross-rac order). and performance drastically improved. </p>
<p>in summary: The sequence speed will be from fastest to slowest as "CACHE NOORDER"->"CACHE ORDER" and way way WAY behind "NOCACHE". </p>
<p>This is easily testable too:</p>
<p>So we start with a standard sequence: </p>
<pre><code>SQL> create sequence daz_test start with 1 increment by 1 cache 100 noorder;
Sequence created.
</code></pre>
<p>ie CACHE with no order. Now we fire up two sessions. I'm using a 4 node RAC database 10.2.0.4 in this test:</p>
<p>my test script is simply</p>
<pre><code>select instance_number from v$instance;
set serverout on
declare
v_timer timestamp with time zone := systimestamp;
v_num number(22);
begin
for idx in 1..100000
loop
select daz_test.nextval into v_num from dual;
end loop;
dbms_output.put_line(systimestamp - v_timer);
end;
/
/
</code></pre>
<p>now we run the first test (CACHE NOORDER): </p>
<pre><code>SESSION 1 SESSION 2
SQL> @run_test SQL> @run_test
INSTANCE_NUMBER INSTANCE_NUMBER
--------------- ---------------
2 1
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
SQL> @run_test SQL> @run_test
INSTANCE_NUMBER INSTANCE_NUMBER
--------------- ---------------
2 1
+000000000 00:00:07.309916000 +000000000 00:00:07.966913000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
+000000000 00:00:08.430094000 +000000000 00:00:07.341760000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
</code></pre>
<p>so 7-8 seconds to select 100,000 iterations of the sequence. </p>
<p>Now lets try NOCACHE (ORDER vs NOORDER is irrelavant for this, as we are forcing a write to seq$ for every call to the sequence).</p>
<pre><code>SQL> alter sequence daz_test nocache;
Sequence altered.
SESSION 1 SESSION 2
SQL> @run_test SQL> @run_test
INSTANCE_NUMBER INSTANCE_NUMBER
--------------- ---------------
2 1
+000000000 00:08:20.040064000 +000000000 00:08:15.227200000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
+000000000 00:08:30.140277000 +000000000 00:08:35.063616000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
</code></pre>
<p>so we've jumped from 8 seconds to 8 MINUTES for the same work set. </p>
<p>what about CACHE + ORDER? </p>
<pre><code>SQL> alter sequence daz_test cache 100 order;
Sequence altered.
SQL> @run_test SQL> @run_test
INSTANCE_NUMBER INSTANCE_NUMBER
--------------- ---------------
2 1
+000000000 00:00:25.549392000 +000000000 00:00:26.157107000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
+000000000 00:00:26.057346000 +000000000 00:00:25.919005000
PL/SQL procedure successfully completed. PL/SQL procedure successfully completed.
</code></pre>
<p>so in summary for 100,000 single call fetches
CACHE NOORDER = 8 seconds
NOCACHE = 8 minutes
CACHE ORDER = 25 seconds</p>
<p>for cache order, oracle does do a lot of pinging between the RAC nodes , but it <em>DOESNT</em> have to write stuff back to seq$ until the cache size is used up, as its all done in memory. </p>
<p>i would if i were you, set an appropriate cache size (p.s. a high cache size doesn't put a load on the box memory, as oracle doesn't store all the numbers in RAM; only the current + final number) and consider ORDER if required. </p> |
13,289,751 | Cron job in a different timezone | <p>Is there a way of setting up a cronjob for a specific timezone?</p>
<p>My shared hosting is in USA (Virginia) and I am in UK. If I set a cron job to be executed at 1600 hrs every friday, then it will execute when its 1600 in Virginia.</p>
<p>I was wondering if I can setup my cronjob in such a way that it understands which timezone to pick. I am not too worried about daylight saving difference.</p>
<p>I have asked my shared hosting providers about it and they said I should be able to set the timezone in some cron ini files, but I could not find any.</p> | 13,290,144 | 5 | 1 | null | 2012-11-08 13:25:13.84 UTC | 5 | 2020-05-25 12:43:37.973 UTC | null | null | null | null | 418,366 | null | 1 | 17 | cron|controlpanel | 59,775 | <p>I think that you should check </p>
<pre><code>/etc/default/cron
</code></pre>
<p>or just type</p>
<pre><code>Crontab cronfile
</code></pre>
<p>and you should find </p>
<pre><code>TZ=UTC
</code></pre>
<p>This should be changed (for example America/New_York). Second way is set in cron example</p>
<pre><code>5 2 3 * * TZ="America/New_York" /do/command > /dev/null 2>&1
</code></pre> |
13,448,065 | Generating an SSL Key to work with node.js | <p>I'm working to setup a SSL via GoDaddy to use with my node.js server on AWS EC2. I've been unable to get it to work. </p>
<p>Here's what I've tried:</p>
<p>Intended for the domain: files.mysite.com</p>
<p><strong>On the server I run:</strong></p>
<pre><code>$ openssl req -new -newkey rsa:2048 -nodes -keyout files.mysite.key -out files.mysite.csr
Common Name: files.mysite.com
password: left empty
</code></pre>
<p>I then get the CSR: vim files.mysite.csr</p>
<p>I copy and paste from:</p>
<pre><code>-----BEGIN CERTIFICATE-----
......... lots of stuff
-----END CERTIFICATE-----
</code></pre>
<p>There is an extra empty line at the end, which I leave and paste into the GoDaddy interface using rekey.</p>
<p>I then download the godaddy key which provides:</p>
<pre><code>gd_bundle.crt
files.mysite.com.crt
</code></pre>
<p>Then in node I insert: </p>
<pre><code>key: fs.readFileSync('server.key').toString(),
cert: fs.readFileSync('server.crt').toString()
</code></pre>
<p>I'm not sure what server.key is or server.crt given that GoDaddy provides two crt files?<br>
Can you help? </p> | 13,450,299 | 2 | 1 | null | 2012-11-19 05:17:48.19 UTC | 10 | 2016-08-18 12:02:46.44 UTC | 2016-08-18 12:02:46.44 UTC | null | 2,870,922 | null | 823,449 | null | 1 | 20 | node.js|ssl|openssl | 12,191 | <p>GoDaddy uses an intermidiate certificate to sign your certificate. This has several advantages to both you and GoDaddy. But it takes a bit more work to get it to work (just a bit, mostly googling around).</p>
<p>In node.js you can install them like this:</p>
<pre><code>require('https').createServer({
key: fs.readFileSync('files.mysite.com.key'),
cert: fs.readFileSync('files.mysite.com.crt'),
ca: [fs.readFileSync('gd_bundle.crt')] // <----- note this part
}, app).listen(443);
</code></pre> |
13,717,555 | Pass array to where in Codeigniter Active Record | <p>I have a table in my database with adminId and clientId</p>
<p>There might be 20 records with the adminId of the logged in user and I'm trying to pull a list of clients.</p>
<p>I am wondering if there is a way i can say something like:</p>
<pre><code>$this->db->where('id', '20 || 15 || 22 || 46 || 86');
</code></pre>
<p>I'm trying to do this with dynamic data (you never know how many clients Id's you'll need to pull). Any ideas?</p> | 13,717,646 | 4 | 0 | null | 2012-12-05 06:29:55.587 UTC | 4 | 2021-02-26 14:35:51.303 UTC | null | null | null | null | 1,494,951 | null | 1 | 42 | php|codeigniter|activerecord | 142,087 | <pre><code>$this->db->where_in('id', ['20','15','22','42','86']);
</code></pre>
<p>Reference: <a href="https://codeigniter.com/userguide3/database/query_builder.html?highlight=where_in#CI_DB_query_builder::where_in" rel="noreferrer">where_in</a></p> |
13,778,650 | Why isn't a qualified static final variable allowed in a static initialization block? | <h2>Case 1</h2>
<pre><code>class Program {
static final int var;
static {
Program.var = 8; // Compilation error
}
public static void main(String[] args) {
int i;
i = Program.var;
System.out.println(Program.var);
}
}
</code></pre>
<h2>Case 2</h2>
<pre><code>class Program {
static final int var;
static {
var = 8; //OK
}
public static void main(String[] args) {
System.out.println(Program.var);
}
}
</code></pre>
<p>Why does <strong>Case 1</strong> cause a compilation error?</p> | 13,778,722 | 2 | 12 | null | 2012-12-08 14:57:22.003 UTC | 14 | 2014-12-16 14:38:24.673 UTC | 2013-05-25 17:54:25.48 UTC | null | 211,563 | null | 1,162,620 | null | 1 | 53 | java|static|final|static-initialization|qualified-name | 2,231 | <p>The JLS holds the answer (note the bold statement):</p>
<blockquote>
<p>Similarly, every blank final variable must be assigned at most once; it must be <em>definitely unassigned</em> when an assignment to it occurs. <strong>Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator.</strong> [<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-16.html" rel="noreferrer">§16</a>]</p>
</blockquote>
<p>This means that the 'simple name' must be used when assigning static final variables - i.e. the var name without any qualifiers.</p> |
24,149,679 | linking multiple files with fortran | <p>I'm new to Fortran but I'm trying to find a way that I can retrieve information from programs I've written without including them as subprograms within my new file. As of right now I have 4 subroutines within my new file and I would like to instead just be able to input the radius into all 4 and receive their respective outputs.</p>
<p>this is the basic format for my code--- basically I want to show that I need 4 separate programs in order to get all the variables needed for the current programs expression.
So far I've tried to use both the include and call expressions but they weren't able to retrieve the information I needed to bring back into my file and they came up with just "not applicable" answers.</p>
<pre><code>program practicedynamo
implicit none
real:: A,B,C, Radius
real::Bsquared,Vsquared
read*,radius
call programA(radius,A)
call programB(radius,B)
call programC(radius,C)
Vsquared=(1.0/3.0)*B
Bsquared= 4*pi*density*Vsquared
gradient=radius*C
Rvector=Bsquared*Vsquared*gradient
ThetaVector=Rvector*sin(A)
end program practicedynamo
!and then my four subroutines would be placed afterwards
!here is an example of one of my subroutines within my actual code (the version above has been simplified and I've changed the variables)
subroutine testdensity(radius,density)
implicit none
real::radius,x,sunradius,density
if (radius>0.and.radius<=695500000) then
sunradius=695500000
x=radius/sunradius
density=((519*x**4.0)-(1630*x**3.0)+(1844*x*x)-(889*x)+155)
print*," "
density=density*1000
print*,"the density is",density, "kg per meters cubed"
else
print*, "this radius is not an option for the sun"
end if
end subroutine testdensity
</code></pre> | 24,150,276 | 1 | 2 | null | 2014-06-10 19:48:23.987 UTC | 10 | 2014-06-11 07:17:11.667 UTC | 2014-06-11 07:17:11.667 UTC | null | 2,737,715 | null | 3,617,451 | null | 1 | 4 | file|fortran|external|subroutine | 10,354 | <p>You haven't mentioned how you are compiling your code, but here are some general ways to include multiple source files in a single executable. You don't need to include the files, you can just compile them separately and link them together. Writing a Makefile to do this is recommended and you can find plenty of examples on that elsewhere.</p>
<p>To compile multiple files into one executable, you need only list them all when compiling</p>
<pre><code>gfortran -o output programA.f90 programB.f90 programC.90 mainprogram.f90
</code></pre>
<p>If you do not want to compile them all together or have to recompile when you build, you can compile individual objects, e.g.</p>
<pre><code>gfortran -c -o programA.o programA.f90
gfortran -c -o programB.o programB.f90
gfortran -c -o programC.o programC.f90
</code></pre>
<p>and then link as</p>
<pre><code>gfortran -o output mainprogram.f90 programA.o programB.o programC.o
</code></pre>
<p>If you are instead trying to use libraries and want program A-C to be in a standalone library, you can first compile the objects as above, then</p>
<pre><code>ar rcs libABC.a programA.o programB.o programC.o
</code></pre>
<p>and then compile your main program as </p>
<pre><code>gfortran -o output mainprogram.f90 libABC.a
</code></pre>
<hr>
<p>If you aren't using modules, you'll be responsible for making sure that your calls to external subroutines match the declared interface in the external file. To be safe and have the compiler catch problems with mismatched arguments you can declare explicit interfaces in your program or put the external code into modules and <code>use</code> those modules in the main program.</p> |
3,345,387 | how to change originating IP in HttpWebRequest | <p>I'm running this application on a server that has assigned 5 IPs. I use HttpWebRequest to fetch some data from a website. But when I make the connection I have be able to specify which one of the 5 IPs to make the connection from. Does HttpWebRequest support this? If it doesn't can I inherit a class from it to change it's behavior? I need so ideas here.</p>
<p>My code right now is something like:</p>
<pre><code>System.Net.WebRequest request = System.Net.WebRequest.Create(link);
((HttpWebRequest)request).Referer = "http://application.com";
using (System.Net.WebResponse response = request.GetResponse())
{
StreamReader sr = new StreamReader(response.GetResponseStream());
return sr.ReadToEnd();
}
</code></pre> | 3,345,466 | 2 | 3 | null | 2010-07-27 15:45:21.95 UTC | 14 | 2013-08-17 16:42:09.9 UTC | null | null | null | null | 403,577 | null | 1 | 18 | c#|httpwebrequest|ip|webrequest | 18,667 | <p>According to <a href="https://stackoverflow.com/questions/2829238/how-to-change-the-request-ip-in-httpwebrequest">this</a>, no. You may have to drop down to using Sockets, where I know you can choose the local IP.</p>
<p>EDIT: actually, it seems that it may be possible. HttpWebRequest has a ServicePoint Property, which in turn has <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepoint.bindipendpointdelegate.aspx" rel="nofollow noreferrer">BindIPEndPointDelegate</a>, which may be what you're looking for.</p>
<p>Give me a minute, I'm going to whip up an example...</p>
<pre><code>HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
req.ServicePoint.BindIPEndPointDelegate = delegate(
ServicePoint servicePoint,
IPEndPoint remoteEndPoint,
int retryCount) {
if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) {
return new IPEndPoint(IPAddress.IPv6Any, 0);
} else {
return new IPEndPoint(IPAddress.Any, 0);
}
};
Console.WriteLine(req.GetResponse().ResponseUri);
</code></pre>
<p>Basically, the delegate has to return an IPEndPoint. You can pick whatever you want, but if it can't bind to it, it'll call the delegate again, up to int.MAX_VALUE times. That's why I included code to handle IPv6, since IPAddress.Any is IPv4.</p>
<p>If you don't care about IPv6, you can get rid of that. Also, I leave the actual choosing of the IPAddress as an exercise to the reader :)</p> |
4,016,921 | WPF invoke a control | <p>How can I invoke a control with parameters? I've googled this up, but nowhere to find!</p>
<p><a href="http://www.google.nl/search?num=100&hl=en&newwindow=1&safe=off&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&q=WPF+invoke+ui+thread&aq=f&aqi=g1&aql=&oq=&gs_rfai=" rel="noreferrer">invoke ui thread</a></p>
<p>This is the error i get:</p>
<blockquote>
<p>Additional information: Parameter count mismatch.</p>
</blockquote>
<p>And this happens when i do a simple check whether the text property of a textbox control is empty or not. This works in WinForms:</p>
<pre><code>if (this.textboxlink.Text == string.Empty)
SleepThreadThatIsntNavigating(5000);
</code></pre>
<p>It jumps from this if the line to the catch block and shows me that message.</p>
<p>This is how i try to invoke the control:</p>
<pre><code>// the delegate:
private delegate void TBXTextChanger(string text);
private void WriteToTextBox(string text)
{
if (this.textboxlink.Dispatcher.CheckAccess())
{
this.textboxlink.Text = text;
}
else
{
this.textboxlink.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new TBXTextChanger(this.WriteToTextBox));
}
}
</code></pre>
<p>What am I doing wrong? And since when do i have to invoke a control when i just want to read its content?</p> | 4,016,979 | 2 | 0 | null | 2010-10-25 16:52:04.773 UTC | 4 | 2018-04-16 09:31:29.773 UTC | 2018-04-16 09:31:29.773 UTC | null | 7,571,526 | null | 405,046 | null | 1 | 18 | c#|wpf|invoke | 48,807 | <p>When you call Invoke, you're not specifying your argument (<code>text</code>). When the Dispatcher tries to run your method, it doesn't have a parameter to supply, and you get an exception.</p>
<p>Try:</p>
<pre><code>this.textboxlink.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new TBXTextChanger(this.WriteToTextBox), text);
</code></pre>
<hr>
<p>If you want to read the value from a text box, one option is to use a lambda:</p>
<pre><code>string textBoxValue = string.Empty;
this.textboxlink.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action( () => { textBoxValue = this.textboxlink.Text; } ));
if (textBoxValue == string.Empty)
Thread.Sleep(5000);
</code></pre> |
45,477,133 | How to change CUDA version | <p>I met this error when compiling a modified caffe version.</p>
<p><code>OpenCV static library was compiled with CUDA 7.5 support. Please, use the same version or rebuild OpenCV with CUDA 8.0</code></p>
<p>I have some old code may not compatible with CUDA8.0, so I want to change my cuda version for this error.</p>
<p>I modified my ~/.bash_profile like this</p>
<pre><code># export PYTHONPATH=$PYTHONPATH:/usr/local/cuda-8.0/lib64/
# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-8.0/lib64
export PYTHONPATH=$PYTHONPATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib/
</code></pre>
<p>But it did't work. Still the same error. What should I do? Thanks.</p> | 46,069,613 | 6 | 7 | null | 2017-08-03 07:05:23.213 UTC | 11 | 2022-08-22 12:46:36.39 UTC | 2022-08-22 12:46:36.39 UTC | null | 2,602,877 | null | 7,033,937 | null | 1 | 22 | linux|opencv|caffe | 68,313 | <p>Change your CUDA soft link to point on your desired CUDA version. For example:</p>
<blockquote>
<p>ll /usr/local/cuda
lrwxrwxrwx 1 root root 19 Sep 06 2017 /usr/local/cuda -> /usr/local/cuda-8.0/</p>
</blockquote>
<p>Simply relink it with</p>
<p>Update:
If the symlink already exists, use this other command:</p>
<pre><code>[jalal@goku ~]$ ls /usr/local/cuda
lrwxrwxrwx. 1 root root 20 Sep 14 08:03 /usr/local/cuda -> /usr/local/cuda-10.2
[jalal@goku ~]$ sudo ln -sfT /usr/local/cuda/cuda-11.1/ /usr/local/cuda
[jalal@goku ~]$ ls /usr/local/cuda
lrwxrwxrwx. 1 root root 26 Sep 14 13:25 /usr/local/cuda -> /usr/local/cuda/cuda-11.1/
</code></pre>
<blockquote>
<p>ln -s /usr/local/cuda-7.5 /usr/local/cuda</p>
</blockquote>
<p>(With the proper installation location)</p> |
28,410,852 | Startup is really slow for all Cygwin applications | <p>Start of any Cygwin application takes <strong>more than a minute</strong> on Windows 8.1 x64. It doesn't matter, either I'm starting <code>mintty</code> from shortcut or <code>cygwin.bat</code> or <code>ls.exe</code> or <code>bash.exe</code> from bin folder. Each of them will be slow.</p>
<p>After Bash or mintty is started they are working fairly quick:</p>
<pre><code>$ time for i in {1..10} ; do bash -c "echo Hello" ; done
Hello
...
Hello
real 0m1.273s
user 0m0.060s
sys 0m1.181s
</code></pre>
<p>Steps, which I've tried:</p>
<ul>
<li>Reinstalled and tried both Cygwin and Cygwin64 a few times (version 2.864)</li>
<li>Started them as Administrator</li>
<li>Tried to run them in Windows 7 compatibility mode</li>
<li>Disabled "Automatically detect settings" for LAN <a href="https://stackoverflow.com/a/12466037/515835">as in this reply</a></li>
<li>Added <code>127.0.0.1 localhost cygdrive wpad</code> to hosts <a href="https://stackoverflow.com/a/12466037/515835">as in same reply</a></li>
<li>Set antivirus to disabled state</li>
<li>Checked that Bash completion is not installed (no <code>/etc/bash_completion.d</code> folder)</li>
<li>Disabled all removable drives in Device Manager (only system SSD and data HDD left)</li>
<li>Tried to run with empty <code>etc/profile.d</code> folder</li>
<li>Tried to run with empty <code>etc/bash.bashrc</code> file</li>
</ul>
<p>How else can I find root cause?</p>
<p>P.S. -
I have two different systems, laptop and desktop both with Windows 8.1 64 bit. This issue it 100% reproducible on both.</p>
<p>Also, if I start Bash a few seconds after login it starts immediately.</p> | 28,427,299 | 4 | 8 | null | 2015-02-09 13:25:04.76 UTC | 30 | 2018-10-31 14:35:49.04 UTC | 2018-10-31 14:29:19.93 UTC | null | 63,550 | null | 515,835 | null | 1 | 42 | windows|cygwin|windows-8.1 | 18,328 | <p>Eventually I found what causes this issue, but I'm still not sure why. Cygwin works for other people in same environment very well.</p>
<p><strong>Cause:</strong> On the start of every Cygwin application it tries to get credentials as it is described in <code>etc/nsswitch.conf</code> file. For some reason, it takes a lots of time for my account as it contacts with several Active Directory domain controllers via LDAP.</p>
<p><strong>Solution 1:</strong> You can save the current user and group in <code>etc/passwd</code> and <code>etc/group</code> files and set Cygwin to check them before Active Directory.</p>
<ol>
<li>Start <code>mintty.exe</code> and wait till it opens</li>
<li>Run <code>mkpasswd -c</code> and save its output to <code>etc/passwd</code> file (you will have to create it, output should be one line)</li>
<li>Run <code>mkgroup -c</code> and save its output to <code>etc/group</code> file (you will have to create it, output should be one line)</li>
<li>Open <code>etc/nsswitch.conf</code> and write</li>
</ol>
<p>nsswitch.conf contents:</p>
<pre><code>passwd: files # db
group: files # db
</code></pre>
<p>Now your Cygwin should start immediately.</p>
<p><strong>Solution 2:</strong> There is special <a href="https://cygwin.com/cygwin-ug-net/using-cygserver.html" rel="noreferrer">CygServer</a> application, shipped with Cygwin, which can be started as an NT service or as a simple process (just run <code>usr/sbin/cygserver.exe</code>). It caches credentials and propagates them to every next Cygwin process <em>while cygserver is running</em>.</p>
<p>Add it to startup or start it before your Cygwin session and you're good — cygserver startup will take time, but every next Cygwin process will start immediately.</p>
<p><strong>Is it your case?</strong> I want to share my investigation steps, so you could check, if your case is same to mine.</p>
<ul>
<li>Install <a href="https://www.microsoft.com/en-us/download/details.aspx?id=4865" rel="noreferrer">MS Network Monitor</a> as it is able to show traffic from a specific process. Run it as administrator.</li>
<li>Create <em>New capture tab</em> and click <em>Start</em> (you don't have to add any filters or anything).</li>
<li>Start <code>mintty</code> and you will see its connections in netmon: <img src="https://i.stack.imgur.com/J32zm.png" alt="netmon-screenshot"></li>
<li>You will see list of <code>mintty</code> connections in the tree view on the left and TCP and LDAP frames on the right after selecting on of those connections.</li>
<li>Additionally, you can get name of those remote machines by IP address. Run <code>nbtstat -a 8.8.8.8</code> in command line (replace 8.8.8.8 by one of IP addresses from netmon).</li>
</ul>
<p><strong>Going deeper:</strong> I'm still playing with <a href="https://cygwin.com/cygwin-ug-net/ntsec.html#ntsec-mapping-nsswitch" rel="noreferrer">etc/nsswitch.conf</a> file to get local credentials or maybe cached ones so it will run faster without cygserver. But no luck yet.</p> |
9,437,438 | Current_timestamp -> PHP Date() | <p>I have a field in a database labelled "timestamp" that is recording the current_timestamp.</p>
<p>What PHP code do I need to write in order to get the current_timestamp (YYYY-MM-DD HH:MM:SS) to display as something a little more reader friendly, i.e. (April 30, 2012 at 3:45pm)</p> | 9,437,474 | 5 | 2 | null | 2012-02-24 20:18:10.8 UTC | 1 | 2012-02-24 21:25:40.453 UTC | null | null | null | null | 1,121,315 | null | 1 | 1 | php|mysql|timestamp | 42,844 | <p>Great resource for this: <a href="http://php.net/manual/en/function.date.php" rel="noreferrer">http://php.net/manual/en/function.date.php</a></p>
<pre><code>$dateTimeVariable = date("F j, Y \a\t g:ia");
</code></pre>
<p>This will give you that format of the current time (which seemed to be what you were getting at), otherwise you need to pass the timestamp in after the date format string.</p> |
9,132,964 | linq group by, order by | <p>I have the following list</p>
<pre><code>ID Counter SrvID FirstName
-- ------ ----- ---------
1 34 66M James
5 34 66M Keith
3 55 45Q Jason
2 45 75W Mike
4 33 77U Will
</code></pre>
<p>What I like to do is to order by ID by ascending and then
get the first value of Counter, SrvID which are identical (if any).</p>
<p>So the output would be something like:</p>
<pre><code>ID Counter SrvID FirstName
-- ------ ----- ---------
1 34 66M James
2 45 75W Mike
3 55 45Q Jason
4 33 77U Will
</code></pre>
<p>Note how ID of 5 is removed from the list as Counter and SrvID was identical to what I had for ID 1 but as ID 1 came first
I removed 5.</p>
<p>This is what I would do but not working</p>
<pre><code> var result = (from ls in list1
group ts by new {ls.Counter, ls.SrvID}
order by ls.ID
select new{
ls.ID,
ls.Counter.FirstOrDefault(),
ls.SrvID.First,
ls.FirstName}).ToList()
</code></pre> | 9,133,119 | 2 | 2 | null | 2012-02-03 17:38:40.883 UTC | 5 | 2016-04-29 17:06:35.113 UTC | 2012-02-03 19:09:40.17 UTC | null | 69,537 | null | 996,431 | null | 1 | 24 | c#|linq | 76,356 | <pre><code>list1.GroupBy(item => new { Counter = item.Counter, SrvID = item.SrvID })
.Select(group => new {
ID = group.First().ID,
Counter = group.Key.Counter,
SrvID = group.Key.SrvID,
FirstName = group.First().FirstName})
.OrderBy(item => item.ID);
</code></pre> |
9,197,440 | Razor view engine for ExpressJS | <p>I've been toying around with NodeJS, ExpressJS etc, and would really like to be able to have a template engine closer to ASP.Net MVC's Razor engine for node (jshtml). I'm curious if anyone is familiar with such a beast, or something closer to it.</p>
<p>The main feature I am wanting is region/section based inserts against a master/parent layout/template, which doesn't seem to be a feature in the template engines for node I have seen so far.</p>
<hr>
<p><strong>-- edit: 2012-02-09 --</strong></p>
<p>I'm essentially wanting to be able to do the following...</p>
<p>_layout.jshtml</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- meta tags, etc -->
<!-- title set in page -->
<title>@ViewBag.Title</title>
<!-- site-wide styles -->
@RenderSection("Styles", false)
</head>
<body class="@ViewBag.PageClass">
<!-- site-wide header -->
<div id="side_content">
@RenderSection("Side", false)
</div>
<div id="main_content">
@RenderBody()
</div>
<!-- site-wide footer -->
<!-- site-wide scripts -->
@RenderSection("Scripts", false)
</body>
</html></code></pre>
<p>mypage.jshtml</p>
<pre><code>@{
ViewBag.Title = "My Page";
ViewBag.PageClass = "page-x";
}
@section Styles {
<link ... />
}
@section Scripts {
<script type="text/javascript">
var pagesettings = @Html.Raw(Model.SomeJsonContentFromController);
</script>
}
@section Side {
side content here
}
main content here</code></pre>
<hr>
<p>Which is pass certain criteria from the view into the layout including multiple sections. I haven't seen an example of how to do this in Jade or EJS, if it's possible I would appreciate the insight.</p>
<hr>
<p><em>-- edit: 2012-02-13 --</em></p>
<p>It looks like ExpressJS 3 + Jade there are now "extends" and "block" keywords for defining precisely what I was looking for. Example taken <a href="http://www.devthought.com/code/use-jade-blocks-not-layouts/" rel="nofollow noreferrer">from here</a>. Thanks to <a href="https://stackoverflow.com/users/6845/don">@Don</a> for his answer & comment.</p>
<pre><code>// my-template.jade
extends my-layout
// only guessing this var will be passed to the layout (testing later)
- var pageTitle = "My Template";
- var pageClass = "my-template";
block styles
style(type="text/css")
block scripts
script(src="myscript.js")
block side
div Side Content Here
block main
div Main Content Here
</code></pre>
<pre><code>//my-layout.jade
doctype 5
html
head
title #{pageTitle} - My Site
body(class=pageClass)
#side
block side
#main
block main
block scripts
</code></pre>
<p>I'm not 100% sure about some aspects above (namely variables carrying to the layout from the template... will try to confirm later.</p> | 20,463,113 | 5 | 2 | null | 2012-02-08 16:30:14.297 UTC | 10 | 2018-12-20 15:07:39.613 UTC | 2017-05-23 11:45:58.217 UTC | null | -1 | null | 43,906 | null | 1 | 28 | node.js|razor|express | 20,417 | <p><a href="https://github.com/kirbysayshi/vash">Vash</a> is the most feature complete and up-to-date razor clone I have found yet. Definitely check that one out.</p> |
29,797,172 | What's the enhancement of AppCompatActivity over ActionBarActivity? | <p><code>android.support.v7.app.AppCompatActivity</code> was added into the latest v7 support library as a new feature yesterday.</p>
<p>It is said that <code>ActionBarActivity</code> has been deprecated in favor of the new <code>AppCompatActivity</code> and that <code>AppCompatActivity</code> is base class for activities that use the support library action bar features. So, what are new features of <code>AppCompatActivity</code> over <code>ActionBarActivity</code>? What enhancements do <code>AppCompatActivity</code> have over <code>ActionBarActivity</code>? And what are advantages of <code>AppCompatActivity</code>? Could somebody supply a few samples?</p>
<p><strong>PS:</strong> what surprised me most is that <code>AppCompatActivity</code> which is extended from <code>android.support.v4.app.FragmentActivity</code> is the direct parent class of <code>ActionBarActivity</code>! I mean actually now that <code>ActionBarActivity</code> can do anything that <code>AppCompatActivity</code> can do, why did Android pushed out the latter?</p>
<p>Meanwhile, I saw a blog post that states: "<em>It's not a rename from <code>ActionBarActivity</code> to <code>AppCompatActivity</code>, the internal logic of <code>AppCompat</code> is available via <code>AppCompatDelegate</code></em>", so what's the "<em>internal logic</em>" of <code>AppCompat</code>? What can <code>AppCompatDelegate</code> do? Could somebody post some codes about this?</p> | 29,978,777 | 6 | 4 | null | 2015-04-22 12:10:53.777 UTC | 45 | 2020-09-02 09:27:20.78 UTC | 2020-09-02 09:27:20.78 UTC | null | 5,740,428 | null | 4,407,176 | null | 1 | 164 | android|android-appcompat|android-actionbaractivity|appcompatactivity | 95,021 | <p>As Chris wrote, new deprecated version of <code>ActionBarActivity</code> (the one extending <code>AppCompatActivity</code> class) is a safe to use backward compatibility class. Its deprecation is just a hint for you asking to use new <code>AppCompatActivity</code> directly instead. <code>AppCompatActivity</code> is a new, more generic implementation which uses <code>AppCompatDelegate</code> class internally. </p>
<p>If you start a new development, then you should rather use new <code>AppCompatActivity</code> class right away. If you have a chance to update your app, then replace deprecated <code>ActionBarActivity</code> by the new activity as well. Otherwise you can stay with deprecated activity and there will be no difference in behavior at all.</p>
<p>Regarding <code>AppCompatDelegate</code>, it allows you to have new tinted widgets in an activity, which is neither <code>AppCompatActivity</code> nor <code>ActionBarActivity</code>. </p>
<p>For instance, you inherit an activity from an external library, which, in turn, does <strong>not</strong> inherit from <code>AppCompatActivity</code> but you want this activity to have tinted materials widgets (views). To make it happen you need to create an instance of <code>AppCompatDelegate</code> inside your activity, override methods of that activity like <code>addContentView()</code>, <code>setContentView()</code> etc. (see <code>AppCompatDelegate</code> javadoc for the full list of methods), and inside of those overridden methods forward the calls to the inner <code>AppCompatDelegate</code> instance. <code>AppCompatDelegate</code> will do the rest and your "old-fashion" activity will be "materialized".</p> |
16,569,840 | Using objc_setAssociatedObject with weak references | <p>I know that OBJC_ASSOCIATION_ASSIGN exists, but does it zero the reference if the target object is dealloced? Or is it like the old days where that reference needs to get nil-ed or we risk a bad access later on?</p> | 16,572,944 | 6 | 1 | null | 2013-05-15 16:00:21.537 UTC | 12 | 2021-12-17 15:55:41.68 UTC | null | null | null | null | 614,688 | null | 1 | 25 | objective-c|weak-references|objective-c-runtime | 6,951 | <p>After trying it out, the answer is NO.</p>
<p>I ran the following code under the iOS 6 Simulator, but it would probably have the same behavior with previous iterations of the runtime:</p>
<pre><code>NSObject *test1 = [NSObject new];
NSObject __weak *test2 = test1;
objc_setAssociatedObject(self, "test", test1, OBJC_ASSOCIATION_ASSIGN);
test1 = nil;
id test3 = objc_getAssociatedObject(self, "test");
</code></pre>
<p>In the end, test1 and test2 are nil, and test3 is the pointer previously stored into test1. Using test3 would result in trying to access an object that had already been dealloced.</p> |
29,106,019 | Xcode attach to process doesn't display NSLog | <p>I'm just getting started with Apple Watch. I found instructions from "<a href="http://www.fiveminutewatchkit.com/blog/?category=Xcode"><strong>Five Minute Watchkit</strong></a>", on getting the iOS app and the watch kit app both running in the simulator and both processes attached to the LLDB debugger.</p>
<p>What I do is launch and quit the iOS app to install a current version in the sim. Then I switch to the watchKit scheme and launch that, which displays my watch app UI on the watch simulator.</p>
<p>I then launch the corresponding iOS app in the simulator, then user "attach to process" in the Xcode menu to attach the debugger to the running iOS app.</p>
<p>This works. I can set breakpoints in either the watch kit InterfaceController or in my iOS app and the debugger breaks there when it should.</p>
<p>However, I'm not seeing NSLog() statements in the debug console from my iOS app. (I do see log statements from the WatchKit extension code.) If I set a breakpoint in my iOS app, it does stop at that breakpoint when it should. I assume the lack of console output from NSLog has SOMETHING to do with attaching to a running process on the sim rather than launching it from Xcode, but I don't know what that something is.</p>
<p>(BTW, attaching an action to a breakpoint that invokes NSLog from the breakpoint also doesn't display, but the "log message" debugger command DOES display.
Does anybody have any insights?)</p>
<p>EDIT:
The code in the iOS app doesn't seem to matter. In my case, it was a dirt simple IBAction that was attached to a button in the iOS app storyboard:</p>
<pre><code>- (IBAction)buttonAction:(UIButton *)sender;
{
NSLog(@"Button clicked on iPhone");
}
</code></pre>
<p>I can set a breakpoint on that NSLog statement. The debugger stops at that line, but I don't see the log statement in the debug console.</p> | 29,107,583 | 8 | 7 | null | 2015-03-17 17:39:08.32 UTC | 8 | 2021-11-06 09:47:28.46 UTC | 2015-03-17 19:29:06.973 UTC | null | 457,406 | null | 205,185 | null | 1 | 34 | ios|objective-c|xcode|apple-watch | 22,665 | <p>I can reproduce that with a simple test app, sans WatchKit. The app consists of a NSTimer that prints "Timer fired" every second. (This code is 100% correct ;). Nothing shows in the log after I have manually attached to the process.<br>
As far as I know NSLog outputs to stderr, I guess attaching the debugger does not redirect stderr to the Xcode terminal.</p>
<p>If you are okay with using the console app or the terminal to look at your logs you can do that. iOS8 stores simulator logs in <code>~/Library/Logs/CoreSimulator/<Device-UUID></code>. In this directory you will find a system.log, which contains all your <code>NSLog</code> output. </p>
<p>You can look at it in terminal (<code>cat</code>, <code>grep</code>, <code>tail</code>), or open it in the Console.app. </p>
<p><a href="https://i.stack.imgur.com/pDMOp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pDMOp.png" alt="enter image description here"></a></p>
<hr>
<p>Apple confirms that (at least for GDB) in <a href="https://developer.apple.com/library/ios/technotes/tn2239/_index.html" rel="noreferrer">Technical Note TN2239: iOS Debugging Magic</a>. </p>
<blockquote>
<p>Console Output</p>
<p>Many programs, and indeed many system frameworks, print debugging
messages to stderr. The destination for this output is ultimately
controlled by the program: it can redirect stderr to whatever
destination it chooses. However, in most cases a program does not
redirect stderr, so the output goes to the default destination
inherited by the program from its launch environment. This is
typically one of the following:</p>
<ul>
<li>If you launch a GUI application as it would be launched by a normal
user, the system redirects any messages printed on stderr to the
system log. You can view these messages using the techniques described
earlier. </li>
<li>If you run a program from within Xcode, you can see its
stderr output in Xcode's debugger Console window (choose the Console
menu item from the Run menu to see this window). </li>
</ul>
<p><strong>Attaching to a
running program (using Xcode's Attach to Process menu, or the attach
command in GDB) does not automatically connect the program's stderr to
your GDB window.</strong> You can do this from within GDB using the trick
described in the "Seeing stdout and stderr After Attaching" section of
Technical Note TN2030, 'GDB for MacsBug Veterans'.</p>
</blockquote>
<p>The mentioned TN2030 is no longer available on their server (<a href="http://www.fenestrated.net/~macman/mirrors/Apple%20Technotes%20(As%20of%202002)/tn/tn2030.html" rel="noreferrer">mirror</a>). It showed how you can redirect stdout and stderr to the Xcode console. However, since <code>shell tty</code> isn't a valid command for LLDB it won't help much. But maybe there is a different way to access the tty Xcodes console uses, so I attach the important part of that TN. </p>
<blockquote>
<p>Seeing stdout and stderr After Attaching</p>
<p>If you attach GDB to a process (as opposed to starting the process
from within GDB), you won't be able to see anything that the process
prints to stdout or stderr. Programs launched by the Finder typically
have stdout and stderr connected to "/dev/console", so the information
they print goes to the console. You can view this by launching the
Console application (in the Utilities folder), however, it's
inconvenient to have to look in a separate window. Another alternative
is to connect the process's stdout or stderr to the terminal device
for GDB's Terminal window. Listing 9 shows how to do this.</p>
<p>Listing 9. Connecting stdout and stderr to GDB's terminal device.</p>
<pre><code>(gdb) attach 795
[... output omitted ...]
(gdb) call (void) DebugPrintMenuList()
No output )-:
Close the stdout and stderr file descriptors.
(gdb) call (void) close(1)
(gdb) call (void) close(2)
Determine the name of the terminal device for GDB itself.
(gdb) shell tty
/dev/ttyp1
Reopen stdout and stderr, but connected to GDB's terminal.
The function results should be 1 and 2; if not, something
is horribly wrong.
(gdb) call (int) open("/dev/ttyp1", 2, 0)
$1 = 1
(gdb) call (int) open("/dev/ttyp1", 2, 0)
$2 = 2
Try the DebugPrintMenuList again.
(gdb) call (void) DebugPrintMenuList()
Yay output!
Index MenuRef ID Title
----- ---------- ---- -----
<regular menus>
00001 0x767725D3 -21629 Ed
00002 0x76772627 1128 <Apple>
00003 0x767726CF 1129 File
00004 0x76772567 1130 Edit
[... remaining output omitted ...]
</code></pre>
</blockquote> |
15,231,486 | How do I set up a dynamic file path in SSIS for an Excel file? | <p>The name of the file changes based on months. Every month you have a new file. </p>
<pre><code>I:\Test\Data_201303.xlsx
</code></pre>
<p>How do I set up a connection manager that will work with variable file paths?</p> | 15,231,995 | 2 | 0 | null | 2013-03-05 18:35:31.69 UTC | 1 | 2015-09-01 03:27:50.637 UTC | null | null | null | null | 1,336,632 | null | 1 | 5 | sql|ssis | 43,244 | <p>You need to set the expression for the <em><code>ServerName</code></em> or <em><code>ExcelFilePath</code></em> property to modify <em><code>ConnectionString</code></em> of Excel connection manager dynamically using an SSIS package variable. </p>
<p>Here are some SO answers that deal with looping multiple Excel files :</p>
<p><a href="https://stackoverflow.com/questions/7411741/how-to-loop-through-excel-files-and-load-them-into-a-database-using-ssis-package">How to loop through Excel files and load them into a database using SSIS package?</a></p>
<p><a href="https://stackoverflow.com/questions/6190578/how-to-import-excel-files-with-different-names-and-same-schema-into-database">How to import Excel files with different names and same schema into database?</a></p> |
21,809,112 | What does *tuple and **dict mean in Python? | <p>As mentioned in PythonCookbook, <code>*</code> can be added before a tuple. What does <code>*</code> mean here?</p>
<blockquote>
<p>Chapter 1.18. Mapping Names to Sequence Elements:</p>
<pre><code>from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price'])
s = Stock(*rec)
# here rec is an ordinary tuple, for example: rec = ('ACME', 100, 123.45)
</code></pre>
</blockquote>
<p>In the same section, <code>**dict</code> presents:</p>
<blockquote>
<pre><code>from collections import namedtuple
Stock = namedtuple('Stock', ['name', 'shares', 'price', 'date', 'time'])
# Create a prototype instance
stock_prototype = Stock('', 0, 0.0, None, None)
# Function to convert a dictionary to a Stock
def dict_to_stock(s):
return stock_prototype._replace(**s)
</code></pre>
</blockquote>
<p>What is <code>**</code>'s function here?</p> | 21,809,162 | 1 | 5 | null | 2014-02-16 08:50:44.947 UTC | 43 | 2021-09-03 12:41:19.553 UTC | 2020-07-12 18:40:48.677 UTC | null | 4,621,513 | null | 2,151,275 | null | 1 | 51 | python|python-3.x|tuples|namedtuple|iterable-unpacking | 67,558 | <h1>In a function call</h1>
<p><code>*t</code> means "treat the elements of this iterable as positional arguments to this function call."</p>
<pre><code>def foo(x, y):
print(x, y)
>>> t = (1, 2)
>>> foo(*t)
1 2
</code></pre>
<p>Since v3.5, you can also do this in a list/tuple/set literals:</p>
<pre><code>>>> [1, *(2, 3), 4]
[1, 2, 3, 4]
</code></pre>
<p><code>**d</code> means "treat the key-value pairs in the dictionary as additional named arguments to this function call."</p>
<pre><code>def foo(x, y):
print(x, y)
>>> d = {'x':1, 'y':2}
>>> foo(**d)
1 2
</code></pre>
<p>Since v3.5, you can also do this in a dictionary literals:</p>
<pre><code>>>> d = {'a': 1}
>>> {'b': 2, **d}
{'b': 2, 'a': 1}
</code></pre>
<h1>In a function signature</h1>
<p><code>*t</code> means "take all additional positional arguments to this function and pack them into this parameter as a tuple."</p>
<pre><code>def foo(*t):
print(t)
>>> foo(1, 2)
(1, 2)
</code></pre>
<p><code>**d</code> means "take all additional named arguments to this function and insert them into this parameter as dictionary entries."</p>
<pre><code>def foo(**d):
print(d)
>>> foo(x=1, y=2)
{'y': 2, 'x': 1}
</code></pre>
<h1>In assignments and <code>for</code> loops</h1>
<p><code>*x</code> means "consume additional elements in the right hand side", but it doesn't have to be the last item. Note that <code>x</code> will always be a list:</p>
<pre><code>>>> x, *xs = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3, 4]
>>> *xs, x = (1, 2, 3, 4)
>>> xs
[1, 2, 3]
>>> x
4
>>> x, *xs, y = (1, 2, 3, 4)
>>> x
1
>>> xs
[2, 3]
>>> y
4
>>> for (x, *y, z) in [ (1, 2, 3, 4) ]: print(x, y, z)
...
1 [2, 3] 4
</code></pre>
<hr />
<p>Note that parameters that appear after a <code>*</code> are keyword-only:</p>
<pre><code>def f(a, *, b): ...
f(1, b=2) # fine
f(1, 2) # error: b is keyword-only
</code></pre>
<p>Python3.8 added <a href="https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters" rel="noreferrer">positional-only parameters</a>, meaning parameters that cannot be used as keyword arguments. They appear before a <code>/</code> (a pun on <code>*</code> preceding keyword-only args).</p>
<pre><code>def f(a, /, p, *, k): ...
f( 1, 2, k=3) # fine
f( 1, p=2, k=3) # fine
f(a=1, p=2, k=3) # error: a is positional-only
</code></pre> |
45,060,886 | Grouping items by date | <p>I have items in my list and the items have a field, which shows the creation date of the item.</p>
<p><a href="https://i.stack.imgur.com/Ket2G.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Ket2G.jpg" alt="enter image description here"></a></p>
<p>and I need to group them based on a "compression", which the user gives. The options are <code>Day</code>, <code>Week</code>, <code>Month</code> and <code>Year</code>.</p>
<p>If the user selects <code>day</code> compression, I need to group my items as such that the items, which are created in the same day, will be groupped. In my example above, only item 1 and item 2 are created in the same day. The others are also groups but they will have only one item because at their day, only one item is created.</p>
<pre><code>{{item1, item2}, {item3}, {item4}, {item5}, {item6}, {item7}}
</code></pre>
<p>If the user selects <code>week</code>:</p>
<pre><code>{{item1, item2, item3, item4}, {item5}, {item6}, {item7}}
</code></pre>
<p>If the user selects <code>month</code>:</p>
<pre><code>{{item1, item2, item3, item4, item5}, {item6}, {item7}}
</code></pre>
<p>If the user selects <code>year</code>:</p>
<pre><code>{{item1, item2, item3, item4, item5, item6}, {item7}}
</code></pre>
<p>After groups are created, the date of the items are not important. I mean the key can be anything, as long as the groups are created.</p>
<p>In case of usage of <code>Map</code>, I thought as the keys as follow:</p>
<p><code>day</code> = day of the year<br>
<code>week</code> = week of the year<br>
<code>month</code> = month of the year<br>
<code>year</code> = year<br></p>
<p>What would be the best solution to this problem? I could not even start it an I cannot think of a solution other than iteration. </p> | 45,068,322 | 5 | 5 | null | 2017-07-12 14:43:42.443 UTC | 12 | 2017-07-17 08:07:20.877 UTC | 2017-07-17 08:07:20.877 UTC | null | 5,873,039 | null | 5,873,039 | null | 1 | 18 | java|java-8|java-stream|java-time | 27,264 | <p>I would use <code>Collectors.groupingBy</code> with an adjusted <code>LocalDate</code> on the classifier, so that items with similar dates (according to the <em>compression</em> given by the user) are grouped together.</p>
<p>For this, first create the following <code>Map</code>:</p>
<pre><code>static final Map<String, TemporalAdjuster> ADJUSTERS = new HashMap<>();
ADJUSTERS.put("day", TemporalAdjusters.ofDateAdjuster(d -> d)); // identity
ADJUSTERS.put("week", TemporalAdjusters.previousOrSame(DayOfWeek.of(1)));
ADJUSTERS.put("month", TemporalAdjusters.firstDayOfMonth());
ADJUSTERS.put("year", TemporalAdjusters.firstDayOfYear());
</code></pre>
<p>Note: for <code>"day"</code>, a <code>TemporalAdjuster</code> that lets the date untouched is being used.</p>
<p>Next, use the <code>compression</code> given by the user to dynamically select how to group your list of items:</p>
<pre><code>Map<LocalDate, List<Item>> result = list.stream()
.collect(Collectors.groupingBy(item -> item.getCreationDate()
.with(ADJUSTERS.get(compression))));
</code></pre>
<p>The <code>LocalDate</code> is adjusted by means of the <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#with-java.time.temporal.TemporalAdjuster-" rel="noreferrer"><code>LocalDate.with(TemporalAdjuster)</code></a> method.</p> |
17,371,302 | new Date(milliseconds) returns Invalid date | <p>I am trying to convert milliseconds to a date using the javascript using:</p>
<pre><code>new Date(Milliseconds);
</code></pre>
<p>constructor, but when I give it a milliseconds value of say 1372439683000 it returns invalid date. If I go to a <a href="http://www.ruddwire.com/handy-code/date-to-millisecond-calculators/">site that converts milliseconds to date</a> it returns the correct date.</p>
<p>Any ideas why?</p> | 17,371,366 | 5 | 2 | null | 2013-06-28 18:26:05.62 UTC | 10 | 2021-09-16 11:46:47.983 UTC | 2013-06-28 18:38:06.183 UTC | null | 1,634,451 | null | 1,634,451 | null | 1 | 51 | javascript|date|time|milliseconds | 49,357 | <p>You're not using a number, you're using a <em>string</em> that looks like a number. According to MDN, when you pass a string into <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer"><code>Date</code></a>, it expects</p>
<blockquote>
<p>a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).</p>
</blockquote>
<p>An example of such a string is "<code>December 17, 1995 03:24:00</code>", but you're passing in a string that looks like "<code>1372439683000</code>", which is not able to be parsed.</p>
<p>Convert <code>Milliseconds</code> to a number using <code>parseInt</code>, or a unary <code>+</code>:</p>
<pre><code>new Date(+Milliseconds);
new Date(parseInt(Milliseconds,10));
</code></pre> |
18,663,078 | Disable history in Linux | <p>To disable a history in Linux environment I've executed the following commands:</p>
<pre><code>export HISTFILESIZE=0
export HISTSIZE=0
unset HISTFILE
</code></pre>
<p>Is such command combination enough or I have to also execute <code>history -c</code> or something else?</p>
<p>Will this keep history disabled even when I reboot a server or such commands need to be executed after reboot again and again?</p> | 18,663,518 | 3 | 1 | null | 2013-09-06 17:11:36.993 UTC | 6 | 2016-04-21 08:06:25.993 UTC | null | null | null | null | 1,215,106 | null | 1 | 15 | linux|bash|shell|history | 49,385 | <p>Just add this command to a bash startup file which could be <code>/etc/profile</code>, <code>~/.bash_profile</code>, <code>~/.bash_login</code>, <code>~/.profile</code>, or <code>~/.bashrc</code> depending your target scope and distro that customizes bash. See the <code>INVOCATION</code> section of bash's manual (<code>man bash</code>).</p>
<pre><code>shopt -u -o history
</code></pre>
<p>Or</p>
<pre><code>set +o history
</code></pre>
<p>Which would disable history.</p>
<p>Although you have to clear your history once:</p>
<pre><code>history -c
</code></pre>
<p>And also delete your <code>~/.bash_history</code> file.</p> |
18,735,180 | Bootstrap 3 Popover: display on hover AND on click, aka. Pin a Popover | <p>Making a popover appear with the <strong>hover</strong> trigger works fine.</p>
<p>Making a popover appear with the <strong>click</strong> trigger works fine.</p>
<p>Now, how do I go about making the popover appear when the triggering image is hovered over, but then if the user clicks on the image, cancel the hover and initiate a click toggle? In other words, hovering shows the popover and clicking 'pins' the popover.</p>
<p>The HTML is pretty standard:</p>
<pre><code><li>User<span class="glyphicon glyphicon-user" rel="popover" data-trigger="click" data-container="body" data-placement="auto left" data-content="Body Text" data-original-title="Title Text"></span></li>
</code></pre>
<p>And the popover initialization, even more boring:</p>
<pre><code>$(function () {
$("[rel=popover]").popover();
});
</code></pre>
<p>From what I have seen so far, it seems likely that the solution is a nice complex set of <code>popover('show')</code>, <code>popover('hide')</code>, and <code>popover('toggle')</code> calls, but my javascript / jQuery-foo is not up to the task.</p>
<p><strong>EDIT:</strong> </p>
<p>Using the code provided by @hajpoj as a base, I added a function to listen to the <code>hidden.bs.popover</code> event to try to re-enable the mouseenter and mouseleave events after triggering the click event, but although it does make the 'hover' work again, it kills the click...</p>
<pre><code>var $btn2 = $('#btn2');
var enterShow = function() {
$btn2.popover('show');
};
var exitHide = function() {
$btn2.popover('hide');
}
$btn2.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.one('click', function() {
$btn2.off('mouseenter', enterShow)
.off('mouseleave', exitHide)
.on('click', function() {
$btn2.popover('toggle');
});
});
$('#btn2').on('hidden.bs.popover', function () {
$btn2.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
});
</code></pre> | 18,754,902 | 4 | 0 | null | 2013-09-11 07:30:50.733 UTC | 9 | 2017-08-15 16:38:16.413 UTC | 2013-09-18 17:56:57.3 UTC | null | 2,767,651 | null | 2,767,651 | null | 1 | 17 | javascript|jquery|twitter-bootstrap|popover | 66,063 | <p><strong>Edit:</strong></p>
<p>Heres an updated solutions based off your comment. It doesn't stay in a 'click' state but returns to the hover state.</p>
<p>jsfiddle: <a href="http://jsfiddle.net/hajpoj/JJQS9/15/">http://jsfiddle.net/hajpoj/JJQS9/15/</a></p>
<p>html:</p>
<pre><code><a href="#" id="btn2" class="btn btn-lg btn-danger" data-toggle="popover" title="" data-content="And here's some amazing content. It's very engaging. right?" data-original-title="A Title">Click to toggle popover</a>
</code></pre>
<p>js:</p>
<pre><code>var $btn2 = $('#btn2');
$btn2.data('state', 'hover');
var enterShow = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('show');
}
};
var exitHide = function () {
if ($btn2.data('state') === 'hover') {
$btn2.popover('hide');
}
};
var clickToggle = function () {
if ($btn2.data('state') === 'hover') {
$btn2.data('state', 'pinned');
} else {
$btn2.data('state', 'hover')
$btn.popover('hover');
}
};
$btn2.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.on('click', clickToggle);
</code></pre>
<hr>
<p><strong>Old:</strong></p>
<p>I believe this is what you are looking for:</p>
<p><a href="http://jsfiddle.net/JJQS9/1/">http://jsfiddle.net/JJQS9/1/</a></p>
<p>html:</p>
<pre><code><a href="#" id="btn2" class="btn btn-lg btn-danger" data-toggle="popover" title="" data-content="And here's some amazing content. It's very engaging. right?" data-original-title="A Title">Click to toggle popover</a>
</code></pre>
<p>js:</p>
<pre><code>var $btn2 = $('#btn2');
var enterShow = function() {
$btn2.popover('show');
};
var exitHide = function() {
$btn2.popover('hide');
}
$btn2.popover({trigger: 'manual'})
.on('mouseenter', enterShow)
.on('mouseleave', exitHide)
.one('click', function() {
$btn2.off('mouseenter', enterShow)
.off('mouseleave', exitHide)
.on('click', function() {
$btn2.popover('toggle');
});
});
</code></pre>
<p>Basically you manually pop open/close the popover on the <code>mouseenter</code> and <code>mouseleave</code> events, but once someone clicks on the popover for the first time, you remove those event handlers, and add a new handler on the <code>click</code> event that toggles the popover. </p>
<p><strong>Edit:</strong>
an alternative js code. simpler code, but there is a small visual blip when you use it:
<a href="http://jsfiddle.net/hajpoj/r3Ckt/1/">http://jsfiddle.net/hajpoj/r3Ckt/1/</a></p>
<pre><code>var $btn2 = $('#btn2');
$btn2.popover({trigger: 'hover'})
.one('click', function() {
$btn2.popover('destroy')
.popover({ trigger: 'click'})
.popover('show');
});
</code></pre> |
18,697,278 | How to style SVG <g> element? | <p>I have some SVG elements grouped together in a <code><g></code> element. I just want to style that <code><g></code> element to show grouping of elements. Like I want to give some background-color and a border to it. How it would be achieved?</p>
<p>I tried <code>fill</code> and <code>stroke</code> attribute to <code><g></code> element, but it doesn't work. How it would be possible? Thanks in advance!</p>
<p><a href="http://jsfiddle.net/VBmbP/1/" rel="noreferrer">Sample Here</a></p>
<pre><code><svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<g fill="blue" stroke="2">
<rect id="svg_6" height="112" width="84" y="105" x="136" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke-width="5" stroke="#000000" fill="#00ff00"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="271" cy="156" id="svg_7" rx="64" ry="56"/>
</g>
</svg>
</code></pre> | 18,698,798 | 4 | 2 | null | 2013-09-09 11:31:38.327 UTC | 10 | 2020-02-23 11:09:50.907 UTC | 2014-09-28 17:36:30.563 UTC | null | 1,696,030 | null | 2,031,628 | null | 1 | 64 | javascript|jquery|html|css|svg | 133,675 | <p>You actually cannot draw <a href="http://www.w3.org/TR/SVG11/intro.html#TermContainerElement">Container Elements</a></p>
<p>But you can use a "foreignObject" with a "SVG" inside it to simulate what you need.</p>
<p><a href="http://jsfiddle.net/VBmbP/4/">http://jsfiddle.net/VBmbP/4/</a></p>
<pre><code><svg width="640" height="480" xmlns="http://www.w3.org/2000/svg">
<foreignObject id="G" width="300" height="200">
<svg>
<rect fill="blue" stroke-width="2" height="112" width="84" y="55" x="55" stroke-linecap="null" stroke-linejoin="null" stroke-dasharray="null" stroke="#000000"/>
<ellipse fill="#FF0000" stroke="#000000" stroke-width="5" stroke-dasharray="null" stroke-linejoin="null" stroke-linecap="null" cx="155" cy="65" id="svg_7" rx="64" ry="56"/>
</svg>
<style>
#G {
background: #cff; border: 1px dashed black;
}
#G:hover {
background: #acc; border: 1px solid black;
}
</style>
</foreignObject>
</svg>
</code></pre> |
26,389,899 | Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation) | <p>I am trying to mitigate our vulnerability to the <a href="https://www.openssl.org/~bodo/ssl-poodle.pdf" rel="noreferrer">Poodle SSL 3.0 Fallback</a> attack. Our admins have already started disabling SSL in favor of TLS for inbound connections to our servers. And we have also advised our team to disable SSL in their web browsers. I'm now looking at our .NET codebase, which initiates HTTPS connections with various services through <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.110).aspx" rel="noreferrer">System.Net.HttpWebRequest</a>. I believe that these connections could be vulnerable to a MITM attack if they allow fallback from TLS to SSL. Here is what I have determined so far. Could some one please double-check this to verify that I am right? This vulnerability is brand new, so I have yet to see any guidance from Microsoft on how to mitigate it in .NET:</p>
<ol>
<li><p>The allowed protocols for the System.Net.Security.SslStream class, which underpins secure communication in .NET, are set globally for each AppDomain via the <strong>System.Net.ServicePointManager.SecurityProtocol</strong> property.</p></li>
<li><p>The default value of this property in .NET 4.5 is <code>Ssl3 | Tls</code> (although I can't find documentation to back that up.) SecurityProtocolType is an enum with the Flags attribute, so it's a bitwise <em>OR</em> of those two values. You can check this in your environment with this line of code: </p>
<p><strong>Console.WriteLine(System.Net.ServicePointManager.SecurityProtocol.ToString());</strong></p></li>
<li><p>This should be changed to just <code>Tls</code>, or perhaps <code>Tls12</code>, before you initiate any connections in your app:</p>
<p><strong>System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;</strong></p></li>
<li><p><strong>Important:</strong> Since the property supports multiple bitwise flags, I assume that the SslStream will <strong>not</strong> automatically fallback to other unspecified protocols during handshake. Otherwise, what would be the point of supporting multiple flags?</p></li>
</ol>
<p><strong>Update on TLS 1.0 vs 1.1/1.2:</strong></p>
<p>According to Google security expert Adam Langley, <a href="https://www.imperialviolet.org/2014/12/08/poodleagain.html" rel="noreferrer">TLS 1.0 was later found to be vulnerable to POODLE if not implemented correctly</a>, so you should consider moving to TLS 1.2 exclusively.</p>
<p><strong>Update for .NET Framework 4.7 and above:</strong></p>
<p>As alluded to by <a href="https://stackoverflow.com/a/35851145">Prof Von Lemongargle</a> below, starting with version 4.7 of the .NET Framework, there is no need to use this hack as the default setting will allow the OS to choose the most secure TLS protocol version. See <a href="https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls" rel="noreferrer">Transport Layer Security (TLS) best practices with the .NET Framework</a> for more information.</p> | 26,392,698 | 6 | 3 | null | 2014-10-15 18:48:27.11 UTC | 51 | 2020-01-21 00:32:54.807 UTC | 2020-01-21 00:32:54.807 UTC | null | 1,127,428 | null | 284,704 | null | 1 | 111 | .net|ssl | 134,600 | <p>We are doing the same thing. To support only TLS 1.2 and no SSL protocols, you can do this:</p>
<pre><code>System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
</code></pre>
<p>SecurityProtocolType.Tls is only TLS 1.0, not all TLS versions.</p>
<p>As a side: If you want to check that your site does not allow SSL connections, you can do so here (I don't think this will be affected by the above setting, we had to edit the registry to force IIS to use TLS for incoming connections):
<a href="https://www.ssllabs.com/ssltest/index.html">https://www.ssllabs.com/ssltest/index.html</a></p>
<p>To disable SSL 2.0 and 3.0 in IIS, see this page: <a href="https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html">https://www.sslshopper.com/article-how-to-disable-ssl-2.0-in-iis-7.html</a></p> |
4,902,523 | How to get the URL of a redirect with Python | <p>In Python, I'm using urllib2 to open a url. This url redirects to another url, which redirects to yet another url. </p>
<p>I wish to print out the url after each redirect.</p>
<p>For example</p>
<p>-> = redirects to</p>
<p>A -> B -> C -> D</p>
<p>I want to print the URL of B, C and D (A is already known because it's the start URL).</p> | 4,902,605 | 3 | 1 | null | 2011-02-04 20:19:52.787 UTC | 10 | 2020-03-29 14:19:46.99 UTC | null | null | null | null | 284,016 | null | 1 | 35 | python|redirect|urllib2 | 40,689 | <p>Probably the best way is to subclass <code>urllib2.HTTPRedirectHandler</code>. Dive Into Python's <a href="http://www.diveintopython.net/http_web_services/redirects.html">chapter on redirects</a> may be helpful.</p> |
5,175,034 | cvc-complex-type.2.4.a: Invalid content was found starting with element 'init-param' | <p>This is my <code>web.xml</code> xsd</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</code></pre>
<p>Here is servlet node</p>
<pre><code><servlet>
<servlet-name>spring1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param> <!-- here is a problem -->
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
</servlet>
</code></pre>
<p>On the marked line xml validator says</p>
<blockquote>
<p>cvc-complex-type.2.4.a: Invalid content was found starting with element 'init-param'. One of '{"<a href="http://java.sun.com/xml/ns/javaee" rel="noreferrer">http://java.sun.com/xml/ns/javaee</a>":enabled, "<a href="http://java.sun.com/xml/ns/javaee" rel="noreferrer">http://java.sun.com/xml/ns/javaee</a>":async-supported, "<a href="http://java.sun.com/xml/ns/javaee" rel="noreferrer">http://java.sun.com/xml/ns/javaee</a>":run-as, "<a href="http://java.sun.com/xml/ns/javaee" rel="noreferrer">http://java.sun.com/xml/ns/javaee</a>":security-role-ref, "<a href="http://java.sun.com/xml/ns/javaee" rel="noreferrer">http://java.sun.com/xml/ns/javaee</a>":multipart-config}' is expected.</p>
</blockquote>
<p>What is wrong and how do I correct this error?</p> | 5,175,139 | 3 | 0 | null | 2011-03-03 00:01:27.94 UTC | 8 | 2020-02-06 09:58:27.043 UTC | 2016-02-14 08:53:57.653 UTC | null | 157,882 | null | 471,149 | null | 1 | 47 | servlets|xsd|web.xml|init-parameters | 55,038 | <p>The order of elements in <code>web.xml</code> matters and in all examples I've come across, the <code><load-on-startup></code> comes after <code><init-param></code>.</p>
<pre><code><servlet>
<servlet-name>spring1</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
</code></pre> |
43,419,975 | Installing downloaded tar.gz files with pip | <p>When I download <code>PyGUI-2.5.4.tar.gz</code> from <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/" rel="noreferrer">http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/</a> and then run</p>
<pre><code>pip install downloads/PyGUI-2.5.4.tar.gz
</code></pre>
<p>I get a long error, the root of which appears to be the following:</p>
<pre><code>tarfile.ReadError: not a gzip file
</code></pre>
<p>Any ideas what I'm doing wrong?</p> | 43,420,234 | 2 | 3 | null | 2017-04-14 22:21:57.8 UTC | 1 | 2019-05-14 09:20:53.443 UTC | null | null | null | null | 3,219,839 | null | 1 | 6 | python|pip|pygui | 46,915 | <p>You can install tar.gz with pip Install a particular source archive file. </p>
<pre><code>pip install ./Package-1.0.4.tar.gz
</code></pre>
<p>You can also install it with extracting tar.gz file. First you should extract it using using tar command. </p>
<pre><code>tar -xzvf PyGUI-2.5.4.tar.gz
cd PyGUI-2.5.4.tar.gz
</code></pre>
<p>And then use the setup.py file to install the package .</p>
<pre><code>python setup.py install
</code></pre>
<p>or</p>
<pre><code>sudo python setup.py install
</code></pre>
<p>( use sudo only in linux )</p>
<p>Source: <a href="https://pip.readthedocs.io/en/stable/reference/pip_install/#git" rel="noreferrer">https://pip.readthedocs.io/en/stable/reference/pip_install/#git</a></p> |
43,217,872 | Laravel - htmlspecialchars() expects parameter 1 to be string, object given | <p>I go this error: </p>
<pre><code>htmlspecialchars() expects parameter 1 to be string, object given
</code></pre>
<p>I'm using in controller:</p>
<pre><code>$data = '{"pr":{"code":"1"},"ac":[[{"icon":"web","action":"link","url":"asd"}]]}'
$newData = json_decode($data);
</code></pre>
<p>And i send it to the view as array: 'data' => $newData
And when i try to use $data into the view, it give me that error</p>
<p>Tried already to use $data->ac OR $data['ac'] but still the same...
Some help, please?</p> | 43,218,105 | 5 | 4 | null | 2017-04-04 21:18:27.037 UTC | 8 | 2022-01-18 14:07:44.167 UTC | null | null | null | null | 7,764,584 | null | 1 | 42 | php|laravel | 264,894 | <p>When you use a blade echo <code>{{ $data }}</code> it will automatically escape the output. It can only escape strings. In your data <code>$data->ac</code> is an array and <code>$data</code> is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do <code>{{ $data->ac[0][0]['url'] }}</code> (not sure why you have two nested arrays but I'm just following your data structure).</p>
<pre><code>@foreach($data->ac['0'] as $link)
<a href="{{ $link['url'] }}">This is a link</a>
@endforeach
</code></pre> |
9,043,820 | Regex to match words of a certain length | <p>I would like to know the regex to match words such that the words have a maximum length.
for eg, if a word is of maximum 10 characters in length, I would like the regex to match, but if the length exceeds 10, then the regex should not match. </p>
<p>I tried </p>
<pre><code>^(\w{10})$
</code></pre>
<p>but that brings me matches only if the minimum length of the word is 10 characters. If the word is more than 10 characters, it still matches, but matches only first 10 characters. </p> | 9,043,828 | 7 | 4 | null | 2012-01-28 08:01:24.283 UTC | 19 | 2022-06-20 09:57:02.097 UTC | 2015-11-20 21:44:36.863 UTC | null | 236,345 | null | 945,672 | null | 1 | 103 | java|regex | 260,792 | <p>I think you want <code>\b\w{1,10}\b</code>. The <code>\b</code> matches a word boundary.</p>
<p>Of course, you could also replace the <code>\b</code> and do <code>^\w{1,10}$</code>. This will match a word of at most 10 characters as long as its the only contents of the string. I think this is what you were doing before.</p>
<p>Since it's Java, you'll actually have to escape the backslashes: <code>"\\b\\w{1,10}\\b"</code>. You probably knew this already, but it's gotten me before.</p> |
15,376,839 | Socket.IO with Ember and Ember-Data | <p>I've been poking around and I can't find any up to date examples of ember (1.0.0-rc.1) and ember-data(revision 11) that also use socket.io. I've tried something like this.</p>
<pre><code>App.ApplicationRoute = Ember.Route.extend({
setupController: function(controller, data) {
var socket = io.connect(),
self = this;
socket.on('apartment/new', function(apartment) {
var apt = App.Apartment.createRecord(apartment);
self.controllerFor('apartments').pushObject(apt);
});
}
});
</code></pre>
<p>This actually will create a new model class, it pushes the object to the controller, and creates a new li but the values do not render.</p>
<pre><code><ul class="list-view">
{{#each apartment in controller}}
<li>
{{#linkTo 'apartment' apartment }}
<span class="date">{{date apartment.date}}</span>
{{apartment.title}}
{{/linkTo}}
</li>
{{/each}}
</ul>
</code></pre>
<p>Does this have something to do with the run loop? How do force the values to render? Or is there a better approach to this?</p> | 15,447,665 | 2 | 0 | null | 2013-03-13 04:03:21.907 UTC | 19 | 2014-09-02 00:28:28.023 UTC | 2013-08-28 22:49:37.72 UTC | null | 2,431,285 | null | 228,833 | null | 1 | 18 | ember.js|socket.io|ember-data | 5,865 | <p>There's a very simple solution to this which I'm using in some of my apps. You can either have a general purpose callback for the socket and accept any kind of data</p>
<pre><code>callback: function(message) {
// this is better than just `eval`
var type = Ember.get(Ember.lookup, message.type);
store.load(type, message.data);
}
</code></pre>
<p>or here it is specifically tailored to your use case</p>
<pre><code>socket.on('apartment/new', function(apartment) {
store.load(App.Apartment, apartment);
});
</code></pre>
<p>using <code>store.load</code> will load the record data directly into the identity map. There's also <code>loadMany</code> for loading multiple records.</p> |
15,001,822 | Sending large image data over HTTP in Node.js | <p>In my development environment I have two servers. One sends and image to the other over a <code>POST</code> http request.</p>
<p>Client server does this:</p>
<pre><code> fs.readFile(rawFile.path,'binary',function (err, file){
restler.post("http://0.0.0.0:5000",{
data: file,
headers:{
"Content-Type": rawFile.type,
}
}).on('complete',function(data,response){
console.log(data);
res.send("file went through")
})
</code></pre>
<p>The server that recieves the request does this:</p>
<pre><code> server.post('/',function(req,res,next){
fs.writeFileSync("test.png",req.body,"binary",function(err){
if(err) throw err;
res.send("OK")
})
})
</code></pre>
<p>If i send a small image it works fine. However, if i send a large image although the file is saved correctly only the first upper portion of the image is displayed. The rest is black. Image size is correct.</p>
<p>I guess it's just the first chunk of the image that's being written on the file.
I've tried creating a <code>readStream</code> and a <code>writeStream</code> but it doesn't seem to work:</p>
<pre><code>req.body.pipe(fs.createWriteStream('test.png'))
</code></pre>
<p>Can i stream directly from the binary data and <code>pipe</code> it into the file? For what i've seen, <code>readStream</code> is often used to stream from files not raw binary data.</p>
<p>I read a few <a href="https://stackoverflow.com/questions/14170210/nodejs-createwritestream-vs-writefile">post</a>s but it doesn't seem to work for me.</p>
<p>I'm using <code>restler</code> module in the client server and <code>restify</code> in the other.</p>
<p>Thanks!</p> | 15,007,987 | 3 | 0 | null | 2013-02-21 12:04:00.727 UTC | 20 | 2013-09-06 18:38:00.79 UTC | 2017-05-23 11:33:26.943 UTC | null | -1 | null | 1,100,238 | null | 1 | 29 | image|node.js|http | 37,835 | <p>Sorry to be blunt, but there's a lot wrong here.</p>
<p><a href="http://nodejs.org/api/fs.html#fs_fs_readfile_filename_encoding_callback"><code>readFile</code></a> reads the <em>entire contents</em> of a file into memory before invoking the callback, at which point you begin uploading the file.</p>
<p>This is bad–especially when dealing with large files like images–because there's really no reason to read the file into memory. It's wasteful; and under load, you'll find that your server will run out of memory and crash.</p>
<p>Instead, you want to get a <em>stream</em>, which emits chunks of data as they're read from disk. All you have to do is pass those chunks along to your upload stream (<code>pipe</code>), and then discard the data from memory. In this way, you never use more than a small amount of buffer memory.</p>
<p>(A readable stream's default behavior is to deal in raw binary data; it's only if you pass an <code>encoding</code> that it deals in text.)</p>
<p>The <a href="https://github.com/mikeal/request">request</a> module makes this especially easy:</p>
<pre><code>fs.createReadStream('test.png').pipe(request.post('http://0.0.0.0:5000/'));
</code></pre>
<p>On the server, you have a larger problem. <strong>Never use *<code>Sync</code> methods.</strong> It blocks your server from doing <em>anything</em> (like responding to other requests) until the entire file is flushed to disk, which can take seconds.</p>
<p>So instead, we want to take the incoming data stream and pipe it to a filesystem stream. You were on the right track originally; the reason that <code>req.body.pipe(fs.createWriteStream('test.png'))</code> didn't work is because <code>body</code> is not a stream.</p>
<p><code>body</code> is generated by the <code>bodyParser</code> middleware. In restify, that middleware acts much like <code>readFile</code> in that it buffers the entire incoming request-entity in memory. In this case, we don't want that. Disable the body parser middleware.</p>
<p>So where is the incoming data stream? It is the <code>req</code> object itself. restify's <code>Request</code> inherits node's <code>http.IncomingMessage</code>, which is a readable stream. So:</p>
<pre><code>fs.createWriteStream('test.png').pipe(req);
</code></pre>
<hr>
<p>I should also mention that this all works so simply because there's no form parsing overhead involved. request simply sends the file with no <code>multipart/form-data</code> wrappers:</p>
<pre class="lang-none prettyprint-override"><code>POST / HTTP/1.1
host: localhost:5000
content-type: application/octet-stream
Connection: keep-alive
Transfer-Encoding: chunked
<image data>...
</code></pre>
<p>This means that a browser could not post a file to this URL. If that's a need, look in to <a href="https://github.com/felixge/node-formidable">formidable</a>, which does streaming parsing of request-entities.</p> |
15,347,541 | What does ApplicationIntent=ReadOnly mean in the connection string | <p>I am using MS Access to connect to Sql Server through a DSN connection. This is a linked table to a sql server backend. Here is the connection string</p>
<pre><code>ODBC;DSN=mydsn;Description=mydesc;Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=mydb;ApplicationIntent=READONLY;;TABLE=dbo.mytable
</code></pre>
<p>As you can see there is a <code>ApplicationIntent=READONLY</code> tag in the connection string. What does this mean. Am I connecting to the database in a read only fashion? Is it recommended to perform updates and inserts using this connection string?</p> | 15,347,697 | 1 | 0 | null | 2013-03-11 20:02:36.377 UTC | 9 | 2022-08-09 20:11:50.293 UTC | null | null | null | null | 184,773 | null | 1 | 31 | sql-server|ms-access | 58,497 | <p>This means that if you are using Availability Groups in SQL Server 2012, the engine knows that your connections are read only and can be routed to read-only replicas (if they exist). Some information here:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/hh213002.aspx" rel="nofollow noreferrer">Configure Read-Only Access on an Availability Replica</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/hh213417.aspx" rel="nofollow noreferrer">Availability Group Listeners, Client Connectivity, and Application Failover</a></li>
</ul>
<p>If you are not currently using Availability Groups, it <em>may</em> be a good idea to leave that in there for forward compatibility, but it really depends on whether or not you are intentionally only just reading. This should prevent writes but there are some caveats. These Connect items may be useful or may leave you scratching your head. I'll confess I haven't read them through.</p>
<ul>
<li><a href="https://web.archive.org/web/20130125015414/http://connect.microsoft.com/SQLServer/feedback/details/697217/applicationintent-readonly-allows-updates-to-a-database" rel="nofollow noreferrer">ApplicationIntent=ReadOnly allows updates to a database</a></li>
<li><a href="https://web.archive.org/web/20130726222919/http://connect.microsoft.com/SQLServer/feedback/details/700331/applicationintent-readonly-does-not-send-the-connection-to-the-secondary-copy" rel="nofollow noreferrer">ApplicationIntent=ReadOnly does not send the connection to the secondary copy</a></li>
</ul> |
15,174,477 | How is GetHashCode() of C# string implemented? | <p>I'm just curious because I guess it will have impact on performance. Does it consider the full string? If yes, it will be slow on long string. If it only consider part of the string, it will have bad performance (e.g. if it only consider the beginning of the string, it will have bad performance if a HashSet contains mostly strings with the same.</p> | 15,176,541 | 2 | 4 | null | 2013-03-02 12:29:04.19 UTC | 13 | 2015-09-14 15:24:34.617 UTC | null | null | null | null | 385,387 | null | 1 | 69 | c#|.net|string|hash|gethashcode | 38,256 | <p>Be sure to obtain the <a href="http://referencesource.microsoft.com/#mscorlib/system/string.cs" rel="noreferrer">Reference Source source code</a> when you have questions like this. There's a lot more to it than what you can see from a decompiler. Pick the one that matches your preferred .NET target, the method has changed a great deal between versions. I'll just reproduce the .NET 4.5 version of it here, retrieved from Source.NET 4.5\4.6.0.0\net\clr\src\BCL\System\String.cs\604718\String.cs</p>
<pre><code> public override int GetHashCode() {
#if FEATURE_RANDOMIZED_STRING_HASHING
if(HashHelpers.s_UseRandomizedStringHashing)
{
return InternalMarvin32HashString(this, this.Length, 0);
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING
unsafe {
fixed (char *src = this) {
Contract.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
Contract.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
#if WIN32
int hash1 = (5381<<16) + 5381;
#else
int hash1 = 5381;
#endif
int hash2 = hash1;
#if WIN32
// 32 bit machines.
int* pint = (int *)src;
int len = this.Length;
while (len > 2)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
if (len > 0)
{
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
}
#else
int c;
char *s = src;
while ((c = s[0]) != 0) {
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
break;
hash2 = ((hash2 << 5) + hash2) ^ c;
s += 2;
}
#endif
#if DEBUG
// We want to ensure we can change our hash function daily.
// This is perfectly fine as long as you don't persist the
// value from GetHashCode to disk or count on String A
// hashing before string B. Those are bugs in your code.
hash1 ^= ThisAssembly.DailyBuildNumber;
#endif
return hash1 + (hash2 * 1566083941);
}
}
}
</code></pre>
<p>This is possibly more than you bargained for, I'll annotate the code a bit:</p>
<ul>
<li>The #if conditional compilation directives adapt this code to different .NET targets. The FEATURE_XX identifiers are defined elsewhere and turn features off whole sale throughout the .NET source code. WIN32 is defined when the target is the 32-bit version of the framework, the 64-bit version of mscorlib.dll is built separately and stored in a different subdirectory of the GAC.</li>
<li>The s_UseRandomizedStringHashing variable enables a secure version of the hashing algorithm, designed to keep programmers out of trouble that do something unwise like using GetHashCode() to generate hashes for things like passwords or encryption. It is enabled by <a href="http://msdn.microsoft.com/en-us/library/jj152924.aspx" rel="noreferrer">an entry</a> in the app.exe.config file</li>
<li>The <em>fixed</em> statement keeps indexing the string cheap, avoids the bounds checking done by the regular indexer</li>
<li>The first Assert ensures that the string is zero-terminated as it should be, required to allow the optimization in the loop</li>
<li>The second Assert ensures that the string is aligned to an address that's a multiple of 4 as it should be, required to keep the loop performant</li>
<li>The loop is unrolled by hand, consuming 4 characters per loop for the 32-bit version. The cast to int* is a trick to store 2 characters (2 x 16 bits) in a int (32-bits). The extra statements after the loop deal with a string whose length is not a multiple of 4. Note that the zero terminator may or may not be included in the hash, it won't be if the length is even. It looks at <em>all</em> the characters in the string, answering your question</li>
<li>The 64-bit version of the loop is done differently, hand-unrolled by 2. Note that it terminates early on an embedded zero, so doesn't look at all the characters. Otherwise very uncommon. That's pretty odd, I can only guess that this has something to do with strings potentially being very large. But can't think of a practical example</li>
<li>The debug code at the end ensures that no code in the framework ever takes a dependency on the hash code being reproducible between runs.</li>
<li>The hash algorithm is pretty standard. The value 1566083941 is a magic number, a prime that is common in a <a href="http://en.wikipedia.org/wiki/Mersenne_twister" rel="noreferrer">Mersenne twister</a>.</li>
</ul> |
8,310,926 | Active admin customization | <p>I have an <code>Event</code> model with field status, which is string so it appears as a <code>text_field</code>. But I have a list of possible statuses and I want to display it as a <code>select</code> box. Also, when I select <code>cancel</code> status for a event it should ask me for the cancellation reason. I am not able to find good tutorial for this.</p> | 8,311,208 | 2 | 0 | null | 2011-11-29 12:45:31.927 UTC | 23 | 2016-09-30 07:58:42.683 UTC | 2016-08-16 05:13:24.95 UTC | null | 2,202,702 | null | 230,293 | null | 1 | 14 | ruby-on-rails|activeadmin | 20,252 | <p>ActiveAdmin uses Formtastic for form generation, so <a href="https://github.com/justinfrench/formtastic" rel="noreferrer">Formtastic's documentation</a> should answer your questions.</p>
<p>You can get a select instead of a textfield with the following code:</p>
<pre><code>form do |f|
f.status, :as => :select, :collection => STATUSES #whatever collection you want to display
end
</code></pre>
<p>Triggering an event when selecting "cancelled" should be solved with javascript.</p> |
8,040,002 | How to make a WCF REST method entirely asynchronous with the Task Parallel Library? | <p>I am trying to make a WCF REST method entirely asynchronous (I don't want to block anywhere). Essentially I have a simple service with 3 layers: Service, Business Logic and Data Access Layer. The Data Access Layer is accessing a database and it can take several second to get a response back from that method. </p>
<p>I don't understand very well how to chaining of all those method work. Can someone please help me to complete the sample I am trying to write below? I don't understand well the pattern used by WCF and I didn't find much documentation on the subject.</p>
<p>Can someone help me to complete the following example? In addition, how can I measure that the service will be able to handle more load than a typical synchronous implementation?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Threading.Tasks;
namespace WcfRestService1
{
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{
private BusinessLogic bll = new BusinessLogic();
// Synchronous version
[WebGet(UriTemplate = "/sync")]
public string GetSamples()
{
return bll.ComputeData();
}
// Asynchronous version - Begin
[WebGet(UriTemplate = "/async")]
[OperationContract(AsyncPattern = true)]
public IAsyncResult BeginGetSampleAsync(AsyncCallback callback,
object state)
{
Task<string> t = bll.ComputeDataAsync();
// What am I suppose to return here
// return t.AsyncState; ???
}
// Asynchronous version - End
public List<SampleItem> EndGetSampleAsync(IAsyncResult result)
{
// How do I handle the callback here?
}
}
public class BusinessLogic
{
public Task<string> ComputeDataAsync()
{
DataAccessLayer dal = new DataAccessLayer();
return dal.GetData();
}
public string ComputeData()
{
Task<string> t = this.ComputeDataAsync();
// I am blocking... Waiting for the data
t.Wait();
return t.Result;
}
}
public class DataAccessLayer
{
public Task<string> GetData()
{
// Read data from disk or network or db
}
}
}
</code></pre> | 8,303,493 | 2 | 5 | null | 2011-11-07 17:14:54.99 UTC | 9 | 2011-11-29 17:32:22.58 UTC | 2011-11-28 03:58:06.53 UTC | null | 42,024 | null | 42,024 | null | 1 | 21 | c#|wcf|asynchronous|task-parallel-library | 6,365 | <p>Here's an example. I got it working with help from the following posts:</p>
<p><strong>Edit: Added an example of an async client</strong></p>
<p><a href="https://stackoverflow.com/questions/5161159/implement-classic-async-pattern-using-tpl">Implement Classic Async Pattern using TPL</a><br>
<a href="http://pfelix.wordpress.com/2008/06/27/wcf-and-the-asyncpattern-property-part-1/" rel="nofollow noreferrer">http://pfelix.wordpress.com/2008/06/27/wcf-and-the-asyncpattern-property-part-1/</a>
<a href="http://pfelix.wordpress.com/2008/06/28/wcf-and-the-asyncpattern-part-2/" rel="nofollow noreferrer">http://pfelix.wordpress.com/2008/06/28/wcf-and-the-asyncpattern-part-2/</a> </p>
<p>Here's a little do-nothing service:</p>
<pre>
<code>
namespace WcfAsyncTest
{
[ServiceContract]
public interface IAsyncTest
{
[OperationContract(AsyncPattern=true)]
IAsyncResult BeginOperation(AsyncCallback callback, object state);
string EndOperation(IAsyncResult ar);
}
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1 : IAsyncTest
{
public IAsyncResult BeginOperation(AsyncCallback callback, object state)
{
Task result = Task.Factory.StartNew((x) =>
{
// spin to simulate some work
var stop = DateTime.Now.AddSeconds(10);
while (DateTime.Now < stop)
Thread.Sleep(100);
}, state);
if (callback != null)
result.ContinueWith(t => callback(t));
return result;
}
public string EndOperation(IAsyncResult ar)
{
ar.AsyncWaitHandle.WaitOne();
return "Hello!!";
}
}
}
</code>
</pre>
<p>And here's the client (command line):</p>
<pre>
<code>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestClient
{
class Program
{
static void Main(string[] args)
{
var client = new ServiceReference1.AsyncTestClient();
var result = client.Operation();
Console.WriteLine(result);
Console.ReadLine();
}
}
}
</code>
</pre>
<p>if you put trace points on the service, you can see that WCF really is calling EndOperation for you.</p>
<p><strong>Async Client Example</strong> </p>
<p>First, you will need to generate an async proxy. You can do that by right-clicking on the Service Reference (in the References Folder of your project), and choosing "Configure Service Reference". Check the "Generate Asynchronous Operations" checkbox.</p>
<p>Now your client proxy will have some new members that weren't there before. Here's how to use them:</p>
<pre>
<code>
// this is in the command-line test client
// no changes to your service required.
static void AsyncTest()
{
var client = new ServiceReference1.AsyncTestClient();
client.OperationCompleted += new EventHandler(client_OperationCompleted);
client.OperationAsync();
Console.WriteLine("Operation Running");
}
static void client_OperationCompleted(object sender, ServiceReference1.OperationCompletedEventArgs e)
{
if (e.Error == null)
Console.WriteLine("Operation Complete. Result: " + e.Result);
else
Console.WriteLine(e.Error.ToString());
}
</code>
</pre> |
23,855,518 | Fatal error: Uncaught exception 'PDOException' with message | <p>I am trying to run a MySQL PDO query. I am not sure why I am getting a fatal error. I have checked other posts, but their answers don't seem to solve mine.</p>
<p>The script is connecting to the database fine. The username and password are correct and I have removed them in the script below.</p>
<p>My output:</p>
<pre><code>Connected to database
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'nobody'@'localhost' (using password: NO)' in /home/a/public_html/d/inc/header.php:34 Stack trace: #0 /home/a/public_html/d/inc/header.php(34): PDO->__construct('mysql:host=;dbn...', NULL, NULL) #1 /home/a/public_html/d/inc/header.php(43): testdb_connect() #2 /home/a/public_html/d/article.php(3): include('/home/a/p...') #3 {main} thrown in /home/a/public_html/d/inc/header.php on line 34
</code></pre>
<p>My code:</p>
<pre><code><?php
/*** MySQL hostname ***/
$hostname = 'localhost';
/*** MySQL username ***/
$username = 'removed';
/*** MySQL password ***/
$password = 'removed';
try {
function testdb_connect(){
$dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
return ($dbh);
}
echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh = testdb_connect();
$id = $_GET[id];
echo 'dfsdfs ' . $id;
var_dump($dbh);
$sql = "SELECT * FROM 'radiologyArticles' WHERE 'id' = :id";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
?>
<section>
<header>
<h2><?php echo $row['articleTitle']; ?></h2>
<h3>A generic two column layout</h3>
</header>
<p>
<?php echo $row['articleBody']; ?>
</p>
</section>
<?php
}
// Close the PDO connection
$link = null;
?>
</code></pre> | 23,855,586 | 1 | 7 | null | 2014-05-25 12:57:47.827 UTC | null | 2020-04-21 15:58:52.503 UTC | 2020-04-21 15:57:53.787 UTC | null | 63,550 | null | 2,036,386 | null | 1 | 3 | php|mysql|pdo | 52,928 | <pre><code>/*** MySQL hostname ***/
$hostname = 'localhost';
/*** MySQL username ***/
$username = 'removed';
/*** MySQL password ***/
$password = 'removed';
function testdb_connect ($hostname, $username, $password){
$dbh = new PDO("mysql:host=$hostname;dbname=removed", $username, $password);
return $dbh;
}
try {
$dbh = testdb_connect ($hostname, $username, $password);
echo 'Connected to database';
} catch(PDOException $e) {
echo $e->getMessage();
}
</code></pre> |
19,517,868 | Integer division by negative number | <p>What should integer division -1 / 5 return? I am totally confused by this behaviour. I think mathematically it should be 0, but python and ruby are returning -1.</p>
<p>Why are different languages behaving differently here? Please someone explain. Thanks.</p>
<pre><code>| Language | Code | Result |
|-----------+----------------+--------|
| ruby | -1 / 5 | -1 |
| python | -1 / 5 | -1 |
| c | -1 / 5 | 0 |
| clojure | (int (/ -1 5)) | 0 |
| emacslisp | (/ -1 5) | 0 |
| bash | expr -1 / 5 | 0 |
</code></pre> | 19,518,866 | 2 | 9 | null | 2013-10-22 12:26:34.643 UTC | 15 | 2019-07-09 14:57:16.483 UTC | 2014-06-04 18:06:14.51 UTC | null | 2,443,656 | null | 2,443,656 | null | 1 | 35 | python|ruby|math | 12,952 | <p><strong>Short answer:</strong> Language designers get to choose if their language will round towards zero, negative infinity, or positive infinity when doing integer division. Different languages have made different choices.</p>
<p><strong>Long answer:</strong> The language authors of Python and Ruby both decided that rounding towards negative infinity makes more sense than rounding towards zero (like C does). The creator of python wrote a blog post about his reasoning <a href="http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html">here</a>. I've excerpted much of it below.</p>
<blockquote>
<p>I was asked (again) today to explain why integer division in Python returns the floor of the result instead of truncating towards zero like C.</p>
<p>For positive numbers, there's no surprise:</p>
<pre><code>>>> 5//2
2
</code></pre>
<p>But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):</p>
<pre><code>>>> -5//2
-3
>>> 5//-2
-3
</code></pre>
<p>This disturbs some people, but there is a good mathematical reason.
The integer division operation (//) and its sibling, the modulo
operation (%), go together and satisfy a nice mathematical
relationship (all variables are integers):</p>
<pre><code>a/b = q with remainder r
</code></pre>
<p>such that</p>
<pre><code>b*q + r = a and 0 <= r < b
(assuming a and b are >= 0).
</code></pre>
<p>If you want the relationship to extend for negative a (keeping b
positive), you have two choices: if you truncate q towards zero, r
will become negative, so that the invariant changes to 0 <= abs(r) <
otherwise, you can floor q towards negative infinity, and the
invariant remains 0 <= r < b. [update: fixed this para]</p>
<p>In mathematical number theory, mathematicians always prefer the latter
choice (see e.g. <a href="http://en.wikipedia.org/wiki/Modulo_operation">Wikipedia</a>). For Python, I made the same choice
because there are some interesting applications of the modulo
operation where the sign of a is uninteresting. Consider taking a
POSIX timestamp (seconds since the start of 1970) and turning it into
the time of day. Since there are 24*3600 = 86400 seconds in a day,
this calculation is simply t % 86400. But if we were to express times
before 1970 using negative numbers, the "truncate towards zero" rule
would give a meaningless result! Using the floor rule it all works out
fine.</p>
</blockquote> |
8,409,180 | Reading data from bluetooth device in android | <p>I am using bluetooth chat in order to connect and recieve data from a bluetooth device.</p>
<p>I use the following code for reading data:</p>
<pre><code>public void run() {
byte[] buffer = new byte[1024];
int bytes;
Log.v("MR", "start listening....");
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
Log.d("MR", "buffer in try");
bytes = mmInStream.read(buffer);
Log.d("MR", "input stream :"+(new String(buffer)));
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Conn.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
Log.d("MR", "buffer after");
} catch (Exception e) {
Log.e("MR", "Error :"+e.getMessage());
//
connectionLost();
// break;
}
Log.d("MR", "buffer after while");
}
}
</code></pre>
<p>The device is sending data all the time without stopping.</p>
<p>With the above code I get the message of:</p>
<pre><code>Log.d("MR", "buffer in try");
</code></pre>
<p>then it goes to the next line:</p>
<pre><code>bytes=mmInStream.read(buffer);
</code></pre>
<p>and never returns from that call. I guess this is because it starts reading data from the device and doesn't stop until it disconnects. How can I read a certain amount of bytes at a time?</p>
<p><strong>EDIT</strong></p>
<p>Unless it stay to the <code>bytes = mmInStream.read(buffer);</code> code due to that it don;t get any data back on from the device?</p> | 8,421,825 | 1 | 3 | null | 2011-12-07 01:06:07.55 UTC | 10 | 2011-12-07 20:08:02.757 UTC | 2011-12-07 15:42:59.167 UTC | null | 260,197 | null | 1,041,204 | null | 1 | 16 | java|android|bluetooth | 35,294 | <p>I use DataInputStreams instead as you can do a readFully() method which waits to read a certain number of bytes before returning. I setup the BT connection like this:</p>
<pre><code>BluetoothDevice btDevice = bta.getRemoteDevice(macAddress);
BluetoothSocket btSocket = InsecureBluetooth.createRfcommSocketToServiceRecord(
btDevice, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), false);
btSocket.connect();
InputStream input = btSocket.getInputStream();
DataInputStream dinput = new DataInputStream(input);
</code></pre>
<p>then later on when I want to read I use readFully:</p>
<pre><code>dinput.readFully(byteArray, 0, byteArray.length);
</code></pre> |
8,583,339 | Key Shortcut for Eclipse Imports | <p>It's been a while since I last used Eclipse. I used to love this handy key shortcut that added all the imports to the top of the source file, but I've forgotten it. Does anyone know what this shortcut is?</p> | 8,583,357 | 9 | 5 | null | 2011-12-20 23:32:46.683 UTC | 24 | 2021-10-22 13:52:48.887 UTC | null | null | null | null | 754,087 | null | 1 | 99 | java|eclipse | 141,010 | <p><kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd> (<-- an 'O' not a zero)</p>
<p><strong>Note: This shortcut also removes unused imports.</strong> </p> |
4,960,375 | Accessing Local file using NSURL | <p>I am trying to access an XML file store in the resources directory. I am using NSURL to access this file using NSURLConnection( this file is going to be swapped out for a remote service in the future). </p>
<pre><code>NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"file:///XMLTest.xml"]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
response = [[NSMutableData data] retain];
} else {
NSLog(@"Could not create connection");
}
</code></pre>
<p>The class that starts the connection implements the NSURLConnection methods:</p>
<pre><code>connection:willCacheResponse:
connection:didReceiveData:
connectionDidFinishLoading:
connectionDidFinishLoading:
</code></pre>
<p>Once I launch this the simulator dies, no messages are printed to the console so I am at a loss for where to look. Any ideas, or am I just doing this completely wrong?</p> | 4,960,526 | 5 | 0 | null | 2011-02-10 17:16:02.007 UTC | 17 | 2020-08-27 05:42:25.007 UTC | null | null | null | null | 299,450 | null | 1 | 51 | iphone|ios | 76,474 | <p>This would also work:</p>
<h3>Obj-C</h3>
<pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"XMLTest" ofType:@"xml"];
</code></pre>
<h3>Swift 5</h3>
<pre><code>let url = Bundle.main.url(forResource: "XMLTest", withExtension: "xml")!
</code></pre>
<p>Hope this helps!</p> |
5,559,250 | C error: undefined reference to function, but it IS defined | <p>Just a simple program, but I keep getting this compiler error. I'm using MinGW for the compiler.</p>
<p>Here's the header file, <strong>point.h</strong>:</p>
<pre><code>//type for a Cartesian point
typedef struct {
double x;
double y;
} Point;
Point create(double x, double y);
Point midpoint(Point p, Point q);
</code></pre>
<p>And here's <strong>point.c</strong>:</p>
<pre><code>//This is the implementation of the point type
#include "point.h"
int main() {
return 0;
}
Point create(double x, double y) {
Point p;
p.x = x;
p.y = y;
return p;
}
Point midpoint(Point p, Point q) {
Point mid;
mid.x = (p.x + q.x) / 2;
mid.y = (p.y + q.y) / 2;
return mid;
}
</code></pre>
<p>And here's where the compiler issue comes in. I keep getting:</p>
<blockquote>
<p>testpoint.c: undefined reference to 'create(double x, double y)'</p>
</blockquote>
<p>While it is defined in point.c.</p>
<p>This is a separate file called <strong>testpoint.c</strong>:</p>
<pre><code>#include "point.h"
#include <assert.h>
#include <stdio.h>
int main() {
double x = 1;
double y = 1;
Point p = create(x, y);
assert(p.x == 1);
return 0;
}
</code></pre>
<p>I'm at a loss as to what the issue could be.</p> | 5,559,274 | 5 | 4 | null | 2011-04-05 22:18:11.263 UTC | 36 | 2022-05-02 21:28:25.303 UTC | 2017-03-17 13:30:19.357 UTC | null | 694,576 | null | 693,844 | null | 1 | 97 | c|function|linker-errors|undefined-reference | 505,419 | <p>How are you doing the compiling and linking? You'll need to specify both files, something like:</p>
<pre><code>gcc testpoint.c point.c
</code></pre>
<p>...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of <code>main</code>. You'll need/want to eliminate one (undoubtedly the one in point.c).</p>
<p>In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use <code>make</code> to do the work. In this case you'd have something like this:</p>
<pre><code>OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
</code></pre>
<p>The first is just a macro for the names of the object files. You get it expanded with <code>$(OBJS)</code>. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.</p>
<p>Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:</p>
<pre><code>.c.o:
$(CC) -c $(CFLAGS) $<
</code></pre>
<p>This assumes the name of the C compiler is in a macro named CC (implicitly defined like <code>CC=gcc</code>) and allows you to specify any flags you care about in a macro named <code>CFLAGS</code> (e.g., <code>CFLAGS=-O3</code> to turn on optimization) and <code>$<</code> is a special macro that expands to the name of the source file.</p>
<p>You typically store this in a file named <code>Makefile</code>, and to build your program, you just type <code>make</code> at the command line. It implicitly looks for a file named <code>Makefile</code>, and runs whatever rules it contains.</p>
<p>The good point of this is that <code>make</code> automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).</p>
<p>Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.</p> |
4,983,508 | Can I have an IF block in DOS batch file? | <p>In a DOS batch file we can only have 1 line if statement body? I think I found somewhere that I could use <code>()</code> for an if block just like the <code>{}</code> used in C-like programming languages, but it is not executing the statements when I try this. No error message either. This my code:</p>
<pre><code>if %GPMANAGER_FOUND%==true(echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
</code></pre>
<p>Strangely neither "GP Manager is up" nor "GP Manager is down" gets printed when I run the batch file.</p> | 4,983,613 | 5 | 2 | null | 2011-02-13 09:51:44.63 UTC | 9 | 2019-05-06 08:01:54.813 UTC | 2011-02-13 10:40:32.633 UTC | null | 366,904 | null | 474,323 | null | 1 | 110 | if-statement|batch-file | 260,732 | <p>You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:</p>
<pre><code>if <statement> (
do something
) else (
do something else
)
</code></pre>
<p>However, I do not believe that there is any built-in syntax for <code>else-if</code> statements. You will unfortunately need to create nested blocks of <code>if</code> statements to handle that.</p>
<p><br>
Secondly, that <code>%GPMANAGER_FOUND% == true</code> test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.</p>
<p><br>
The following sample code works fine for me:</p>
<pre><code>@echo off
if ERRORLEVEL == 0 (
echo GP Manager is up
goto Continue7
)
echo GP Manager is down
:Continue7
</code></pre>
<p>Please note a few specific details about my sample code:</p>
<ul>
<li>The space added between the end of the conditional statement, and the opening parenthesis.</li>
<li>I am setting <code>@echo off</code> to keep from seeing <em>all</em> of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with <code>echo</code>.</li>
<li>I'm using the built-in <code>ERRORLEVEL</code> variable just as a test. Read more <a href="http://www.robvanderwoude.com/errorlevel.php" rel="noreferrer">here</a></li>
</ul> |
5,200,811 | In Android, how do I smoothly fade the background from one color to another? (How to use threads) | <p>I've been playing with Android programming on and off for a couple of weeks, and I'm trying to get something to work that seems simple, but I think I am missing something.</p>
<p>What I am trying to do is have the background fade from, say, white to black smoothly.</p>
<p>I've tried a few things, none of which seem to work.</p>
<p>The first thing I did was using a for loop and the setBackgroundColor method for LinearLayout, changing the R, G, and B values together from 0 to 255. It doesn't work.</p>
<p>I can do one-of settings changes, but when I do the loop I get nothing but the last value. What I think is happening is the UI is locking up while the loop is in progress and unfreezing when the loop ends. I've tried putting delays in the loop (ugly nested loop delays and Thread.sleep), all to no avail.</p>
<p>Can anyone give me any pointers as to how to get this working? Do I need a second thread to do the change to the color? I've got a vague idea of threads, although I have never used them.</p>
<p>My sample code showing roughly what I am trying to do is as follows:</p>
<p>main.xml is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/screen"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
</code></pre>
<p>And my java code is (the 0.01 inc. is just to act as an ugly delay mechanism to try to see the viewing of colors change slowly):</p>
<pre><code>package nz.co.et.bgfader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
public class bgfader extends Activity {
LinearLayout screen;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
screen = (LinearLayout) findViewById(R.id.screen);
for (int i = 0; i < 65535; i+=0.01) {
screen.setBackgroundColor(0xff000000 + i);
}
}
}
</code></pre>
<p>Any help would be greatly appreciated</p>
<p>Cheers</p>
<p>Steve </p> | 5,200,906 | 6 | 0 | null | 2011-03-05 00:42:07.343 UTC | 15 | 2020-08-05 09:30:14.357 UTC | 2012-12-20 21:31:08.983 UTC | null | 645,613 | null | 645,613 | null | 1 | 35 | android | 37,053 | <p>In your loop, your setting on background is so fast that the UI is not (will not) able to schedule the update of display. Yes, you better use a second thread to update the background or else you will stall the UI thread. Try following:</p>
<pre><code>LinearLayout screen;
Handler handler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
screen = (LinearLayout) findViewById(R.id.screen);
(new Thread(){
@Override
public void run(){
for(int i=0; i<255; i++){
handler.post(new Runnable(){
public void run(){
screen.setBackgroundColor(Color.argb(255, i, i, i));
}
});
// next will pause the thread for some time
try{ sleep(10); }
catch{ break; }
}
}
}).start();
}
</code></pre>
<p>This is a threaded version of your code. </p> |
16,864,259 | How to run bash script after git push | <p>I wanted to know how to execute a bash script in the local repo after pushing to github. </p>
<p>The bash script is located in the root of the folder. It can be moved around depending on where it is being called I guess.
I have looked into git hooks but there is no post-push hook and I don't understand the other hooks very well.</p>
<p>I'm trying to call a jenkins build after the push. I have looked into ways of notifying jenkins after a push with post-receive url etc on github but nothing seems to work for me.</p>
<p>This is the script I'm trying to run:</p>
<pre><code>#!/bin/bash/
java -jar jenkins-cli.jar -s http://localhost:8080/ build Test
</code></pre>
<p>Thanks!
Varun</p> | 16,866,281 | 1 | 3 | null | 2013-05-31 19:12:07.057 UTC | 8 | 2019-01-31 06:24:34.503 UTC | null | null | null | null | 1,490,695 | null | 1 | 13 | git|bash|github|hook|githooks | 33,062 | <p>This is fairly easy. There is a script ready to run. You will have to modify .git/hooks/post-commit to find the script you need to run.</p>
<pre><code>mv .git/hooks/post-commit.sample .git/hooks/post-commit
vim .git/hooks/post-commit
</code></pre>
<p>I found this at: <a href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks" rel="nofollow noreferrer">git-scm.com: Git Hooks</a></p>
<p>If there is no <code>.git/hooks/post-commit.sample</code> file, not a problem, just create <code>.git/hooks/post-commit</code> from scratch (Remember to make the script executable with <code>chmod +x</code>), for example:</p>
<pre><code>#!/bin/sh
echo look at me I am the post-commit script
pwd
# call the script you want
</code></pre>
<p>Do a test commit and you should see the output of the script, right before the regular output of the commit.</p> |
12,269,470 | Selectbox disabled or enabled by an option of an other selectbox | <p>I try to create a relation/connexion beetwen 2 selectbox</p>
<pre><code><form id="creation" name="creation">
<select name="select01" id="select01">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
</select>
<select name="select02" id="select02">
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
</form>
</code></pre>
<p>I want that my selectbox <strong>select02</strong> be disabled at the begening, and when i click on <strong>value02</strong> or <strong>value03</strong>, we enable it, and when we click on <strong>value01</strong>, disable it.</p>
<p>There is my code js for the moment. I try to adapt it from an other function (radiobutton enabling a selectbox) but it doesn't seem to work. My list is disable at the beging, but the onclick is not working ...</p>
<p>Some body can help me?</p>
<pre><code>var oui = document.creation.select01[0];
document.getElementById("select02").disabled=true;
oui.onclick = function() {
document.getElementById("select02").disabled=false;
}
</code></pre>
<p>Ok, so NOW, i'm with this code:</p>
<pre><code><script>
var oui = document.select01;
document.getElementById("select02" ).disabled=true;
oui.onchange = function(){
document.getElementById("select02" ).disabled=false;
}
</script>
</code></pre>
<p>I change the value of my selec01, then my select02 is now enable .. but how can I target only 2 options of my select01 ?</p> | 12,269,844 | 4 | 0 | null | 2012-09-04 18:39:16.223 UTC | 2 | 2017-08-14 22:28:38.627 UTC | 2012-09-04 18:53:44.167 UTC | null | 1,431,309 | null | 1,431,309 | null | 1 | 12 | javascript|html|select | 61,183 | <p>Try this:</p>
<pre><code><form id="creation" name="creation" onchange="handleSelect()">
<select name="select01" id="select01">
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
</select>
<select name="select02" id="select02" disabled>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
</form>
</code></pre>
<p>And as a JS script:</p>
<pre><code> function handleSelect() {
if (this.value == '01') {
document.getElementById('select02').disabled = true;
} else {
document.getElementById('select02').disabled = false;
}
}
</code></pre>
<p>And a tip: explore jQuery, a very popular JS framework (jquery.com). You can achieve your task very simply by using it.</p> |
12,528,854 | How to perform rebase (squash) using tortoisegit | <p>Cannot get how to perform squash rebase for the current branch. The console command would be</p>
<pre><code>git rebase -i HEAD~2
</code></pre>
<p>and then squash as usually. But how to do the same in TGit?</p>
<p>Script to initialize the case</p>
<pre><code>git init .
touch 1
git add 1
git commit -m "1"
touch 2
git add 2
git commit -m "2"
touch 3
git add 3
git commit -m "3"
</code></pre>
<p>As a result after squashing we would have 1 commit with 3 files.</p>
<p>Any proposals?</p> | 21,306,306 | 6 | 2 | null | 2012-09-21 10:33:08.937 UTC | 19 | 2022-03-11 14:01:20.63 UTC | null | null | null | null | 251,311 | null | 1 | 53 | git|tortoisegit | 70,959 | <p>You can combine two adjacent commits using the GUI as follows. Remember not do combine commits already on the shared repository.
See:
<img src="https://i.stack.imgur.com/jhnqO.png" alt="Right click 2 commits"></p> |
12,538,510 | Getting 'DatabaseOperations' object has no attribute 'geo_db_type' error when doing a syncdb | <p>I'm attempting to run <code>heroku run python manage.py syncdb</code> on my GeoDjango app on Heroku, but I get the following error:</p>
<p><strong>AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'</strong></p>
<p><a href="http://djangosaur.tumblr.com/post/409277054/geodjango-database-engine-for-django-1-2">All</a> <a href="https://code.djangoproject.com/ticket/12727">of</a> <a href="http://develissimo.com/forum/topic/110229/?page=1#post-267473">my</a> <a href="http://opensourcegeospatial.blogspot.com/2011/06/geodjango-object-has-no-attribute.html">research</a> has yielded the same solution: make sure to use <code>django.contrib.gis.db.backends.postgis</code> as the database engine. Funny thing is that <em>I'm already doing this</em> (and I also have <code>django.contrib.gis</code> in <code>INSTALLED_APPS</code>):</p>
<pre><code>settings.py
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': '...',
'HOST': '...',
'PORT': ...,
'USER': '...',
'PASSWORD': '...'
}
}
INSTALLED_APPS = (
...,
'django.contrib.gis',
)
</code></pre>
<p>Is there something else I am missing? Any help is greatly appreciated, below is the full error trace for reference:</p>
<pre><code>Running `python manage.py syncdb` attached to terminal... up, run.1
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/app/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 91, in handle_noargs
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
File "/app/lib/python2.7/site-packages/django/db/backends/creation.py", line 44, in sql_create_model
col_type = f.db_type(connection=self.connection)
File "/app/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 200, in db_type
return connection.ops.geo_db_type(self)
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
</code></pre>
<p><strong>Update</strong>: I followed the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/">GeoDjango tutorial</a> and <a href="https://devcenter.heroku.com/articles/django">Heroku/Django tutorial</a>, and built a simple app that works on my dev machine. I pushed it to Heroku using a <a href="https://github.com/cirlabs/heroku-buildpack-geodjango">custom GeoDjango buildpack</a>, and tried syncdb, but get the same error. Is this an issue with Django/GeoDjango, Heroku, or the buildpack? My dev environment is using PostgreSQL 9.1 and PostGIS 2.0, but Heroku uses 9.0.9 and 1.5, could that be the issue?</p> | 12,643,826 | 10 | 0 | null | 2012-09-21 21:37:59.43 UTC | 9 | 2021-06-14 17:07:25.287 UTC | 2012-09-28 01:21:26.17 UTC | null | 221,458 | null | 221,458 | null | 1 | 77 | django|heroku|geodjango | 42,396 | <p>The buildpack was the primary culprit here. Instead of using the GeoDjango buildpack listed on <a href="https://devcenter.heroku.com/articles/third-party-buildpacks" rel="nofollow">Heroku's buildpack page</a>, I used <a href="https://github.com/guybowden/heroku-buildpack-geodjango" rel="nofollow">one of it's forks</a> that was updated more recently.</p>
<p>Also, when I do a <code>git push heroku master</code>, Heroku creates a dev database for the app, and when I do a syncdb, <strong>my <code>DATABASES</code> setting is ignored</strong> and Heroku tries to use the dev database
instead... obviously an issue, because dev databases don't/can't have PostGIS installed. So I destroyed the dev database after it was created with the <code>git push</code> (with the <a href="https://github.com/guybowden/heroku-buildpack-geodjango" rel="nofollow">correct buildpack</a>), then ran syncdb and it works.</p> |
12,547,706 | Could not change executable permissions on the application | <p>Just updated to iOS 6 sdk and latest Xcode and get this when trying to build to my 3gs.
I 've added armv6 under valid architectures?</p>
<p>"Could not change executable permissions on the application"</p> | 12,559,057 | 15 | 2 | null | 2012-09-22 21:07:01.54 UTC | 25 | 2015-05-13 21:41:05.927 UTC | null | null | null | null | 652,028 | null | 1 | 167 | xcode|ios6|xcode4.5 | 57,810 | <p>I could solve it erasing an application that I had previously uploaded using the same Bundle Identifier (xcode get's confused doing the chmod). Try checking the log from xCode Organizer (Your device's Name -> Console) you should get information from that log. Good luck!</p> |
3,483,125 | IntelliJ IDEA disable font increase/decrease on CMD+scroll | <p>I am using IntelliJ IDEA 9.0.2 on Mac OS X - with the Magic Mouse. Whenever I press the command button and move my finger a micrometer or two on the surface of the mouse, IDEA immediately increases or decreases my font size rapidly. How can I disable this feature?</p> | 3,485,348 | 3 | 0 | null | 2010-08-14 11:48:04.757 UTC | 7 | 2017-01-20 01:42:08.133 UTC | 2015-04-03 14:07:21.02 UTC | null | 3,885,376 | null | 299,711 | null | 1 | 58 | fonts|size|intellij-idea|command|scroll | 11,394 | <p><code>Settings</code> | <code>Editor</code> | <code>Enable Ctrl+MouseWheel changes font size</code></p>
<p>(On <strong>Mac</strong> it would be <code>Preferences</code> | <code>Editor</code> | <code>General</code> | <code>Enable CMD+MouseWheel changes font size</code>.)</p> |
3,848,375 | Looking for simple MVVM Light example | <p>I'm trying to learn MVVM Light and am looking for a good basic example that shows a model and how to load different views. </p>
<p>The template I see after downloading MVVM Light has no models and only one view. (http://www.galasoft.ch/mvvm/creating/)</p>
<p>Other things I've found are more complex and a bit confusing when all I want to see are the basics. </p>
<p>Thanks.</p> | 6,016,541 | 4 | 0 | null | 2010-10-03 02:59:23.837 UTC | 9 | 2017-01-18 17:13:22.71 UTC | null | null | null | null | 457,507 | null | 1 | 12 | wpf|mvvm|mvvm-light | 28,838 | <p>I have found this example helpful:</p>
<p><a href="http://apuntanotas.codeplex.com/" rel="noreferrer">http://apuntanotas.codeplex.com/</a></p> |
38,080,337 | SQL Performance Slow (Improve Insert Into Temp Table) | <p>I have been working on an old auditing stored procedure that is running slowly, I have had some success from applying indexing and making the query more sargable.</p>
<p>However the stored procedure is still taking over one minute to complete. I think the problem lays in the temp table insert. I did try to apply an index to the temp table but this will only reduce performance as: </p>
<blockquote>
<p>The number of indexes on a table is the most dominant factor for
insert performance. The more indexes a table has, the slower the
execution becomes. The insert statement is the only operation that
cannot directly benefit from indexing because it has no where clause.</p>
</blockquote>
<p><strong>SQL code</strong></p>
<p>I have posted below the snippet of code from the auditing procedure that is taking the longest time to process and included the execution plan. </p>
<pre><code>SELECT dbo.[Audit Result Entry Detail].PK_ID,
dbo.[Audit Result Entry Detail].......
45-50 other columns selected from Audit Result Entry Detail
(Note i need to select all these)
dbo.[Audit Register].Audit_Date,
dbo.[Audit Register].Audit_Type,
dbo.[Audit Register].ContextUser
INTO #temp5
FROM dbo.[Audit Result Entry Detail]
INNER
JOIN dbo.[Audit Register]
ON dbo.[Audit Result Entry Detail].FK_RegisterID = dbo.[Audit Register].PK_ID
INNER
JOIN (
SELECT MAX(Audit_Date) AS DATE,
FK_RegisterID
FROM dbo.[Audit Result Entry Detail]
INNER
JOIN dbo.[Audit Register]
ON dbo.[Audit Result Entry Detail].FK_RegisterID = dbo.[Audit Register].PK_ID
WHERE Audit_Date >= @StartDate AND Audit_Date < DATEADD(dd,1,@EndDate)
--WHERE ((SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, Audit_Date))) >= @StartDate
-- AND (SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, Audit_Date))) <= @EndDate)
AND part_number = @ParticipantNumber
GROUP
BY FK_RegisterID
) dt
ON dbo.[Audit Result Entry Detail].FK_RegisterID = dt.FK_RegisterID
AND dbo.[Audit Register].Audit_Date = dt.[date]
WHERE part_number = @ParticipantNumber
</code></pre>
<p><strong>Execution Plan:</strong>
<a href="https://i.stack.imgur.com/oxXKq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oxXKq.png" alt="Execution_Plan"></a></p>
<p>I believe the bottleneck is the #temp5 table, my question is there a way I can speed up the insert into the temp table or is there a better alternative to a temp table?</p> | 38,085,068 | 1 | 8 | null | 2016-06-28 15:26:20.76 UTC | 2 | 2019-11-21 22:44:46.93 UTC | 2019-11-21 22:44:46.93 UTC | null | 1,015,495 | null | 6,294,612 | null | 1 | 8 | sql|sql-server|performance|stored-procedures|temp-tables | 49,044 | <p>I guess there could be few different causes of the problem.
At least, the assumption is that because of the big number of fields in one record can cause Page overflow in Temp Heap table. Along with that there might be contention in tempdb or even it's slowness. So, the general suggestions might be:<BR/>
1. As already suggested, try to do not use temp table at all.<BR/>
2. If possible, try to limit record size to fit into one page. Or even better, if you can fit 2-3 records into one page.<BR/>
3. If it is possible, use "staging" table with clustered index on it, instead of temp table. Do not truncate that table, only do deletes.<BR/>
4. If using temp table: create table before the insert with clustered index on it.<BR/>
5. Fallow Paul Randal's suggestions about TempDB: <a href="http://www.sqlskills.com/blogs/paul/the-accidental-dba-day-27-of-30-troubleshooting-tempdb-contention/" rel="noreferrer">http://www.sqlskills.com/blogs/paul/the-accidental-dba-day-27-of-30-troubleshooting-tempdb-contention/</a></p>
<p>For deeper troubleshooting, I'd suggest, during the execution of that query, to capture waits, locks, I/O, memory and CPU activity.</p> |
22,646,463 | 'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays? | <p><strong>What explains the difference in behavior of boolean and bitwise operations on lists vs NumPy arrays?</strong> </p>
<p>I'm confused about the appropriate use of <code>&</code> vs <code>and</code> in Python, illustrated in the following examples.</p>
<pre><code>mylist1 = [True, True, True, False, True]
mylist2 = [False, True, False, True, False]
>>> len(mylist1) == len(mylist2)
True
# ---- Example 1 ----
>>> mylist1 and mylist2
[False, True, False, True, False]
# I would have expected [False, True, False, False, False]
# ---- Example 2 ----
>>> mylist1 & mylist2
TypeError: unsupported operand type(s) for &: 'list' and 'list'
# Why not just like example 1?
>>> import numpy as np
# ---- Example 3 ----
>>> np.array(mylist1) and np.array(mylist2)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
# Why not just like Example 4?
# ---- Example 4 ----
>>> np.array(mylist1) & np.array(mylist2)
array([False, True, False, False, False], dtype=bool)
# This is the output I was expecting!
</code></pre>
<p><a href="https://stackoverflow.com/a/6490106/2098573">This answer</a> and <a href="https://stackoverflow.com/a/10246441/2098573">this answer</a> helped me understand that <a href="http://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not" rel="noreferrer"><code>and</code></a> is a boolean operation but <a href="http://docs.python.org/3/reference/expressions.html#binary-bitwise-operations" rel="noreferrer"><code>&</code></a> is a bitwise operation. </p>
<p>I read about <a href="https://wiki.python.org/moin/BitwiseOperators" rel="noreferrer">bitwise operations</a> to better understand the concept, but I am struggling to use that information to make sense of my above 4 examples.</p>
<p>Example 4 led me to my desired output, so that is fine, but I am still confused about when/how/why I should use <code>and</code> vs <code>&</code>. Why do lists and NumPy arrays behave differently with these operators? </p>
<p><strong>Can anyone help me understand the difference between boolean and bitwise operations to explain why they handle lists and NumPy arrays differently?</strong> </p> | 22,647,006 | 8 | 4 | null | 2014-03-25 21:18:23.617 UTC | 88 | 2019-12-15 14:07:30.537 UTC | 2019-08-30 15:18:16.447 UTC | null | 4,518,341 | null | 2,098,573 | null | 1 | 174 | python|numpy|bit-manipulation|boolean-expression|ampersand | 118,427 | <p><code>and</code> tests whether both expressions are logically <code>True</code> while <code>&</code> (when used with <code>True</code>/<code>False</code> values) tests if both are <code>True</code>.</p>
<p>In Python, empty built-in objects are typically treated as logically <code>False</code> while non-empty built-ins are logically <code>True</code>. This facilitates the common use case where you want to do something if a list is empty and something else if the list is not. Note that this means that the list [False] is logically <code>True</code>:</p>
<pre><code>>>> if [False]:
... print 'True'
...
True
</code></pre>
<p>So in Example 1, the first list is non-empty and therefore logically <code>True</code>, so the truth value of the <code>and</code> is the same as that of the second list. (In our case, the second list is non-empty and therefore logically <code>True</code>, but identifying that would require an unnecessary step of calculation.)</p>
<p>For example 2, lists cannot meaningfully be combined in a bitwise fashion because they can contain arbitrary unlike elements. Things that can be combined bitwise include: Trues and Falses, integers.</p>
<p>NumPy objects, by contrast, support vectorized calculations. That is, they let you perform the same operations on multiple pieces of data.</p>
<p>Example 3 fails because NumPy arrays (of length > 1) have no truth value as this prevents vector-based logic confusion.</p>
<p>Example 4 is simply a vectorized bit <code>and</code> operation.</p>
<p><strong>Bottom Line</strong></p>
<ul>
<li><p>If you are not dealing with arrays and are not performing math manipulations of integers, you probably want <code>and</code>.</p></li>
<li><p>If you have vectors of truth values that you wish to combine, use <code>numpy</code> with <code>&</code>.</p></li>
</ul> |
8,752,837 | "Undefined reference to" template class constructor | <p>I have no idea why this is happenning, since I think I have everything properly declared and defined.</p>
<p>I have the following program, designed with templates. It's a simple implementation of a queue, with the member functions "add", "substract" and "print".</p>
<p>I have defined the node for the queue in the fine "nodo_colaypila.h":</p>
<pre><code>#ifndef NODO_COLAYPILA_H
#define NODO_COLAYPILA_H
#include <iostream>
template <class T> class cola;
template <class T> class nodo_colaypila
{
T elem;
nodo_colaypila<T>* sig;
friend class cola<T>;
public:
nodo_colaypila(T, nodo_colaypila<T>*);
};
</code></pre>
<p>Then the implementation in "nodo_colaypila.cpp"</p>
<pre><code>#include "nodo_colaypila.h"
#include <iostream>
template <class T> nodo_colaypila<T>::nodo_colaypila(T a, nodo_colaypila<T>* siguiente = NULL)
{
elem = a;
sig = siguiente;//ctor
}
</code></pre>
<p>Afterwards, the definition and declaration of the queue template class and its functions:</p>
<p>"cola.h":</p>
<pre><code>#ifndef COLA_H
#define COLA_H
#include "nodo_colaypila.h"
template <class T> class cola
{
nodo_colaypila<T>* ult, pri;
public:
cola<T>();
void anade(T&);
T saca();
void print() const;
virtual ~cola();
};
#endif // COLA_H
</code></pre>
<p>"cola.cpp":</p>
<pre><code>#include "cola.h"
#include "nodo_colaypila.h"
#include <iostream>
using namespace std;
template <class T> cola<T>::cola()
{
pri = NULL;
ult = NULL;//ctor
}
template <class T> void cola<T>::anade(T& valor)
{
nodo_colaypila <T> * nuevo;
if (ult)
{
nuevo = new nodo_colaypila<T> (valor);
ult->sig = nuevo;
ult = nuevo;
}
if (!pri)
{
pri = nuevo;
}
}
template <class T> T cola<T>::saca()
{
nodo_colaypila <T> * aux;
T valor;
aux = pri;
if (!aux)
{
return 0;
}
pri = aux->sig;
valor = aux->elem;
delete aux;
if(!pri)
{
ult = NULL;
}
return valor;
}
template <class T> cola<T>::~cola()
{
while(pri)
{
saca();
}//dtor
}
template <class T> void cola<T>::print() const
{
nodo_colaypila <T> * aux;
aux = pri;
while(aux)
{
cout << aux->elem << endl;
aux = aux->sig;
}
}
</code></pre>
<p>Then, I have a program to test these functions as follows:</p>
<p>"main.cpp"</p>
<pre><code>#include <iostream>
#include "cola.h"
#include "nodo_colaypila.h"
using namespace std;
int main()
{
float a, b, c;
string d, e, f;
cola<float> flo;
cola<string> str;
a = 3.14;
b = 2.71;
c = 6.02;
flo.anade(a);
flo.anade(b);
flo.anade(c);
flo.print();
cout << endl;
d = "John";
e = "Mark";
f = "Matthew";
str.anade(d);
str.anade(e);
str.anade(f);
cout << endl;
c = flo.saca();
cout << "First In First Out Float: " << c << endl;
cout << endl;
f = str.saca();
cout << "First In First Out String: " << f << endl;
cout << endl;
flo.print();
cout << endl;
str.print();
cout << "Hello world!" << endl;
return 0;
}
</code></pre>
<p>But when I build, the compiler throws errors in every instance of the template class:</p>
<p><strong>undefined reference to `cola(float)::cola()'...</strong> (it's actually cola'<'float'>'::cola(), but this doesn't let me use it like that.)</p>
<p>And so on. Altogether, 17 warnings, counting the ones for the member functions being called in the program.</p>
<p>Why is this? Those functions and constructors WERE defined. I thought that the compiler could replace the "T" in the template with "float", "string" or whatever; that was the advantage of using templates.</p>
<p>I read somewhere here that I should put the declaration of each function in the header file for some reason. Is that right? And if so, why?</p> | 8,752,879 | 3 | 6 | null | 2012-01-06 02:57:52.78 UTC | 146 | 2021-08-11 23:29:29.783 UTC | 2021-08-11 23:29:29.783 UTC | null | 12,299,000 | null | 1,125,383 | null | 1 | 194 | c++|templates|compiler-errors|codeblocks | 150,988 | <p>This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.</p>
<p>The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors <code>cola<float>::cola(...)</code> and <code>cola<string>::cola(...)</code> until it is forced to do so. And we must ensure that this compilation happens for the constructors <em>at least</em> once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of <code>cola<T></code> also.)</p>
<h3>Understanding the problem</h3>
<p>The problem is caused by the fact that <code>main.cpp</code> and <code>cola.cpp</code> will be compiled separately first. In <code>main.cpp</code>, the compiler will <em>implicitly</em> instantiate the template classes <code>cola<float></code> and <code>cola<string></code> because those particular instantiations are used in <code>main.cpp</code>. The bad news is that the implementations of those member functions are not in <code>main.cpp</code>, nor in any header file included in <code>main.cpp</code>, and therefore the compiler can't include complete versions of those functions in <code>main.o</code>. When compiling <code>cola.cpp</code>, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of <code>cola<float></code> or <code>cola<string></code>. Remember, when compiling <code>cola.cpp</code>, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for <em>every</em> type in order to ensure this problem never happens! (<code>cola<int></code>, <code>cola<char></code>, <code>cola<ostream></code>, <code>cola< cola<int> ></code> ... and so on ...)</p>
<p>The two answers are:</p>
<ul>
<li>Tell the compiler, at the end of <code>cola.cpp</code>, which particular template classes will be required, forcing it to compile <code>cola<float></code> and <code>cola<string></code>.</li>
<li>Put the implementation of the member functions in a header file that will be included <em>every</em> time any other 'translation unit' (such as <code>main.cpp</code>) uses the template class.</li>
</ul>
<h3>Answer 1: Explicitly instantiate the template, and its member definitions</h3>
<p>At the <em>end</em> of <code>cola.cpp</code>, you should add lines explicitly instantiating all the relevant templates, such as</p>
<pre><code>template class cola<float>;
template class cola<string>;
</code></pre>
<p>and you add the following two lines at the end of <code>nodo_colaypila.cpp</code>:</p>
<pre><code>template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;
</code></pre>
<p>This will ensure that, when the compiler is compiling <code>cola.cpp</code> that it will explicitly compile all the code for the <code>cola<float></code> and <code>cola<string></code> classes. Similarly, <code>nodo_colaypila.cpp</code> contains the implementations of the <code>nodo_colaypila<...></code> classes.</p>
<p>In this approach, you should ensure that all the of the implementation is placed into one <code>.cpp</code> file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).</p>
<h3>Answer 2: Copy the code into the relevant header file</h3>
<p>The common answer is to move all the code from the implementation files <code>cola.cpp</code> and <code>nodo_colaypila.cpp</code> into <code>cola.h</code> and <code>nodo_colaypila.h</code>. In the long run, this is more flexible as it means you can use extra instantiations (e.g. <code>cola<char></code>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.</p>
<h3>Summary</h3>
<p>The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for <code>cola<float></code> and <code>cola<string></code>, if you want to use something else, tell me first and will can verify it works before enabling it.").</p>
<p>Finally, there are three other minor typos in the code in your question:</p>
<ul>
<li>You are missing an <code>#endif</code> at the end of nodo_colaypila.h</li>
<li>in cola.h <code>nodo_colaypila<T>* ult, pri;</code> should be <code>nodo_colaypila<T> *ult, *pri;</code> - both are pointers.</li>
<li>nodo_colaypila.cpp: The default parameter should be in the header file <code>nodo_colaypila.h</code>, not in this implementation file.</li>
</ul> |
11,021,242 | Accessing Many to Many "through" relation fields in Formsets | <p>My Models:</p>
<pre><code>class End_User(models.Model):
location = models.ForeignKey(Location)
first_name = models.CharField(max_length=70, blank=True, null=True)
email_address = models.CharField(max_length=70, blank=True, null=True)
class Phone_Client(models.Model):
end_user = models.ManyToManyField(End_User)
...
extensions = models.CharField(max_length=20)
class Line(models.Model):
phone_client = models.ManyToManyField(Phone_Client, through='Phone_Line' )
....
voicemail = models.BooleanField(default=False)
class Phone_Line(models.Model):
phone_client = models.ForeignKey(Phone_Client)
line = models.ForeignKey(Line)
line_index = models.IntegerField()
</code></pre>
<p>So basically One end user can have many phones, a phone can have many Lines, related through Phone_line.</p>
<p>My page need to have all these objects editable and new instances created runtime for Phone_Clients and Line all in the same page. Currently I am creating a simple End_User model form and modelformset_factory objects for Phone_Client and Lines. Since a phone can have many lines, each phone form in the phone_formset can have a line formset object. I am currently doing something like this </p>
<pre><code>end_user = End_User.objects.get(pk=user_id)
user_form = End_UserForm(instance=end_user)
Phone_ClientFormSet = modelformset_factory(Phone_Client,form=PartialPhone_ClientForm, extra=0, can_delete=True)
phone_clients_formset = Phone_ClientFormSet(queryset=end_user.phone_client_set.all(), prefix='phone_client')
all_lines = modelformset_factory(Line, form=PartialLineForm, extra=0, can_delete=True)
phone_clients = end_user.phone_client_set.all()
client_lines_formsets = {}
for phone in phone_clients:
client_lines_formsets[phone.id] = all_lines(queryset=phone.line_set.all(), prefix='phone_client_'+str(phone.id))
</code></pre>
<p>I am using this list to display lines belonging to a phone_client in the template using formsets.</p>
<p>I have the following question, on the models</p>
<ol>
<li><p>Can I use inline_formset factory to handle many to many relation containing a through class? if so how do I do that for the Phone_Client, Line and Phone_Line through relation?</p></li>
<li><p>I need to display the line_index for a given phone, line combination, how do I do that in template? I have looked at<br>
<a href="https://stackoverflow.com/questions/3368442/how-do-i-access-the-properties-of-a-many-to-many-through-table-from-a-django-t">How do I access the properties of a many-to-many "through" table from a django template?</a>
I do not want to only display, but bind the value to the phone, line combination if possible in the line or phone formset, such that if user changes the index, I can save that in the data base while posting the formset data.</p></li>
</ol>
<p>I am new to django so any help is really appreciated.
Thanks!!</p> | 11,022,587 | 1 | 0 | null | 2012-06-13 18:38:07.46 UTC | 10 | 2012-06-13 20:11:26.033 UTC | 2017-05-23 12:22:56.59 UTC | null | -1 | null | 808,734 | null | 1 | 11 | django|django-forms|django-templates|django-orm | 5,622 | <p>As you're probably aware, you can't edit many-to-many relationships with inline formsets. You can, however, edit the through model. So for your inline formset, you just need to set the model to the through model, e.g.:</p>
<pre><code>inlineformset_factory(Phone_Client, Line.phone_client.through)
</code></pre>
<p><code>line_index</code> will actually be a visible field on the inline form, so you really don't have to do anything. If someone changes the index, it'll be saved when the inline forms are saved, just like the rest of the fields.</p> |
11,418,183 | eclipse for chrome? | <p>I use eclipse IDE for developing my GWT and android apps. I would like to transition to a chromebook for my main development computer, but I can't figure out how I would get eclipse "installed". There is no chrome app version of eclipse, at least not that I can find. I do see that there are other IDEs in the chrome store, but I don't think they would have all the nifty helper plugins that eclipse has for google developers. Anybody know if a chrome version of eclipse is coming? Do others share my desire to develop on a chrome book?</p> | 11,418,500 | 6 | 1 | null | 2012-07-10 16:55:56.96 UTC | 1 | 2017-03-08 00:21:22.467 UTC | null | null | null | null | 1,305,454 | null | 1 | 14 | eclipse|google-chrome|ide|developer-tools|chromebook | 56,353 | <p>Eclipse is not coming for Chrome OS. You need a JVM to run it and one of the compatible desktops for the UI widgets. So you would have to escape from Chrome OS desktop into base Linux and somehow launch a regular Linux desktop (like GTK) to have any hope of running Eclipse. Also, a typical chromebook is far too underpowered to run a full IDE. </p>
<p>Here are some options to consider:</p>
<ol>
<li><a href="http://www.eclipse.org/orion/" rel="nofollow noreferrer">Project Orion</a> - A web based IDE from many of the same people who develop Eclipse. One of the goals is to enable Eclipse-like capabilities for platforms like iOS, Android, Chrome OS, etc. It has quite a few base IDE capabilities already, but not a lot of plugins just yet. Probably not going to see something as sophisticated as ADT for a while if ever. Google would have to implement Android emulators in JavaScript. Not an easy task.</li>
<li>Run Eclipse on another machine and use a remote desktop from your chromebook.</li>
<li>Run Eclipse Che on another machine or cloud server and use Chrome </li>
</ol> |
10,964,910 | Getting WPF ListView.SelectedItems in ViewModel | <p>There are some posts discussing adding data-binding ability for <code>ListView.SelectedItems</code> with non-trivial amount of code. In my scenario I don't need to set it from the <code>ViewModel</code>, just getting selected items in order to perform action on them and it is triggered by command so push update is also not necessary. </p>
<p>Is there a simple solution (in terms of lines of code), maybe in code-behind? I am fine with code-behind as long as <code>View</code> and <code>ViewModel</code> don't need to reference each other. I think this is a more generic question: "<em>best practice for VM to get data from the View on-demand</em>", but I can't seem to find anything...</p> | 11,006,325 | 5 | 0 | null | 2012-06-09 22:02:21.77 UTC | 11 | 2016-04-06 09:24:31.897 UTC | 2012-07-13 13:24:05.9 UTC | null | 45,382 | null | 986,080 | null | 1 | 15 | .net|wpf|listview|data-binding|mvvm | 30,253 | <p>To get the <code>SelectedItems</code> only when a command is executed then use <code>CommandParameter</code> and pass in the <code>ListView.SelectedItems</code>.</p>
<pre><code><ListBox x:Name="listbox" ItemsSource="{Binding StringList}" SelectionMode="Multiple"/>
<Button Command="{Binding GetListItemsCommand}" CommandParameter="{Binding SelectedItems, ElementName=listbox}" Content="GetSelectedListBoxItems"/>
</code></pre> |
11,093,744 | Fastest way to insert in parallel to a single table | <p>My company is cursed by a symbiotic partnership turned parasitic. To get our data from the parasite, we have to use a painfully slow odbc connection. I did notice recently though that I can get more throughput by running queries in parallel (even on the same table).</p>
<p>There is a particularly large table that I want to extract data from and move it into our local table. Running queries in parallel I can get data faster, but I also imagine that this could cause issues with trying to write data from multiple queries into the same table at once.</p>
<p>What advice can you give me on how to best handle this situation so that I can take advantage of the increased speed of using queries in parallel?</p>
<p>EDIT: I've gotten some great feedback here, but I think I wasn't completely clear on the fact that I'm pulling data via a linked server (which uses the odbc drivers). In other words that means I can run normal INSERT statements and I believe that would provide better performance than either SqlBulkCopy or BULK INSERT (actually, I don't believe BULK INSERT would even be an option).</p> | 11,095,230 | 3 | 5 | null | 2012-06-19 02:46:17.39 UTC | 9 | 2019-02-17 17:21:43.46 UTC | 2012-06-22 15:14:37.26 UTC | null | 1,019,215 | null | 1,019,215 | null | 1 | 19 | sql|sql-server|parallel-processing|blocking | 33,856 | <p>Have you read <a href="https://techcommunity.microsoft.com/t5/DataCAT/Load-1TB-in-less-than-1-hour/ba-p/304940" rel="nofollow noreferrer">Load 1TB in less than 1 hour</a>?</p>
<blockquote>
<ol>
<li>Run as many load processes as you have available CPUs. If you have
32 CPUs, run 32 parallel loads. If you have 8 CPUs, run 8 parallel
loads.</li>
<li>If you have control over the creation of your input files, make them
of a size that is evenly divisible by the number of load threads you
want to run in parallel. Also make sure all records belong to one
partition if you want to use the switch partition strategy.</li>
<li>Use BULK insert instead of BCP if you are running the process on the
SQL Server machine.</li>
<li>Use table partitioning to gain another 8-10%, but only if your input
files are GUARANTEED to match your partitioning function, meaning
that all records in one file must be in the same partition.</li>
<li>Use TABLOCK to avoid row at a time locking.</li>
<li>Use ROWS PER BATCH = 2500, or something near this if you are
importing multiple streams into one table.</li>
</ol>
</blockquote>
<p>For SQL Server 2008, there are certain circumstances where you can utilize <a href="http://www.sqlmag.com/content1/topic/minimally-logged-inserts/catpath/tsql3" rel="nofollow noreferrer">minimal logging for a standard INSERT SELECT</a>: </p>
<blockquote>
<p>SQL Server 2008 enhances the methods that it can handle with minimal
logging. It supports minimally logged regular INSERT SELECT
statements. In addition, turning on trace flag 610 lets SQL Server
2008 support minimal logging against a nonempty B-tree for new key
ranges that cause allocations of new pages.</p>
</blockquote> |
11,171,685 | Converting a text input to a select element with JavaScript | <p>I'm doing some front end development on a hosted e-commerce platform. The system sends a text input for the customer to choose the quantity of items they want to add to their cart, but I would prefer a select. I don't have access to the markup the system spits out in this regard, so I'd like to use JavaScript to change the text <em>input</em> to a <em>select</em> element.</p>
<p>I used jQuery to remove the select and duplicate the input element with a select with the right choices, but when I try to add something to my cart, only one item is added, regardless of the choice in the select.</p>
<p>Here's the native markup:</p>
<pre><code><div id="buy-buttons">
<label>Quantity:</label>
<input name="txtQuantity" type="text" value="1" id="txtQuantity" class="ProductDetailsQuantityTextBox">
<input type="submit" name="btnAddToCart" value="Add To Cart" id="btnAddToCart" class="ProductDetailsAddToCartButton ThemeButton AddToCartThemeButton ProductDetailsAddToCartThemeButton">
</div>
</code></pre>
<p>Here's the jQuery I'm running to update my markup. </p>
<pre><code> $("#txtQuantity").remove();
$("#buy-buttons").append('<select id="txtQuantity" type="text" value="1" class="ProductDetailsQuantityTextBox"></select>');
$("#txtQuantity").append('<option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option>');
</code></pre>
<p>Does anyone know why this isn't working? Shouldn't the select be submitting the information to through the form in the same way as the text input?</p>
<p>Thanks!</p> | 11,171,702 | 4 | 0 | null | 2012-06-23 17:48:33.767 UTC | 1 | 2021-01-30 12:22:34.003 UTC | 2018-01-16 19:00:51.333 UTC | null | 814,702 | null | 336,781 | null | 1 | 19 | javascript|jquery|forms | 46,485 | <p>You haven't set the field name. Add <code>name='txtQuantity'</code> to the select. Without a name attribute the value of the field will not get posted back to the server.</p>
<p>Also rather than setting <code>value='1'</code> on the select (which isn't doing anything), add <code>selected='selected'</code> to the first option. The result is the same as by default the first option is selected.</p>
<p>You are presumably ending up with the select after the submit button with the above code. However that has been covered in another answer.</p> |
10,903,568 | iOS Run Code Once a Day | <p>The idea behind this app is very simple: download a file. However this app will be for people who are not always within internet access range, so I need it to know that at, say 9:00 AM, to download a file to the hard drive. There will be a button within the app to do it manually as well, but I've already got that working.</p>
<p>As I understand it, this will be difficult if it is even possible. I know that iOS doesn't like multitasking, but I am also aware that it does allow for background timer functions. I am open to any sort of suggestions anyone might have to accomplish this, even if it means writing a separate app. Thanks.</p>
<p>Edit: I see there is the possibility of working with Notifications, or even maybe the Calendar. Ideas in that category as also welcomed.</p>
<p>Edit 2: I also read something about an external server initiating an app, but it gave no description.</p> | 10,904,172 | 5 | 0 | null | 2012-06-05 19:22:41.287 UTC | 19 | 2016-03-06 17:28:34 UTC | 2012-06-05 19:40:02.427 UTC | null | 1,393,620 | null | 1,393,620 | null | 1 | 26 | ios|timer|background | 20,274 | <p>Here's the situation regarding background execution and notifications and timers etc. in relation to an app scheduling some activity to happen periodically.</p>
<ol>
<li><p>An app cannot execute in the background unless:</p>
<ol>
<li><p>It requests extra time from the OS to do so. This is done using <code>beginBackgroundTaskWithExpirationHandler</code>. It is not specified (intentionally) by Apple how long this extra time is, however in practice it is around 10 minutes.</p></li>
<li><p>An app has a background mode, the modes are: voip, audio, location, newstand. Even if it has one of these types an app cannot execute without some restrictions. The rest of this discussion assumes the app does not have a background mode.</p></li>
</ol></li>
<li><p>When an app is suspended it cannot do ANYTHING to rouse itself directly. It cannot previously have scheduled an NSTimer, it cannot make use of something like performSelector:afterDelay. etc. </p>
<p>The ONLY way the app can become active again is if the USER does something to make it active. The user can do this from via of the following:</p>
<ol>
<li><p>Launch the app directly from its icon</p></li>
<li><p>Launch the app in response to a local notification that was previously scheduled by the app while it was active.</p></li>
<li><p>Launch the app in response to a remote notification sent by a server.</p></li>
<li><p>A few others: such as URL launching if the app is registered to deal with launching via a url; or if its registered to be capable of dealing with a certain type of content.</p></li>
</ol></li>
</ol>
<p>If an app is in the foreground when a local/remote notification fires then the app receives it directly. </p>
<p>If the app is not currently in the foreground when a local/remote notification fires then the app DOES NOT receive it. There is no code that is executed when the notification fires!</p>
<p>Only IF the user selects the notification will the app become active and it can execute.</p>
<p>Note that the user can disable notifications, either for the entire device, or just for a specific application, in which case the user will never see them. If the device is turned off when a notification is due to fire then it is lost.</p> |
11,214,167 | How to run Snap haskell webapp in production? | <p>I've installed Snap/Haskell on my production Ubuntu server (on EC2), and checked-out my project - but how do I run it?</p>
<p>I mean, locally, I run it from command line:</p>
<pre><code>project-name -p 8000
</code></pre>
<p>Does snap come with it's own web-server (<a href="http://hackage.haskell.org/package/snap-server-0.7.0.1" rel="nofollow noreferrer">it looks like it</a>), and if so how do I go about configuring it to run as a daemon of some sort?</p>
<p>Any tips?</p>
<p><em>Edit 2:</em></p>
<p>On the <a href="http://snapframework.com/docs/tutorials/snap-api" rel="nofollow noreferrer">wiki</a> they say:</p>
<blockquote>
<p>snap-server is an HTTP server library that supports the interface
defined in snap-core.</p>
</blockquote>
<p>While here, the haskell wiki about "Deployment/Backend options for your haskell web code" says that Snap:</p>
<blockquote>
<p>includes its own server. <a href="http://www.haskell.org/haskellwiki/Web/Frameworks" rel="nofollow noreferrer">see Web/Frameworks</a></p>
</blockquote>
<p>But <strong>HOW</strong>? How would I run it's own server? Why must I know about deployment of the damn thing if I am just interested in programming...</p>
<p><em>Edit:</em> related question: <a href="https://stackoverflow.com/questions/7539450/deploy-haskell-code-that-uses-the-snap-framework">Deploy Haskell code that uses the Snap Framework</a></p> | 11,304,866 | 3 | 4 | null | 2012-06-26 18:56:47.35 UTC | 16 | 2015-05-07 09:13:47.18 UTC | 2017-05-23 12:09:20.03 UTC | null | -1 | null | 74,865 | null | 1 | 29 | haskell|haskell-snap-framework | 3,952 | <p>Ok, so after some <a href="https://stackoverflow.com/a/7544384/74865">digging</a> and <a href="https://serverfault.com/questions/404251/how-to-properly-configure-a-web-service-ubuntu-12-04">asking</a>, here is what I came up with.</p>
<h2>Big idea</h2>
<p>Compile your Snap application into a binary and then run it as a service with the help of <a href="http://upstart.ubuntu.com/cookbook/" rel="nofollow noreferrer">upstart</a>.</p>
<h2>Step by Step</h2>
<ol>
<li><p>Compile your webapp. For the sake of this example, we'll assume the webapp is at <code>/home/john/webapps/mysite</code>:</p>
<pre><code>$ cd /home/john/webapps/mysite
$ cabal install
...
Preprocessing executable 'mysite` for 'mysite-0.1'...
Installing executable(s) in /home/john/.cabal/bin
</code></pre>
<p>As we can see the, the binary is placed in <code>/home/john/.cabal/bin</code>. You may move it to any place you like, but we'll leave it there.</p></li>
<li><p>Create a log in your application folder, otherwise snap will complain:</p>
<pre><code>$ mkdir /home/john/webapps/mysite/log
</code></pre></li>
<li><p>Now we will create a service that will run our webapp. To do so we will use Ubuntu's service facility called <a href="http://upstart.ubuntu.com/cookbook/" rel="nofollow noreferrer">upstart</a>. </p>
<p>a) We name our service simply by creating a conf file with the desired name in the <code>/etc/init/</code> directory. Let's call it <code>mysite</code>:</p>
<pre><code>$ sudo vi /etc/init/mysite.conf
</code></pre>
<p>b) Now let's add the description of what our service is:</p>
<pre><code>start on startup
chdir /home/john/webapps/mysite
exec /home/john/.cabal/bin/mysite -p 80
</code></pre>
<p>First, we say that the service should run on startup (or on bootup) of the system. </p>
<p>Second, since snap needs it's <code>snaplets</code> and other static resources (like the log directory we created earlier) - we tell the service to run inside our project's directory. </p>
<p>Lastly, we specify the binary that actually will run as a service: <code>/home/john/.cabal/bin/mysite</code>. We pass the <code>-p 80</code> parameter to the snap webserver to make it run on port 80. (Note: you have to disable all apache and nginx servers, so that they don't take up that port any more)</p></li>
<li><p>Done. You can check if it is running and start it manually if you need to:</p>
<pre><code>initctl list | grep mysite
initctl start mysite
</code></pre></li>
</ol> |
11,024,080 | How to use not contains() in XPath? | <p>I have some XML that is structured like this:</p>
<pre><code><whatson>
<productions>
<production>
<category>Film</category>
</production>
<production>
<category>Business</category>
</production>
<production>
<category>Business training</category>
</production>
</productions>
</whatson>
</code></pre>
<p>And I need to select every production with a category that doesn't contain "Business" (so just the first production in this example).</p>
<p>Is this possible with XPath? I tried working along these lines but got nowhere:</p>
<pre><code>//production[not(contains(category,'business'))]
</code></pre> | 11,024,134 | 4 | 0 | null | 2012-06-13 22:12:14.893 UTC | 16 | 2022-05-09 06:35:11.607 UTC | 2021-04-01 19:44:14.947 UTC | null | 9,193,372 | null | 566,808 | null | 1 | 92 | xpath|contains | 230,817 | <p>XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"</p>
<pre><code>//production[not(contains(category,'Business'))]
</code></pre>
<p>I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.</p> |
13,039,392 | CSV - list index out of range | <p>I get this error reading CSV file (no headers, 3 columns, 2nd and 3rd strings):</p>
<pre><code>Traceback (most recent call last):
File "C:\Python32\fantasy.py", line 72, in module>
some=row[1]
IndexError: list index out of range*
</code></pre>
<p>Here is part of the code below. It's stupidly simple stuff to be stuck on, but I'm just blank about how it isn't working. I'm new to coding, but have dealt with csv module before and never had problems with this part, and just made some test csv file in notepad to see if it will be read from the same code, and it does. I don't know. </p>
<pre><code>import csv
##############some other code, working good and I believe not relevant to this problem
file=open(r"C:\Users\me\Desktop\file-2.csv","r")
reader=csv.reader(file, delimiter=',', quotechar='"')
for row in reader:
some=row[1]
</code></pre> | 13,046,897 | 4 | 8 | null | 2012-10-23 21:17:28.607 UTC | 2 | 2021-10-28 09:55:38.093 UTC | 2021-10-28 09:55:38.093 UTC | null | 355,230 | null | 1,769,468 | null | 1 | 8 | python|csv|python-3.x | 45,130 | <p>Try checking for blank lines. Also, avoid using <code>file</code> as a variable name. <code>"r"</code> is the default mode with open.</p>
<pre><code>import csv
with open(r"C:\Users\me\Desktop\file-2.csv") as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
for row in reader:
if row:
some=row[1]
</code></pre> |
12,984,948 | Why is strdup considered to be evil | <p>I've seen some posters stating that <code>strdup</code> is evil. Is there a consensus on this? I've used it without any guilty feelings and can see no reason why it is worse than using <code>malloc</code>/<code>memcpy</code>. </p>
<p>The only thing I can think might earn <code>strdup</code> a reputation is that callers might misuse it (eg. not realise they have to free the memory returned; try to strcat to the end of a strdup'ed string). But then malloc'ed strings are not free from the possibility of misuse either.</p>
<hr>
<p>Thanks for the replies and apologies to those who consider the question unhelpful (votes to close). In summary of the replies, it seems that there is no general feeling that <code>strdup</code> is evil per se, but a general consensus that it can, like many other parts of C, be used improperly or unsafely. </p>
<p>There is no 'correct' answer really, but for the sake of accepting one, I accepted @nneoneo's answer - it could equally have been @R..'s answer.</p> | 12,984,973 | 6 | 3 | null | 2012-10-20 03:18:58.913 UTC | 5 | 2016-05-30 03:55:28.877 UTC | 2012-10-20 15:45:37.86 UTC | null | 1,163,625 | null | 1,163,625 | null | 1 | 31 | c|c-strings | 31,370 | <p>Two reasons I can think of:</p>
<ol>
<li>It's not strictly ANSI C, but rather POSIX. Consequently, some compilers (e.g. MSVC) discourage use (MSVC prefers <code>_strdup</code>), and <em>technically</em> the C standard could define its own <code>strdup</code> with different semantics since <code>str</code> is a reserved prefix. So, there are some potential portability concerns with its use.</li>
<li>It hides its memory allocation. Most other <code>str</code> functions don't allocate memory, so users might be misled (as you say) into believing the returned string doesn't need to be freed.</li>
</ol>
<p>But, aside from these points, I think that careful use of <code>strdup</code> is justified, as it can reduce code duplication and provides a nice implementation for common idioms (such as <code>strdup("constant string")</code> to get a mutable, returnable copy of a literal string).</p> |
13,104,681 | Hyperlinks in d3.js objects | <p>I am a complete novice at d3.js or java in general. I am using the indented tree example from <a href="http://bl.ocks.org/1093025" rel="noreferrer">http://bl.ocks.org/1093025</a>. It took me two hours to get this to work on my local computer, so that should give you an idea of my skill level.</p>
<p>I opened the flare.json file and started messing with it and was able to manipulate it successfully. It looks like this</p>
<pre><code>{
"name": "Test D3",
"children": [
{
"name": "News",
"children": [
{
"name": "CNN",
"size": 1000
},
{
"name": "BBC",
"size": 3812
}
]
},
{
"name": "Blogs",
"children": [
{
"name": "Engaget",
"size": 3938
}
]
},
{
"name": "Search",
"children": [
{
"name": "Google",
"size": 3938
},
{
"name": "Bing",
"size": 3938
}
]
}
]
}
</code></pre>
<p>What I want to do now, is to try to add hyperlinks. For example, I want to be able to click on "CNN" and go to CNN.com. Is there a modification I can make to flare.json that will do that?</p> | 13,109,162 | 1 | 0 | null | 2012-10-27 22:20:59.657 UTC | 18 | 2022-02-23 15:50:40.08 UTC | 2012-10-27 22:30:54.35 UTC | null | 1,006,780 | null | 1,780,030 | null | 1 | 37 | d3.js | 34,688 | <p>It is quite easy, just add some more "key" : "value" pairs. Example:</p>
<pre><code> "children": [
{
"name": "Google",
"size": 3938,
"url": "https://www.google.com"
},
{
"name": "Bing",
"size": 3938,
"url": "http://www.bing.com"
}
]
</code></pre>
<p>Of course, in your d3 code you then need to <code>append</code> <code><svg:a></code> tags and set their <code>xlink:href</code> attribute.</p>
<p>Here is some html and d3-code that might be of help to you. First you need to import the xlink namespace in your html file:</p>
<pre><code><html xmlns:xlink="http://www.w3.org/1999/xlink">
...
</html>
</code></pre>
<p>Then in the d3 drawing code where you append nodes for each data element you wrap the element you want to be clickable links with an <code>svg:a</code> tag:</p>
<pre><code>nodeEnter.append("svg:a")
.attr("xlink:href", function(d){return d.url;}) // <-- reading the new "url" property
.append("svg:rect")
.attr("y", -barHeight / 2)
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click); // <- remove this if you like
</code></pre>
<p>You might want to remove the click handler (which is present in the original example) by deleting the .on("click", click) as it might interfere with the default behavior of SVG links.</p>
<p>Clicking on your <code>rect</code>s should now lead you to the appropriate <code>url</code>.
SVG links might not be fully implemented in all browsers.</p>
<p>Alternatively you could modify the <code>click</code> handler to read the URL from <code>d.url</code> and use that one to manually redirect the browser to that URL via JavaScript: <code>window.location = d.url;</code>. Then you do not need the <code>svg:a</code> tag and the <code>xlink</code> code. Though adding a real link (not a scripted one) has the benefit that the user/browser can decide what to do (e.g., open in new tab/page). It also helps if some of your users have JavaScript disabled.</p> |
12,659,778 | Is it possible to run JavaScript files from the command line? | <p>I have several JS files so instead of copy and paste every one in the console window (Firefox and Chromium), I would want to call them from the shell if it is possible.</p>
<p>Every JS file has test functions that show if they are correct using console.log.</p> | 12,659,987 | 6 | 5 | null | 2012-09-30 08:18:09.147 UTC | 11 | 2019-04-05 16:53:08.26 UTC | 2016-02-28 23:42:32.353 UTC | user1243746 | 101,290 | user1243746 | null | null | 1 | 57 | javascript|shell|console | 101,979 | <p>If your tests need access to a DOM there is always <a href="http://phantomjs.org/" rel="noreferrer">PhantomJS</a> - a headless (Webkit) browser.</p> |
12,712,017 | Can't install xdebug on Mac with Homebrew | <p>I'm kind of new to using Homebrew, but I love it. It's so easy. I'm trying install Xdebug. Some of the posts on the web say to do this:</p>
<pre><code>brew install xdebug
</code></pre>
<p>But it doesn't work. I get: <code>Error, no available formula.</code> </p>
<p>I did <code>brew search xdebug</code> and it returned:</p>
<pre><code>josegonzalez/php/php53-xdebug josegonzalez/php/php54-xdebug
</code></pre>
<p>I tried several different iterations of <code>brew install</code> with this including <code>brew install php53-xdebug</code>, but still no luck. Can someone help me? I can't find anything on Xdebug's site about using Homebrew, but yet posts on the web seem to indicate it's possible.</p> | 17,179,697 | 14 | 1 | null | 2012-10-03 15:42:29.1 UTC | 15 | 2022-06-28 13:37:07.883 UTC | null | null | null | null | 537,082 | null | 1 | 60 | xdebug|homebrew | 62,536 | <p>Add this repository: <a href="https://github.com/josegonzalez/homebrew-php#readme" rel="noreferrer">https://github.com/josegonzalez/homebrew-php#readme</a></p>
<p>Then use <code>brew install php54-xdebug</code> for PHP 5.4</p>
<p>Or <code>brew install php53-xdebug</code> for PHP 5.3</p>
<p>Or <code>brew install php55-xdebug</code> for PHP 5.5</p> |
13,194,322 | PHP Regex to check date is in YYYY-MM-DD format | <p>I'm trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I have setup.</p>
<p>So I'm assuming I have made a mess of the regex, detailed below.</p>
<pre><code>$date="2012-09-12";
if (preg_match("^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$",$date))
{
return true;
}else{
return false;
}
</code></pre>
<p>Any thoughts?</p> | 13,194,429 | 25 | 4 | null | 2012-11-02 11:27:47.67 UTC | 49 | 2021-09-30 11:05:22.017 UTC | 2012-11-02 11:46:02.63 UTC | null | 584,490 | null | 1,271,796 | null | 1 | 125 | php|regex|date-format | 285,497 | <p>Try this.</p>
<pre><code>$date="2012-09-12";
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
return true;
} else {
return false;
}
</code></pre> |
11,375,949 | cout is not a member of std | <p>I'm practicing using mulitple files and header files etc. So I have this project which takes two numbers and then adds them. Pretty simple.</p>
<p>Here are my files:</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include "add.h"
int main()
{
int x = readNumber();
int y = readNumber();
writeAnswer(x + y);
return(0);
}
</code></pre>
<p><strong>io.cpp</strong></p>
<pre><code>int readNumber()
{
int x;
std::cout << "Number: ";
std::cin >> x;
return x;
}
void writeAnswer(int x)
{
std::cout << "Answer: ";
std::cout << x;
}
</code></pre>
<p><strong>add.h</strong></p>
<pre><code>#ifndef ADD_H_INCLUDED
#define ADD_H_INCLUDED
int readNumber();
void writeAnswer(int x);
#endif // #ifndef ADD_H_INCLUDED
</code></pre>
<p>The error is showing up in io.cpp. The exact errors are:</p>
<p><a href="https://i.stack.imgur.com/fRKEB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fRKEB.png" alt="enter image description here"></a></p>
<p>Does anyone have any idea why this may be happening? Thanks.</p>
<p><strong>EDIT: I made a small project yesterday with the same amount of files (2 .cpp and 1.h) and I didn't include the iostream header in the other .cpp and it still compiled and ran fine.</strong></p> | 11,375,960 | 3 | 3 | null | 2012-07-07 14:43:46.347 UTC | 22 | 2022-08-13 11:55:50.047 UTC | 2018-03-28 07:18:08.66 UTC | null | 2,111,085 | null | 1,508,848 | null | 1 | 243 | c++|io|std|member|cout | 375,865 | <p>add <code>#include <iostream></code> to the start of <code>io.cpp</code> too.</p> |
16,872,898 | What's the best way to exit a Haskell program? | <p>I've got a program which uses several threads. As I understand it, when thread 0 exits, the entire program exits, regardless of any other threads which might still be running.</p>
<p>The thing is, these other threads may have files open. Naturally, this is wrapped in exception-handling code which cleanly closes the files in case of a problem. That also means that if I use <code>killThread</code> (which is implemented via <code>throwTo</code>), the file should <em>also</em> be closed before the thread exits.</p>
<p>My question is, if I just let thread 0 exit, without attempting to stop the other threads, will all the various file handles be closed nicely? Does any buffered output get flushed?</p>
<p>In short, can I just exit, or do I need to manually kill threads first?</p> | 17,124,274 | 2 | 4 | null | 2013-06-01 12:50:48.877 UTC | 7 | 2013-06-15 13:41:19.063 UTC | null | null | null | null | 1,006,010 | null | 1 | 33 | multithreading|haskell | 3,543 | <p>From my testing, I have discovered a few things:</p>
<ol>
<li><p><code>exitFailure</code> and friends only work in thread 0. (The documentation actually says so, if you go to the trouble of reading it. These functions just throw exceptions, which are silently ignored in other threads.)</p></li>
<li><p>If an exception kills your thread, or your whole program, any open handles are <em>not</em> flushed. This is excruciatingly annoying when you're desperately trying to figure out exactly where your program crashed!</p></li>
</ol>
<p>So it appears it if you want your stuff flushed before the program exits, then <em>you</em> have to implement this. Just letting thread 0 die doesn't flush stuff, doesn't throw any exception, just silently terminates all threads without running exception handlers.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.