instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Is there a way to identify at run-time of an executable is being run from within valgrind? I have a set of C++ unit tests, and one of them expects <code>std::vector::reserve</code> to throw <code>std::bad_alloc</code>. When I run this under valgrind, it bails out completely, preventing me from testing for both memory leaks (using valgrind) and behavior (expecting the exception to be thrown).</p>
<p>Here's a minimal example that reproduces it:</p>
<pre><code>#include <vector>
int main()
{
size_t uint_max = static_cast<size_t>(-1);
std::vector<char> v;
v.reserve(uint_max);
}
</code></pre>
<p>Running valgrind, I get this output:</p>
<pre><code>Warning: silly arg (-1) to __builtin_new()
new/new[] failed and should throw an exception, but Valgrind
cannot throw exceptions and so is aborting instead. Sorry.
at 0x40192BC: VALGRIND_PRINTF_BACKTRACE (valgrind.h:319)
by 0x401C823: operator new(unsigned) (vg_replace_malloc.c:164)
by 0x80487BF: std::vector<char, std::allocator<char> >::reserve(unsigned) new_allocator.h:92)
by 0x804874D: main (vg.cxx:6)
</code></pre>
<p>I'd like to modify my unit test to simply skip the offending code when it's being run from within valgrind. Is this possible?</p>
|
<p>You should look at <a href="http://valgrind.org/docs/manual/manual-core-adv.html#manual-core-adv.clientreq" rel="noreferrer">this page</a> from the Valgrind manual, it contains a <code>RUNNING_ON_VALGRIND</code> macro (included from valgrind.h) which does what you want.</p>
|
<p>I looked at the valgrind doucmentation and didn't find an easy answer. But here are a couple of things you can try:</p>
<ul>
<li><p>Write your own wrapper around the offending new operation and raise the exception before valgrind gets its private new function going.</p></li>
<li><p>Try as poster above suggested except that instead of a command-line option (which requires plumbing) use an environment variable: </p>
<pre><code>MYAPP_UNIT_TESTS_DISABLED="NEW_MINUS_ONE,FLY_TO_MOON,DEREF_NULL" valgrind myapp
</code></pre></li>
</ul>
<p>Then you can easily write a function</p>
<pre><code>bool unit_test_enabled(const char *testname);
</code></pre>
<p>to protect your unit test based on the value returned by getenv(3).</p>
| 47,713
|
<p>I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create a second stored procedure that only returns the second result set of the first?</p>
|
<p>No need for anything fancy. Just use the <a href="https://github.com/mkleehammer/pyodbc/wiki/Cursor#nextset" rel="nofollow noreferrer">cursor's <code>nextset()</code> method</a>:</p>
<pre><code>
import pyodbc
db = pyodbc.connect ("")
q = db.cursor ()
q.execute ("""
SELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES
SELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS
""")
tables = q.fetchall ()
q.nextset ()
columns = q.fetchall ()
assert len (tables) == 5
assert len (columns) == 10
</code></pre>
|
<p>There are a few possible methods <a href="http://www.sommarskog.se/share_data.html" rel="nofollow noreferrer">here</a>. If the result sets are all the same, you might be able to use the INSERT...EXEC method. Otherwise OPENQUERY might work.</p>
| 34,410
|
<p>What resources or methods would OpenSCAD users suggest to piece together disparate STL files?</p>
<p>I'd like to take an existing STL model-library of STL parts (head, torso, arms, legs) and make it a Thingiverse OpenSTL maker, similar to the castle generator and/or the puzzle generators available.</p>
<p>This way, users can generate a custom model using the designated parameters and download the model for printing.</p>
|
<p>Cura prior to version 2.5 does not take G-code as an input. I'm not sure what you mean by "print only using Cura." Don't you have a SD slot on your control board? For that matter, why can't you drive the USB port from Slic3r? </p>
<p>Remember: G-code is the equivalent of "compiled code," the raw commands which drive the printer, while STL or OBJ, etc., are the "source code," which you edit to get the shape you want.</p>
<p>I've looked at a few apps which will render a 3D image on your computer from G-code, but I don't know off-hand of one which will "decompile" into a STL or mesh file.</p>
|
<p>Cura prior to version 2.5 does not take G-code as an input. I'm not sure what you mean by "print only using Cura." Don't you have a SD slot on your control board? For that matter, why can't you drive the USB port from Slic3r? </p>
<p>Remember: G-code is the equivalent of "compiled code," the raw commands which drive the printer, while STL or OBJ, etc., are the "source code," which you edit to get the shape you want.</p>
<p>I've looked at a few apps which will render a 3D image on your computer from G-code, but I don't know off-hand of one which will "decompile" into a STL or mesh file.</p>
| 449
|
<p>Let's say I have a search page called Search.aspx that takes a search string as a url parameter ala Google (e.g. Search.aspx?q=This+is+my+search+string).</p>
<p>Currently, I have an asp:TextBox and an asp:Button on my page. I'm handling the button's OnClick event and redirecting in the codebehind file to Search.aspx?q=
<p>What about with ASP.NET MVC when you don't have a codebehind to redirect with? Would you create a GET form element instead that would post to Search.aspx? Or would you handle the redirect in some other manner (e.g. jQuery event attached to the button)?</p>
|
<p>You need to understand that MVC doesn't directly reference .aspx pages like WebForms in its URLs. Its main purpose is to separate concerns, that is model (data), controller (logic), and view (presentation).</p>
<p>First, you'd have to create a route matching your URLs, which would now look like this for example : /home/search/This+is+my+search+string</p>
<p>This would call the Search action method of the Home controller, which would get "This is my search string" as an input parameter. This action is responsible for accessing the model and pulling the results probably from a database.</p>
<p>Typically, your search action would then return a ViewResult containing the view placed in the folder /Views/Home/Search.aspx. Here, you can use neither the Postback functionality nor the events of your Web controls like in WebForms, because MVC applications are stateless and not event-driven. It's more like a request/dispatch way of doing things.</p>
<p><a href="http://www.asp.net/learn/mvc/" rel="nofollow noreferrer">Read more about MVC here</a>.</p>
|
<p>You can use a simple javascript in the button's onclick to redirect to the search page:</p>
<pre><code>Search <input type="text" id="go" size="4" /><input type="button" value="<%=Html.Encode(">>") %>" onclick="javascript:window.location='<%=Url.Action("Search", "Home") %>/' + document.getElementById('go').getAttribute('value')" />
</code></pre>
| 43,206
|
<p>I'm looking to build a query that will use the non-clustered indexing plan on a street address field that is built with a non-clustered index. The problem I'm having is that if I'm searching for a street address I will most likely be using the 'like' eval function. I'm thinking that using this function will cause a table scan instead of using the index. How would I go about writing one in this case? Is it just pointless to put a non-clustered index on an address3 field? Thanks in advance.</p>
|
<p>If your LIKE expression is doing a start-of-string search (<code>Address LIKE 'Blah%'</code>), I would expect the index to be used, most likely through an index seek.</p>
<p>If you search for <code>Address LIKE '%Blah%'</code>, a table scan/index scan will occur, depending on how many fields you return in your query and how selective the index is.</p>
|
<p>If your LIKE expression is doing a start-of-string search (<code>Address LIKE 'Blah%'</code>), I would expect the index to be used, most likely through an index seek.</p>
<p>If you search for <code>Address LIKE '%Blah%'</code>, a table scan/index scan will occur, depending on how many fields you return in your query and how selective the index is.</p>
| 48,539
|
<p>I am working on a new project. Is there any benefit with going with a WCF web service over a regular old fashion web service?</p>
<p>Visual Studio offers templates for both. What are the differences? Pros and cons?</p>
|
<p>What is a "regular old fashioned web service?" An ASMX service, or are you using WSE as well? ASMX services are not naturally interoperable, don't support WS-* specs, and ASMX is a technology that is aging very quickly. WSE (Web Service Enhancements) services DO add support for WS-* and can be made to be interoperable, but WCF is meant to replace WSE, so you should take the time to learn it. I would say that unless your application is a quick an dirty one-off, you will gain immense flexibility and end up with a better design if you choose WCF. WCF <em>does</em> have a learning curve beyond a [WebMethod] attribute, but the learning curve is over-exaggerated in my opinion, and it is exponentially more powerful and future proof than legacy ASMX services.</p>
<p>Unless your time line simply cannot tolerate the learning curve, you would be doing yourself a huge favor learning WCF instead of just sticking with ASP.NET Web Services. Applications will only continue to become more and more distributed and interconnected, and WCF is the future of distributed computing on the Microsoft platform.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa738737.aspx" rel="noreferrer">Here is a comparison</a> between the two.</p>
|
<p>In my experience</p>
<p><strong>WCF</strong></p>
<p>It is absurdly verbose to work with it, it is not quite compatible with other microsoft products and, of course, it is not widely accepted outside ot the microsoft world.</p>
<p>But my main problem is it is not stable, it trends to fail (in some situation) and it requires to tweak it before it can be used.</p>
<p><strong>Instead</strong></p>
<p>SOAP (aka standard Webservice), it works, it is easy to work and it is widely compatible (Java-JAX accepts it without any modification).</p>
<p>To add authentication in SOAP could be a bit tricky but not impossible.</p>
| 2,841
|
<p>I'm trying to come up with ways to speed up my secure web site. Because there are a lot of CSS images that need to be loaded, it can slow down the site since secure resources are not cached to disk by the browser and must be retrieved more often than they really need to.</p>
<p>One thing I was considering is perhaps moving style-based images and javascript libraries to a non-secure sub-domain so that the browser could cache these resources that don't pose a security risk (a gradient isn't exactly sensitive material).</p>
<p>I wanted to see what other people thought about doing something like this. Is this a feasible idea or should I go about optimizing my site in other ways like using CSS sprite-maps, etc. to reduce requests and bandwidth?</p>
|
<p>Browsers (especially IE) get jumpy about this and alert users that there's mixed content on the page. We tried it and had a couple of users call in to question the security of our site. I wouldn't recommend it. Having users lose their sense of security when using your site is not worth the added speed.</p>
|
<p>Be aware that in IE 7 there are issues with mixing secure and non-secure items on the same page, so this may result in some users not being able to view all the content of your pages properly. Not that I endorse IE 7, but recently I had to look into this issue, and it's a pain to deal with.</p>
| 47,222
|
<p>I'd like to find a Windows batch counterpart to Bash's <code>$@</code> that holds a list of all arguments passed into a script. </p>
<p>Or I have to bother with <code>shift</code>?</p>
|
<p><a href="https://stackoverflow.com/a/357338/511529">dancavallaro</a> has it right, <code>%*</code> for all command line parameters (excluding the script name itself). You might also find these useful:</p>
<p><code>%0</code> - the command used to call the batch file (could be <code>foo</code>, <code>..\foo</code>, <code>c:\bats\foo.bat</code>, etc.)<br>
<code>%1</code> is the first command line parameter,<br>
<code>%2</code> is the second command line parameter,<br>
and so on till <code>%9</code> (and <code>SHIFT</code> can be used for those after the 9th). </p>
<p><code>%~nx0</code> - the actual name of the batch file, regardless of calling method (some-batch.bat)<br>
<code>%~dp0</code> - drive and path to the script (d:\scripts)<br>
<code>%~dpnx0</code> - is the fully qualified path name of the script (d:\scripts\some-batch.bat) </p>
<p>More info examples at <a href="https://www.ss64.com/nt/syntax-args.html" rel="noreferrer">https://www.ss64.com/nt/syntax-args.html</a> and <a href="https://www.robvanderwoude.com/parameters.html" rel="noreferrer">https://www.robvanderwoude.com/parameters.html</a></p>
|
<pre>
@echo off
:start
:: Insert your code here
echo.%%1 is now:%~1
:: End insert your code here
if "%~2" NEQ "" (
shift
goto :start
)</pre>
| 46,588
|
<p>I'm running PHP on Windows/IIS.</p>
<p>My session variables don't seem to be preserved from page-to-page.</p>
<p>This code…</p>
<pre><code>//echos out the session variables in a nice format for inspection
echo "<p><pre>";
print_r($_SESSION);
echo "</pre></p>";
</code></pre>
<p>…outputs blank values, like this…</p>
<pre>
Array
(
[s_firstvar] =>
[s_var2] =>
[s_third] =>
[s_numberfour] =>
[s_youget] =>
[s_thepoint] =>
[] =>
)
</pre>
<p>I found suggestions on a forum…</p>
<blockquote>
<p>I had a similar problem recently (Win2000, IIS), and it turned out that PHP
did not have write-access to whatever directory that the session data was
stored in. You may want to look into this.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>have you set session.save_path?</p>
</blockquote>
<p>What's the proper use of php.ini's session.save_path? And, is that my problem?</p>
|
<p>can you post a bit more of your session code? some basics:</p>
<ul>
<li>did you start your session? (<a href="http://php.net/session_start" rel="nofollow noreferrer"><code>session_start()</code></a> )</li>
<li>did you check whether your save path has proper permissions (not mentioned in OP)</li>
<li>session.save_path is really just the directory sessions will be saved into. if you are on a shared service, it may be better to set it to a different directory than the default temporary directory (as your sessions would be intermingled with other app's sessions as well, and could potentially lead to a greater chance of session collision)</li>
<li>if you are altering session configurations (like <code>save_path</code>, these must be set previous to calling <code>session_start()</code>.</li>
</ul>
|
<p>can you post a bit more of your session code? some basics:</p>
<ul>
<li>did you start your session? (<a href="http://php.net/session_start" rel="nofollow noreferrer"><code>session_start()</code></a> )</li>
<li>did you check whether your save path has proper permissions (not mentioned in OP)</li>
<li>session.save_path is really just the directory sessions will be saved into. if you are on a shared service, it may be better to set it to a different directory than the default temporary directory (as your sessions would be intermingled with other app's sessions as well, and could potentially lead to a greater chance of session collision)</li>
<li>if you are altering session configurations (like <code>save_path</code>, these must be set previous to calling <code>session_start()</code>.</li>
</ul>
| 21,774
|
<p>For the last couple hours I have been messing with all sorts of different variations of SQL Server full text search. However I am still unable to figure out how the ranking works. I have come across a couple examples that really confuse me as to how they rank higher then others. For example</p>
<p>I have a table with 5 cols + more that are not indexed. All are <code>nvarchar</code> fields.</p>
<p>I am running this query (Well almost.. I retyped with different names)</p>
<pre><code>SET @SearchString = REPLACE(@Name, ' ', '*" OR "') --Splits words with an OR between
SET @SearchString = '"'+@SearchString+'*"'
print @SearchString;
SELECT ms.ID, ms.Lastname, ms.DateOfBirth, ms.Aka, ms.Key_TBL.RANK, ms.MiddleName, ms.Firstname
FROM View_MemberSearch as ms
INNER JOIN CONTAINSTABLE(View_MemberSearch, (ms.LastName, ms.Firstname, ms.MiddleName, ms.Aka, ms.DateOfBirth), @SearchString) AS KEY_TBL
ON ms.ID = KEY_TBL.[KEY]
WHERE KEY_TBL.RANK > 0
ORDER BY KEY_TBL.RANK DESC;
</code></pre>
<p>Thus if I search for <strong>11/05/1964 JOHN JACKSON</strong> I would get <strong>"11/05/1964" OR "JOHN*" OR "JACKSON*"</strong> and these results:</p>
<pre><code>ID -- First Name -- Middle Name -- Last Name -- AKA -- Date of Birth -- SQL Server RANK
----------------------------------------------------------------------------------
1 | DAVE | JOHN | MATHIS | NULL | 11/23/1965 | 192
2 | MARK | JACKSON | GREEN | NULL | 05/29/1998 | 192
3 | JOHN | NULL | JACKSON | NULL | 11/05/1964 | 176
4 | JOE | NULL | JACKSON | NULL | 10/04/1994 | 176
</code></pre>
<p>So finally my question. I don't see how row 1 and 2 are ranked above row 3 and why row 3 is ranked the same as row 4. Row 2 should have the highest rank by far seeing as the search string matches the First name and Last Name as well as the Date of birth.</p>
<p>If I change the OR to AND I don't get any results. </p>
|
<p>I've found AND and OR clauses don't apply across columns. Create an indexed view that merges the columns and you'll get better results. Look at my past questions and you'll find information that suites your scenario.</p>
<p>I also have found I'm better off not appending a '*'. I thought it'd turn up more matches, but it tended to return worse results (particularly for long words). As a middle ground you might only append a * to longer words.</p>
<p>The example case you give is definately weird.</p>
|
<p>What happens if you remove the DoB criteria?</p>
<p>MS Full-Text search is really really a black box that's hard to understand and customize
You pretty much take it AS IS, unlike Lucene is great for customization</p>
| 41,247
|
<p>I have come across numerous arguments against the inclusion of multiple inheritance in C#, some of which include (philosophical arguments aside):</p>
<ul>
<li>Multiple inheritance is too complicated and often ambiguous</li>
<li>It is unnecessary because interfaces provide something similar</li>
<li>Composition is a good substitute where interfaces are inappropriate</li>
</ul>
<p>I come from a C++ background and miss the power and elegance of multiple inheritance. Although it is not suited to all software designs there are situations where it is difficult to deny it's utility over interfaces, composition and similar OO techniques.</p>
<p>Is the exclusion of multiple inheritance saying that developers are not smart enough to use them wisely and are incapable of addressing the complexities when they arise?</p>
<p>I personally would welcome the introduction of multiple inheritance into C# (perhaps C##).</p>
<hr>
<p><strong>Addendum</strong>: I would be interested to know from the responses who comes from a single (or procedural background) versus a multiple inheritance background. I have often found that developers who have no experience with multiple inheritance will often default to the multiple-inheritance-is-unnecessary argument simply because they do not have any experience with the paradigm.</p>
|
<p>I've never missed it once, not ever. Yes, it [MI] gets complicated, and yes, interfaces do a similar job in many ways - but that isn't the biggest point: in the general sense, it simply isn't needed most of the time. Even single inheritance is overused in many cases.</p>
|
<p>Interfaces are multiple inheritance. As a matter of fact, I would consider Java/C# type interfaces the "proper" implementation of multiple inheritance. Forcing multiple inheritance through the use of interfaces, rather then allowing inheritance from multiple concrete or abstract classes forces the developer to use composition/delegation for code reuse. Inheritance should never be used for code reuse and the absence of C++ type multiple inheritance forces developers to come up with better designed classes.</p>
| 23,280
|
<p>I have extensively used Prototype before and it helped us add considerable interactivity to our web applications. However we are looking at making the move to use jQuery in order to standardize on something better supported in Visual Studio.</p>
<p>I understand that we can use the jQuery.noConflict to run it alongside Prototype, but we would like to avoid having users need to download both libraries to use our website.</p>
<p>So, is there a good resource that can help us move old scripts from Prototype to jQuery?</p>
|
<p>I can't really help you too much with your question, other than to say that I haven't heard of any such tool, and that I'd be really surprised if one actually existed.</p>
<p>While I think jQuery is a great library, and that you're right to be wanting to only use one library, just remember that the cost of you changing over all your scripts is going to be many many hours of work. The cost of your users downloading an extra 30kb of scripts is going to be roughly 0.3 seconds. Perhaps try to slowly phase out Prototype and only refactor your existing pages when a) you have to, or b) if you've got nothing better to do.</p>
|
<p>Thanks guys for your input. I was looking for more of a syntax comparison than anything automated, but nickf makes a good point in that the real cost need not be too great. We only used Prototype on a few pages that really needed a high level of interactivity, so as long as mind out Ps and Qs it should not hurt to use jQuery everywhere else.</p>
| 32,037
|
<p>How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?</p>
|
<p>Use the <code>SC</code> (service control) command, it gives you a lot more options than just <code>start</code> & <code>stop</code>.</p>
<pre>
DESCRIPTION:
SC is a command line program used for communicating with the
NT Service Controller and services.
USAGE:
sc <server> [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE:
sc start MyService
</pre>
|
<p>I am writing a windows service in C#, the stop/uninstall/build/install/start loop got too tiring. Wrote a mini script, called it <code>reploy.bat</code> and dropped in my Visual Studio output directory (one that has the built service executable) to automate the loop. </p>
<p>Just set these 3 vars </p>
<p><code>servicename</code> : this shows up on the Windows Service control panel (services.msc)</p>
<p><code>slndir</code> : folder (not the full path) containing your solution (.sln) file</p>
<p><code>binpath</code> : full path (not the folder path) to the service executable from the build</p>
<p>NOTE: This needs to be run from the Visual Studio Developer Command Line for the <code>msbuild</code> command to work.</p>
<pre><code>SET servicename="My Amazing Service"
SET slndir="C:dir\that\contains\sln\file"
SET binpath="C:path\to\service.exe"
SET currdir=%cd%
call net stop %servicename%
call sc delete %servicename%
cd %slndir%
call msbuild
cd %bindir%
call sc create %servicename% binpath=%binpath%
call net start %servicename%
cd %currdir%
</code></pre>
<p>Maybe this helps someone :)</p>
| 16,197
|
<p>I have two arrays of animals (for example).</p>
<pre><code>$array = array(
array(
'id' => 1,
'name' => 'Cat',
),
array(
'id' => 2,
'name' => 'Mouse',
)
);
$array2 = array(
array(
'id' => 2,
'age' => 321,
),
array(
'id' => 1,
'age' => 123,
)
);
</code></pre>
<p>How can I merge the two arrays into one by the ID?</p>
|
<p>This does what Erik suggested (id no. as array key) and merges vlaues in <code>$array2</code> to <code>$results</code>.</p>
<pre><code>$results = array();
foreach($array as $subarray)
{
$results[$subarray['id']] = array('name' => $subarray['name']);
}
foreach($array2 as $subarray)
{
if(array_key_exists($subarray['id'], $results))
{
// Loop through $subarray would go here if you have extra
$results[$subarray['id']]['age'] = $subarray['age'];
}
}
</code></pre>
|
<pre><code>$new = array();
foreach ($array as $arr) {
$match = false;
foreach ($array2 as $arr2) {
if ($arr['id'] == $arr2['id']) {
$match = true;
$new[] = array_merge($arr, $arr2);
break;
}
}
if ( !$match ) $new[] = $arr;
}
</code></pre>
| 4,477
|
<p>If i have a simple named query defined, the preforms a count function, on one column:</p>
<pre><code> <query name="Activity.GetAllMiles">
<![CDATA[
select sum(Distance) from Activity
]]>
</query>
</code></pre>
<p>How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?</p>
<p>Here is my attempt (im unable to test it right now), would this work?</p>
<pre><code> public decimal Find(String namedQuery)
{
using (ISession session = NHibernateHelper.OpenSession())
{
IQuery query = session.GetNamedQuery(namedQuery);
return query.UniqueResult<decimal>();
}
}
</code></pre>
|
<p>Sorry! I actually wanted a sum, not a count, which explains alot. Iv edited the post accordingly</p>
<p>This works fine:</p>
<pre><code>var criteria = session.CreateCriteria(typeof(Activity))
.SetProjection(Projections.Sum("Distance"));
return (double)criteria.UniqueResult();
</code></pre>
<p>The named query approach still dies, "Errors in named queries: {Activity.GetAllMiles}":</p>
<pre><code> using (ISession session = NHibernateHelper.OpenSession())
{
IQuery query = session.GetNamedQuery("Activity.GetAllMiles");
return query.UniqueResult<double>();
}
</code></pre>
|
<p>I think in your original example, you just need to to query.UniqueResult(); the count will return an integer.</p>
| 9,078
|
<p>Apple's CoreGraphics library defines two functions for describing an arc.</p>
<ul>
<li>CGPathAddArc adds an arc based on a center point, radius, and pair of angles.</li>
<li>CGPathAddArcToPoint adds an arc based on a radius and a pair of tangent lines.</li>
</ul>
<p>The details are explained in <a href="http://developer.apple.com/documentation/GraphicsImaging/Reference/CGPath/Reference/reference.html" rel="noreferrer">the CGPath API reference</a>. Why two functions? Simple convenience? Is one more efficient than the other? Is one defined in terms of the other?</p>
|
<p><code>CGContextAddArc</code> does this:</p>
<p><img src="https://twistedape.me.uk/blog/images/AddArc.png" alt="addArc"></p>
<p>where the red line is what will be drawn, sA is <code>startAngle</code>, eA is the <code>endAngle</code>, r is <code>radius</code>, and x and y are <code>x</code> and <code>y</code>. If you have a previous point the function will line from this point to the start of the arc (unless you are careful this line won't be going in the same direction as the arc).</p>
<p><code>CGContextAddArcToPoint</code> works like this:</p>
<p><img src="https://www.twistedape.me.uk/blog/images/2013-09-23-what-arctopoint-does-addArcToPoint.png" alt="addArc"></p>
<p>Where P1 is the current point of the path, the x1, x2, y1, y2 match the functions <code>x1</code>, <code>x2</code>, <code>y1</code>, <code>y2</code> and r is <code>radius</code>. The arc will start in the same direction as the line between the current point and <code>(x1, y1)</code> and end in the direction between <code>(x1, y1)</code> and <code>(x2, y2)</code>. it won't line to <code>(x2, y2)</code> It will stop at the end of the circle.</p>
|
<p>The former gets you a portion of a circle (really, an approximation of one), while the latter exposes the fact that you're creating a Bézier path. Depending on what you're actually drawing, one or the other might be more convenient. You could really consider both of them conveniences for CGPathAddCurveToPoint.</p>
| 10,358
|
<p>So far I've seen many posts dealing with equality of floating point numbers. The standard answer to a question like "how should we decide if x and y are equal?" is</p>
<pre><code>abs(x - y) < epsilon
</code></pre>
<p>where epsilon is a <em>fixed</em>, small constant. This is because the "operands" x and y are often the results of some computation where a rounding error is involved, hence the standard equality operator == is not what we mean, and what we should really ask is whether x and y are <em>close</em>, not equal.</p>
<p>Now, I feel that if x is "almost equal" to y, then also x*10^20 should be "almost equal" to y*10^20, in the sense that the <em>relative</em> error should be the same (but "relative" to what?). But with these big numbers, the above test would fail, i.e. that solution does not "scale".</p>
<p>How would you deal with this issue? Should we rescale the numbers or rescale epsilon? How?
(Or is my intuition wrong?)</p>
<p>Here is a <a href="https://stackoverflow.com/questions/21265/comparing-ieee-floats-and-doubles-for-equality">related question</a>, but I don't like its accepted answer, for the reinterpret_cast thing seems a bit tricky to me, I don't understand what's going on. Please try to provide a simple test.</p>
|
<p>It all depends on the specific problem domain. Yes, using relative error will be more correct in the general case, but it can be significantly less efficient since it involves an extra floating-point division. If you know the approximate scale of the numbers in your problem, using an absolute error is acceptable.</p>
<p><a href="http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm" rel="noreferrer">This page</a> outlines a number of techniques for comparing floats. It also goes over a number of important issues, such as those with subnormals, infinities, and NaNs. It's a great read, I highly recommend reading it all the way through.</p>
|
<p>Using relative error is at least not as bad as using absolute errors, but it has subtle problems for values near zero due to rounding issues. A far from perfect, but somewhat robust algorithm combines absolute and relative error approaches:</p>
<pre><code>boolean approxEqual(float a, float b, float absEps, float relEps) {
// Absolute error check needed when comparing numbers near zero.
float diff = abs(a - b);
if (diff <= absEps) {
return true;
}
// Symmetric relative error check without division.
return (diff <= relEps * max(abs(a), abs(b)));
}
</code></pre>
<p>I adapted this code from Bruce Dawson's excellent article <a href="https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/" rel="nofollow">Comparing Floating Point Numbers, 2012 Edition</a>, a required read for anyone doing floating-point comparisons -- an amazingly complex topic with many pitfalls.</p>
| 42,562
|
<p><br />I have an application where I need the user to upload a photo. After the photo is uploaded to the server, which shouldn't take very long, the user should get back a response that's a regular HTML page saying "thanks...bla bla bla..."<br />
Now, after the the response is sent back to the client and he goes on his merry way, I want the server to continue to work on this photo. It needs to do something that's heavy and would take a long time. But this is okay because the user isn't waiting for anything. He's probably in a different page.<br />
So my question is, how do I do this with ASP.NET.
The application I'm writing is in ASP.NET MVC so I'm imagining something like</p>
<pre><code>//save the photo on the server
//and send viewdata saying "thanks..."
return View();
//keep doing heavy processing on the photo
</code></pre>
<p>But I guess this isn't really how it's done. Also, since sometimes I work with ASP.NET WebForms, how is this done with WebForms as well.<br />
Thank you!</p>
|
<p>We do this for a lightweight logging situation:</p>
<pre><code>Action<object> d = delegate(object val)
{
// in this anonymous delegate, write code that you want to run
ProcessDataAndLog();
};
d.BeginInvoke(null, null, null); // this spins off the method asynchronously.
</code></pre>
<p>It's by no means robust. If you need a guarantee of being processed you should consider a message queue. That way you can also offload processing to a separate machine and not bog down your web server. </p>
<p>EDIT:</p>
<p>The following also works, and is perhaps a little more obvious to your fellow coder. It's essentially the same, but apparently faster and you don't need to worry about calling EndInvoke().</p>
<pre><code>System.Threading.ThreadPool.QueueUserWorkItem(
delegate(object state)
{
// in this anonymous delegate, write code that you want to run
ProcessDataAndLog();
});
</code></pre>
<p>Further Reading: <a href="http://www.yoda.arachsys.com/csharp/threads/threadpool.shtml" rel="noreferrer">The Thread Pool and Asynchronous Methods</a> and <a href="http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic61277.aspx" rel="noreferrer">Asynchronous delegate vs thread pool & thread</a> and <a href="http://social.msdn.microsoft.com/Forums/en-US/clr/thread/b18b0a27-e2fd-445a-bcb3-22a315cd6f0d/" rel="noreferrer">Does not calling EndInvoke <em>really</em> cause a memory leak ?</a></p>
|
<p>I'm no ASP.NET programmer, but the way you generally do this is to start another Thread on the server, which does this background processing for you while the originating Thread returns the View and exits.</p>
<p>See if you can find something if you search for "ASP.NET start Thread"</p>
| 43,482
|
<p>I would like to create an iPhone app that can open the google maps app and place a pin on the map.</p>
<p>I have the exact location of the pin, specified by its longitude and latitude.
I also have a name for the pin e.g. 'location 1' that should be displayed along with the pin.</p>
<p>I know that UIApplication:openURL can be used for this but I don't know the exact url format.</p>
<p>So, is there a way to do what I described above? If, yes, what is the correct url format?</p>
|
<p>You can use a URL of the format: <a href="http://maps.google.com/maps?q=Your+Location+name@latitude,longitude" rel="noreferrer">http://maps.google.com/maps?q=Your+Location+name@latitude,longitude</a></p>
<p><a href="http://maps.google.com/maps?q=This+is+near+Lake+Shore+Drive@41.9288,-87.6315" rel="noreferrer"><a href="http://maps.google.com/maps?q=This+is+near+Lake+Shore+Drive@41.9288,-87.6315" rel="noreferrer">http://maps.google.com/maps?q=This+is+near+Lake+Shore+Drive@41.9288,-87.6315</a></a></p>
|
<p>Why should your user have to exit your app to see a map. You can embed a Google map in your application easily. You can even drop multiple pins for which you have lat & long information. </p>
<p>In fact, in my opinion your user should never have to leave your application to view a google map.</p>
<p>An example of how to do this is included as an example application at <a href="https://sourceforge.net/projects/quickconnect/" rel="nofollow noreferrer">https://sourceforge.net/projects/quickconnect/</a>.</p>
<p>Download the QuickConnectiPhone zip file and you will find it in the Examples directory.</p>
| 26,851
|
<p>I recently came across an issue with Windows 2003 (apparently it also exists in other versions too), where if an SSL/TLS server is requesting client certificate authentication and it has more than 16KB of trusted certificate DNs, Internet Explorer (or any other app that uses schannel.dll) is unable to complete the SSL handshake. (In a nutshell, the server breaks the message into chunks of 2^14 bytes, as per RFC 2246 sec. 6.2.1, but Schannel wasn't written to support that. I've gotten confirmation from Microsoft support that this is a flaw in Schannel and that they're considering fixing it in a future release.)</p>
<p>So I'm trying to find a way to easily parse through my trusted certificates (I use Apache as my server, so all of them are in PEM format) to get the total ASN.1-format length of the DNs (which is how they get sent over the wire during the handshake), and thereby see if I'm getting too close to the limit. I haven't yet been able to find a way to do this, though: the OpenSSL asn1parse function comes close, but it doesn't seem to provide a way to get the ASN.1 sequence for just the issuer name, which is what I need.</p>
<p>Any suggestions?</p>
|
<p>Since ASN.1 is self describing, it's fairly easy to write an ASN.1 parser. As you probably know, ASN.1 data contains a tree of values, where each value type is identified by a globally assigned OID (Object ID). You can find a free ASN.1 decoder with source code at: <a href="http://www.geocities.co.jp/SiliconValley-SanJose/3377/asn1JS.html" rel="nofollow noreferrer"><a href="http://www.geocities.co.jp/SiliconValley-SanJose/3377/asn1JS.html" rel="nofollow noreferrer">http://www.geocities.co.jp/SiliconValley-SanJose/3377/asn1JS.html</a></a>. It;'s written in javascript so you can play with it directly in your browser.</p>
<p>As to your exact question - I would:</p>
<ol>
<li>Use the supplied parser, find another one or write my own</li>
<li>Find the OID of trusted DNs (check the specification or simply decode a certificate using the supplied ASN.1 decoder page)</li>
<li>Combine the two above to extract the size of trusted DNs inside a certificate.</li>
</ol>
|
<p>openssl asn1parse will do it, but you'll need to do some manual parsing to figure out where the issuer sequence begins. Per RFC 5280, it's the 4th item in the TBSCertificate sequence (potentially 3rd if it's a v1 certificate), immediately following the signature algorithm. In the following example:</p>
<pre><code> 0:d=0 hl=4 l= 621 cons: SEQUENCE
4:d=1 hl=4 l= 470 cons: SEQUENCE
8:d=2 hl=2 l= 3 cons: cont [ 0 ]
10:d=3 hl=2 l= 1 prim: INTEGER :02
13:d=2 hl=2 l= 1 prim: INTEGER :02
16:d=2 hl=2 l= 13 cons: SEQUENCE
18:d=3 hl=2 l= 9 prim: OBJECT :sha1WithRSAEncryption
29:d=3 hl=2 l= 0 prim: NULL
31:d=2 hl=2 l= 64 cons: SEQUENCE
33:d=3 hl=2 l= 11 cons: SET
35:d=4 hl=2 l= 9 cons: SEQUENCE
37:d=5 hl=2 l= 3 prim: OBJECT :countryName
42:d=5 hl=2 l= 2 prim: PRINTABLESTRING :US
46:d=3 hl=2 l= 26 cons: SET
48:d=4 hl=2 l= 24 cons: SEQUENCE
50:d=5 hl=2 l= 3 prim: OBJECT :organizationName
55:d=5 hl=2 l= 17 prim: PRINTABLESTRING :Test Certificates
74:d=3 hl=2 l= 21 cons: SET
76:d=4 hl=2 l= 19 cons: SEQUENCE
78:d=5 hl=2 l= 3 prim: OBJECT :commonName
83:d=5 hl=2 l= 12 prim: PRINTABLESTRING :Trust Anchor
97:d=2 hl=2 l= 30 cons: SEQUENCE
99:d=3 hl=2 l= 13 prim: UTCTIME :010419145720Z
114:d=3 hl=2 l= 13 prim: UTCTIME :110419145720Z
129:d=2 hl=2 l= 59 cons: SEQUENCE
</code></pre>
<p>the Issuer DN starts at offset 31 and has a header-length of two and a value length of 64, for a total length of 66 bytes. This isn't so easy to script, of course...</p>
| 9,786
|
<p>Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?</p>
<p>This is what I'm doing at the moment:</p>
<pre><code>ChannelServices.RegisterChannel(new HttpChannel(), false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton);
MyServerObject = (IRemoteServer)Activator.GetObject(
typeof(IRemoteServer),
String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port));
</code></pre>
|
<p>The first two lines are in the server-side code, for marshaling out the server object, yes?</p>
<p>In that case, yes, the third line is the simplest you can get at client-side.</p>
<p>In addition, you can serve out additional server-side objects from the <strong>MyServerObject</strong> instance, if you include public accessors for them in <strong>IRemoteServer</strong> interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:</p>
<pre><code>//obtain another marshalbyref object of the type ISessionManager:
ISessionManager = MyServerObject.GetSessionManager();
</code></pre>
|
<p>WCF. </p>
<p>I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly.</p>
<p>What’s the simplest way to connect to a .NET remote server object? WCF.</p>
| 4,556
|
<p>I have a web app on our intranet (VS 2005). There are a couple pages that don't require the user to be logged into the app (feedback and the default page). I am trying to get the domain and username to display and/or send with the feedback. Is there a way to do this without requiring the user to log in? I've tried <code>this.Request.ServerVariables["LOGON_USER"]</code> and <code>this.User.Identity.Name</code>, but neither of them worked.</p>
<p>Edit:<br>
I should have mentioned most of the users have Windows 2000 on their machines. It works on my development machine (XP), but not on the production network (where I have 2000).</p>
|
<p>Theresa, I think this is what you're looking for...</p>
<pre><code>AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal principal = (WindowsPrincipal)Thread.CurrentPrincipal;
WindowsIdentity identity = (WindowsIdentity)principal.Identity;
String userName= principal.Identity.Name;
</code></pre>
|
<p>Assuming you have turned Windows Authentication on in IIS for your site:</p>
<pre><code>public string user_Name
{
get
{
string x = Page.User.Identity.Name;
x = x.Replace("YOURDOMAIN\\", "");
return x;
}
}
</code></pre>
<p>The x = x.Replace("DOMAIN\", ""); strips out the DOMAIN sectionof the user acccount e.g NISSAN\rmcdonough</p>
| 44,462
|
<p>It has always been best practice to open links in the same window. Should that still be the rule now that most common browsers use tabs? Personally i prefer closing a tab/window over hitting the backbutton. What are your thoughts?</p>
|
<p>If you prefer closing a tab/window over hitting the back button, then by all means, click links with your middle mouse button. But please don't force your surfing preferences on others. Tabs don't change this principle in the slightest.</p>
|
<p>I'm going to wear out my scroll wheel button by the amount of tabs I open. There's a great Firefox extension that allows you to close the current tab with a single keypress, and I've assigned to it, so it's very easy to close tabs quickly.</p>
| 14,969
|
<p>We are sending out Word documents via email (automated system, not by hand). The email is sent to the user, and CC'd to me.</p>
<p>We are getting reports that some users are having the attachments come through corrupted, though when we open the copy that is CC'd to me, it opens fine.</p>
<p>When the user forwards us the copy they received, then we cannot open it.</p>
<p>Below is a hex comparison of the two files. Can anyone identity what is going on here?</p>
<p><a href="https://i.stack.imgur.com/8sSqA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8sSqA.png" width="680" height="692"></a></p>
<p>Message headers are below</p>
<pre><code>Return-Path: <info@example.co.nz>
Received: from animal.hosts.net.nz (root@localhost) by example.co.nz
(8.12.11/8.12.11) with ESMTP id m8T52Mw6021168; Mon, 29 Sep 2008 18:02:22
+1300
X-Clientaddr: 210.48.108.196
Received: from marjory.hosts.net.nz (marjory.hosts.net.nz
[210.48.108.196]) by animal.hosts.net.nz (8.12.11/8.12.11) with ESMTP id
m8T52EvU028021; Mon, 29 Sep 2008 18:02:19 +1300
Received: from example.example.co.nz ([210.48.67.48]) by
marjory.hosts.net.nz with esmtp (Exim 4.63) (envelope-from
<info@example.co.nz>) id 1KkAtd-0004Ch-I9; Mon, 29 Sep 2008 18:02:09 +1300
Received: from localhost ([127.0.0.1]) by example.example.co.nz with esmtp
(Exim 4.63) (envelope-from <info@example.co.nz>) id 1KkAtV-0001C3-4s;
Mon, 29 Sep 2008 18:02:01 +1300
From: "XXX" <info@example.co.nz>
To: "Sue" <sue@example.co.nz>
Reply-To: jayar_navarro@example.com
Subject: XXX: new application received
Date: Mon, 29 Sep 2008 18:02:01 +1300
Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline
MIME-Version: 1.0
Message-ID: <E1KkAtV-0001C3-4s@example.example.co.nz>
</code></pre>
<hr>
<p>I think I know what it is, but not why it is happening.</p>
<p>"X-Mimeole: Produced By Microsoft Exchange V6.5" the client is using Exchange. Now, compare these lines.</p>
<p>The original:</p>
<pre><code>Content-Type: multipart/mixed;
charset="utf-8";
boundary="=_5549133ca51ec83196e2cfd28dad40f7"
</code></pre>
<p>What they get:</p>
<pre><code>Content-Type: multipart/mixed;
boundary="----_=_NextPart_001_01C92270.6BBA3EE6"
</code></pre>
<p>The missing charset="UTF-8" likely means that the client will fall back to Windows-1252, which I think (can someone confirm?) result in corrupted attachments.</p>
<p>Now the question is, why would the char-set be stripped?</p>
|
<p>I have always been fond of <a href="http://www.codeblocks.org" rel="nofollow noreferrer">Code::Blocks</a> It's a wonderful C/C++ IDE, with several helpful addons. As for a compiler I've always used MingW but I hear <a href="http://www.digitalmars.com" rel="nofollow noreferrer">DigitalMars C/C++</a> compiler is good.</p>
|
<p><a href="http://www.netbeans.org/features/cpp/" rel="nofollow noreferrer">Netbeans</a> provides a fairly slick C/C++ development environment. Excellent for anyone who is already familiar with NB for Java, Ruby, or PHP development. Provides many of the same features as Visual Studio, Borland, or CodeWarrior (are they still around?) but without being tied to the proprietary libraries. It also provides for a portable development environment so you get a consistent workflow and toolset between platforms.</p>
<p>Of course, a properly configured Vim with the GNU compiler tools can provide a pretty slick experience. You don't get popups and a gui, but it can automate the build process and even jump to errors in your code.</p>
| 18,190
|
<p>How do I delimit a Javascript data-bound string parameter in an anchor <code>OnClick</code> event?</p>
<ul>
<li>I have an anchor tag in an ASP.NET Repeater control.</li>
<li>The <code>OnClick</code> event of the anchor contains a call to a Javascript function.</li>
<li>The Javascript function takes a string for its input parameter.</li>
<li>The string parameter is populated with a data-bound value from the Repeater.</li>
</ul>
<p>I need the "double quotes" for the <code>Container.DataItem</code>.<br />
I need the 'single quotes' for the <code>OnClick</code>.</p>
<p>And I still need <em>one more delimiter</em> (triple quotes?) for the input string parameter of the Javascript function call.</p>
<p>Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?</p>
<p>Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.</p>
<p>The anchor:</p>
<pre><code><a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
</code></pre>
<p>And there is my Javascript:</p>
<pre><code><script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has its ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script>
</code></pre>
|
<p>I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (<code>&#39;</code>) and double quotes (<code>&#34;</code>). </p>
<p>Source code was total mess of course but it worked.</p>
<p>Try</p>
<pre><code><a id="aShowHide" onclick='ToggleDisplay(&#34;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#34;);'>Show/Hide</a>
</code></pre>
<p>or</p>
<pre><code><a id="aShowHide" onclick='ToggleDisplay(&#39;<%# DataBinder.Eval(Container.DataItem, "JobCode") %>&#39;);'>Show/Hide</a>
</code></pre>
|
<p>Try putting the extra text inside the server-side script block and concatenating.</p>
<pre><code>onclick='<%# "ToggleDisplay(""" & DataBinder.Eval(Container.DataItem, "JobCode") & """);" %>'
</code></pre>
<p>Edit: I'm pretty sure you could just use double quotes outside the script block as well.</p>
| 2,413
|
<p>How can I achieve the following? I have two models (blogs and readers) and a JOIN table that will allow me to have an N:M relationship between them:</p>
<pre><code>class Blog < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :readers, :through => :blogs_readers
end
class Reader < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :blogs, :through => :blogs_readers
end
class BlogsReaders < ActiveRecord::Base
belongs_to :blog
belongs_to :reader
end
</code></pre>
<p>What I want to do now, is add readers to different blogs. The condition, though, is that I can only add a reader to a blog ONCE. So there mustn't be any duplicates (same <code>readerID</code>, same <code>blogID</code>) in the <code>BlogsReaders</code> table. How can I achieve this?</p>
<p>The second question is, how do I get a list of blog that the readers isn't subscribed to already (e.g. to fill a drop-down select list, which can then be used to add the reader to another blog)?</p>
|
<p>Simpler solution that's built into Rails:</p>
<pre><code> class Blog < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :readers, :through => :blogs_readers, :uniq => true
end
class Reader < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :blogs, :through => :blogs_readers, :uniq => true
end
class BlogsReaders < ActiveRecord::Base
belongs_to :blog
belongs_to :reader
end
</code></pre>
<p>Note adding the <code>:uniq => true</code> option to the <code>has_many</code> call.</p>
<p>Also you might want to consider <code>has_and_belongs_to_many</code> between Blog and Reader, unless you have some other attributes you'd like to have on the join model (which you don't, currently). That method also has a <code>:uniq</code> opiton.</p>
<p>Note that this doesn't prevent you from creating the entries in the table, but it does ensure that when you query the collection you get only one of each object.</p>
<p><strong>Update</strong></p>
<p>In Rails 4 the way to do it is via a scope block. The Above changes to.</p>
<pre><code>class Blog < ActiveRecord::Base
has_many :blogs_readers, dependent: :destroy
has_many :readers, -> { uniq }, through: :blogs_readers
end
class Reader < ActiveRecord::Base
has_many :blogs_readers, dependent: :destroy
has_many :blogs, -> { uniq }, through: :blogs_readers
end
class BlogsReaders < ActiveRecord::Base
belongs_to :blog
belongs_to :reader
end
</code></pre>
<p><strong>Update for Rails 5</strong></p>
<p>The use of <code>uniq</code> in the scope block will cause an error <code>NoMethodError: undefined method 'extensions' for []:Array</code>. Use <code>distinct</code> instead : </p>
<pre><code>class Blog < ActiveRecord::Base
has_many :blogs_readers, dependent: :destroy
has_many :readers, -> { distinct }, through: :blogs_readers
end
class Reader < ActiveRecord::Base
has_many :blogs_readers, dependent: :destroy
has_many :blogs, -> { distinct }, through: :blogs_readers
end
class BlogsReaders < ActiveRecord::Base
belongs_to :blog
belongs_to :reader
end
</code></pre>
|
<p>Easiest way is to serialize the relationship into an array: </p>
<pre><code>class Blog < ActiveRecord::Base
has_many :blogs_readers, :dependent => :destroy
has_many :readers, :through => :blogs_readers
serialize :reader_ids, Array
end
</code></pre>
<p>Then when assigning values to readers, you apply them as</p>
<pre><code>blog.reader_ids = [1,2,3,4]
</code></pre>
<p>When assigning relationships this way, duplicates are automatically removed.</p>
| 40,775
|
<p>I thought .Net code gets compiled into MSIL, so I always wondered how do Yellow Screens produce the faulty code. If it's executing the compiled code, how is the compiler able to produce code from the source files in the error message?</p>
<p>Feel free to edit this question/title, I know it doesn't really make sense.</p>
|
<p>A .Net assembly is compiled with metadata about the bytecode included that allows easy decompilation of the code - that's how tools like <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">.Net Reflector</a> work. The PDB files are debug symbols only - the difference in the Yellow Screen Of Death is that you'll get line numbers in the stack trace.</p>
<p>In other words, you'd get the code, even if the PDB files were missing.</p>
|
<p>I think this is down to the debug information that can be included with the compiled assemblies..(although I could definately be wrong)</p>
| 4,054
|
<p>I are working in a small development team of 4 people.
We are trying develop "Agile style" - story points, small tasks, etc...
Unfortunately, we are currently managing our tasks in a (shared) excel table.</p>
<p>We looked at some available tools (Mingle, TFS, Scrum for Team System), but all of these looked like they would be too much overhead and take the fun out of working.</p>
<p>What are you Agile lovers using for tracking your tasks over long period of time?</p>
<p><strong>Update</strong>
The current top answer is not really an answer to what I intended to ask - I need some tool to help me find out, over the long run, which features & tasks I estimated correctly, and where did I go horribly wrong. I see how a whiteboard/all of post-its help with managing the current or previous iterations, but I don't see myself searching for a post-it from 2 months ago.</p>
|
<p><img src="https://lh3.ggpht.com/thomas.carr/SNKKrk6eOUI/AAAAAAAAA2Y/nrhxuYzrBOQ/s512/ATT637484.jpg" alt="alt text"></p>
<hr>
<p><strong>Update Response:</strong> It doesn't seem imprortant to track WHAT was underestimated as much as WHY it was underestimated. This is something addressed at the iteration retrospective. If there are impediments, they should be addressed early and resolved. If you're looking to address something more specific than just seeing a task in the past that was undersetimated, you should ask about that. </p>
|
<p>This question is mostly a duplicate of <a href="https://stackoverflow.com/questions/12328/what-bug-tracking-software-do-you-use">https://stackoverflow.com/questions/12328/what-bug-tracking-software-do-you-use</a> which has <em>a lot</em> of answers - tasks are not necessarily bugs, but good tools let you specify other task types than 'bug'.</p>
| 12,007
|
<p>I am working on a webpage in ASP.Net/C# that uses absolute positioning for a textbox, for several in fact. It was working just fine, until I added some more text boxes. That is, the existing text boxes still positioned correctly, but the new ones did not, despite the fact that I created new styles in the CSS for them just like the others. An exampe is below:</p>
<pre><code>.pieceBox {
position: absolute;
top: 425px;
left: 133px;
background-color: White;
color: Black;
width: 132px;
font-weight: bold;
text-align: center;
}
</code></pre>
<p>Identical styles in the same CSS file (with different names of course) both above and below this one work fine. I have checked, double-checked, and triple-checked the name of the style in the CssClass attribute of the and it is correct. However, no matter what I do, including giving it a new name, copying the old entries, and renaming them, etc., these three new text boxes position themselves at the top of the page, whereas the others show in their correct absolute positions. I looked at the aspx source page and made sure they are not in some other DIV, etc. I am at my wits end with it. I did come up with a workaround for now, but it is not how I want to leave it (involves programmatically creating some HTML inside an Asp:Literal.)</p>
<p>I checked the resulting source (via IE's viewsource) and the class is set correctly in the resulting HTML.</p>
<p>One more thing in case this matters; this website project was originally created in VS 2005 and converted to VS 2008 format. Not that it should matter, but thought I would mention it.</p>
<p>Has anyone else experienced this type of behavior?</p>
|
<p>If you have absolutely positioned elements that have a parent that is either absolutely or relatively positioned, they will position themselves relative to their container instead of the whole page.</p>
<p>In other words, your elements might be positioning themselves from different origin points.</p>
|
<p>It is difficult to explain problems like this if no actual code is provided, but my first guess would be that you're having problem with new controls that are not using the same parent containers as the old ones.</p>
<p>Have you checked the css rules that apply for parent containers of properly working text boxes? They usually should be set to "position: relative;" if you want to have your child controls aligned according to them.</p>
<p>Also make sure that the layout problem isn't occurring due to overlapping of the controls i.e. two text boxes might have similar or near positions and then one comes over another.</p>
<p>In any case, if you want proper and straight solution to your problem, i would suggest that you post part of your code. </p>
| 23,425
|
<p>I'm looking for a good algorithm that can give me the unique edges from a set of polygon data. In this case, the polygons are defined by two arrays. One array is the number of points per polygon, and the other array is a list of vertex indices.</p>
<p>I have a version that is working, but performance gets slow when reaching over 500,000 polys. My version walks over each face and adds each edge's sorted vertices to an stl::set. My data set will be primarily triangle and quad polys, and most edges will be shared.</p>
<p>Is there a smarter algorithm for this?</p>
|
<p>Yes<br>
Use a double hash map.<br>
Every edge has two indexes A,B. lets say that A > B.<br>
The first, top level hash-map maps A to another hash-map which is in turn maps B to some value which represents the information you want about every edge. (or just a bool if you don't need to keep information for edges).<br>
Essentially this creates a two level tree composed of hash maps.</p>
<p>To look up an edge in this structure you take the larger index, look it up in the top level and end up with a hash map. then take the smaller index and look it up in this second hash map.</p>
|
<p>First you need to make sure your vertices are unique. That is if you want only one edge at a certain position. Then I use this data structure</p>
<p><code>typedef std::pair<int, int> Edge;</code></p>
<p><code>Edge sampleEdge;</code></p>
<p><code>std::map<Edge, bool> uniqueEdges;</code></p>
<p>Edge contains the vertex indices that make up the edge in sorted order. Hence if sampleEdge is an edge made up of vertices with index numbers 12 and 5, sampleEdge.first = 5 and sampleEdge.12</p>
<p>Then you can just do</p>
<p><code>uniqueEdges[sampleEdge] = true;</code></p>
<p>for all the edges. uniqueEdges will hold all the unique edges.</p>
| 25,458
|
<p>I have a CakePHP application that in some moment will show a view with product media (pictures or videos) I want to know if, there is someway to include another view that threats the video or threats the pictures, depending on a flag. I want to use those "small views" to several other purposes, so It should be "like" a cake component, for reutilization.</p>
<p>What you guys suggest to use to be in Cake conventions (and not using a raw <code>include('')</code> command)</p>
|
<p>In the interest of having the information here in case someone stumbles upon this, it is important to note that the solution varies depending on the CakePHP version.</p>
<h2>For CakePHP 1.1</h2>
<p><code>$this->renderElement('display', array('flag' => 'value'));</code></p>
<p>in your view, and then in <code>/app/views/elements/</code> you can make a file called <code>display.thtml</code>, where <code>$flag</code> will have the value of whatever you pass to it.</p>
<h2>For CakePHP 1.2</h2>
<p><code>$this->element('display', array('flag' => 'value'));</code></p>
<p>in your view, and then in <code>/app/views/elements/</code> you can make a file called <code>display.ctp</code>, where <code>$flag</code> will have the value of whatever you pass to it.
<hr>
In both versions the element will have access to all the data the view has access to + any values you pass to it. Furthermore, as someone pointed out, <code>requestAction()</code> is also an option, but it can take a heavy toll in performance if done without using cache, since it has to go through all the steps a normal action would.</p>
|
<blockquote>
<p>I want to use those "small views" to
several other purposes, so It should
be "like" a cake component, for
reutilization.</p>
</blockquote>
<p>This is done with "Helpers", as <a href="http://book.cakephp.org/2.0/en/views/helpers.html" rel="nofollow noreferrer">described here</a>. But I'm not sure that's really what you want. The "<a href="http://book.cakephp.org/2.0/en/views.html#elements" rel="nofollow noreferrer">Elements</a>" suggestion seems correct too. It heavily depends of what you're trying to accomplish. My two cents...</p>
| 11,917
|
<p>How do I find areas of my code that run slowly in a C++ application running on Linux?</p>
|
<p>If your goal is to use a profiler, use one of the suggested ones.</p>
<p>However, if you're in a hurry and you can manually interrupt your program under the debugger while it's being subjectively slow, there's a simple way to find performance problems.</p>
<p>Just halt it several times, and each time look at the call stack. If there is some code that is wasting some percentage of the time, 20% or 50% or whatever, that is the probability that you will catch it in the act on each sample. So, that is roughly the percentage of samples on which you will see it. There is no educated guesswork required. If you do have a guess as to what the problem is, this will prove or disprove it.</p>
<p>You may have multiple performance problems of different sizes. If you clean out any one of them, the remaining ones will take a larger percentage, and be easier to spot, on subsequent passes. This <em>magnification effect</em>, when compounded over multiple problems, can lead to truly massive speedup factors.</p>
<p><strong>Caveat</strong>: Programmers tend to be skeptical of this technique unless they've used it themselves. They will say that profilers give you this information, but that is only true if they sample the entire call stack, and then let you examine a random set of samples. (The summaries are where the insight is lost.) Call graphs don't give you the same information, because </p>
<ol>
<li>They don't summarize at the instruction level, and</li>
<li>They give confusing summaries in the presence of recursion.</li>
</ol>
<p>They will also say it only works on toy programs, when actually it works on any program, and it seems to work better on bigger programs, because they tend to have more problems to find. They will say it sometimes finds things that aren't problems, but that is only true if you see something <em>once</em>. If you see a problem on more than one sample, it is real.</p>
<p><strong>P.S.</strong> This can also be done on multi-thread programs if there is a way to collect call-stack samples of the thread pool at a point in time, as there is in Java.</p>
<p><strong>P.P.S</strong> As a rough generality, the more layers of abstraction you have in your software, the more likely you are to find that that is the cause of performance problems (and the opportunity to get speedup).</p>
<p><strong>Added</strong>: It might not be obvious, but the stack sampling technique works equally well in the presence of recursion. The reason is that the time that would be saved by removal of an instruction is approximated by the fraction of samples containing it, regardless of the number of times it may occur within a sample.</p>
<p>Another objection I often hear is: "<em>It will stop someplace random, and it will miss the real problem</em>".
This comes from having a prior concept of what the real problem is.
A key property of performance problems is that they defy expectations.
Sampling tells you something is a problem, and your first reaction is disbelief.
That is natural, but you can be sure if it finds a problem it is real, and vice-versa.</p>
<p><strong>Added</strong>: Let me make a Bayesian explanation of how it works. Suppose there is some instruction <code>I</code> (call or otherwise) which is on the call stack some fraction <code>f</code> of the time (and thus costs that much). For simplicity, suppose we don't know what <code>f</code> is, but assume it is either 0.1, 0.2, 0.3, ... 0.9, 1.0, and the prior probability of each of these possibilities is 0.1, so all of these costs are equally likely a-priori.</p>
<p>Then suppose we take just 2 stack samples, and we see instruction <code>I</code> on both samples, designated observation <code>o=2/2</code>. This gives us new estimates of the frequency <code>f</code> of <code>I</code>, according to this:</p>
<pre><code>Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&&f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.1 1 1 0.1 0.1 0.25974026
0.1 0.9 0.81 0.081 0.181 0.47012987
0.1 0.8 0.64 0.064 0.245 0.636363636
0.1 0.7 0.49 0.049 0.294 0.763636364
0.1 0.6 0.36 0.036 0.33 0.857142857
0.1 0.5 0.25 0.025 0.355 0.922077922
0.1 0.4 0.16 0.016 0.371 0.963636364
0.1 0.3 0.09 0.009 0.38 0.987012987
0.1 0.2 0.04 0.004 0.384 0.997402597
0.1 0.1 0.01 0.001 0.385 1
P(o=2/2) 0.385
</code></pre>
<p>The last column says that, for example, the probability that <code>f</code> >= 0.5 is 92%, up from the prior assumption of 60%.</p>
<p>Suppose the prior assumptions are different. Suppose we assume <code>P(f=0.1)</code> is .991 (nearly certain), and all the other possibilities are almost impossible (0.001). In other words, our prior certainty is that <code>I</code> is cheap. Then we get:</p>
<pre><code>Prior
P(f=x) x P(o=2/2|f=x) P(o=2/2&& f=x) P(o=2/2&&f >= x) P(f >= x | o=2/2)
0.001 1 1 0.001 0.001 0.072727273
0.001 0.9 0.81 0.00081 0.00181 0.131636364
0.001 0.8 0.64 0.00064 0.00245 0.178181818
0.001 0.7 0.49 0.00049 0.00294 0.213818182
0.001 0.6 0.36 0.00036 0.0033 0.24
0.001 0.5 0.25 0.00025 0.00355 0.258181818
0.001 0.4 0.16 0.00016 0.00371 0.269818182
0.001 0.3 0.09 0.00009 0.0038 0.276363636
0.001 0.2 0.04 0.00004 0.00384 0.279272727
0.991 0.1 0.01 0.00991 0.01375 1
P(o=2/2) 0.01375
</code></pre>
<p>Now it says <code>P(f >= 0.5)</code> is 26%, up from the prior assumption of 0.6%. So Bayes allows us to update our estimate of the probable cost of <code>I</code>. If the amount of data is small, it doesn't tell us accurately what the cost is, only that it is big enough to be worth fixing.</p>
<p>Yet another way to look at it is called the <a href="http://en.wikipedia.org/wiki/Rule_of_succession" rel="noreferrer">Rule Of Succession</a>.
If you flip a coin 2 times, and it comes up heads both times, what does that tell you about the probable weighting of the coin?
The respected way to answer is to say that it's a Beta distribution, with average value <code>(number of hits + 1) / (number of tries + 2) = (2+1)/(2+2) = 75%</code>.</p>
<p>(The key is that we see <code>I</code> more than once. If we only see it once, that doesn't tell us much except that <code>f</code> > 0.)</p>
<p>So, even a very small number of samples can tell us a lot about the cost of instructions that it sees. (And it will see them with a frequency, on average, proportional to their cost. If <code>n</code> samples are taken, and <code>f</code> is the cost, then <code>I</code> will appear on <code>nf+/-sqrt(nf(1-f))</code> samples. Example, <code>n=10</code>, <code>f=0.3</code>, that is <code>3+/-1.4</code> samples.)</p>
<hr>
<p><strong>Added</strong>: To give an intuitive feel for the difference between measuring and random stack sampling:<br>
There are profilers now that sample the stack, even on wall-clock time, but <em>what comes out</em> is measurements (or hot path, or hot spot, from which a "bottleneck" can easily hide). What they don't show you (and they easily could) is the actual samples themselves. And if your goal is to <em>find</em> the bottleneck, the number of them you need to see is, <em>on average</em>, 2 divided by the fraction of time it takes.
So if it takes 30% of time, 2/.3 = 6.7 samples, on average, will show it, and the chance that 20 samples will show it is 99.2%.</p>
<p>Here is an off-the-cuff illustration of the difference between examining measurements and examining stack samples.
The bottleneck could be one big blob like this, or numerous small ones, it makes no difference.</p>
<p><a href="https://i.stack.imgur.com/FpWuS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FpWuS.png" alt="enter image description here"></a></p>
<p>Measurement is horizontal; it tells you what fraction of time specific routines take.
Sampling is vertical.
If there is any way to avoid what the whole program is doing at that moment, <em>and if you see it on a second sample</em>, you've found the bottleneck.
That's what makes the difference - seeing the whole reason for the time being spent, not just how much.</p>
|
<p>As no one mentioned Arm MAP, I'd add it as personally I have successfully used Map to profile a C++ scientific program. </p>
<p>Arm MAP is the profiler for parallel, multithreaded or single threaded C, C++, Fortran and F90 codes. It provides in-depth analysis and bottleneck pinpointing to the source line. Unlike most profilers, it's designed to be able to profile pthreads, OpenMP or MPI for parallel and threaded code.</p>
<p>MAP is commercial software. </p>
| 49,190
|
<p>How do you iterate over each file in a directory with a .bat or .cmd file?</p>
<p>For simplicity please provide an answer that just echoes the filename or file path.</p>
|
<p>Command line usage:</p>
<pre><code>for /f %f in ('dir /b c:\') do echo %f
</code></pre>
<p>Batch file usage:</p>
<pre><code>for /f %%f in ('dir /b c:\') do echo %%f
</code></pre>
<p><strong>Update</strong>: if the directory contains files with space in the names, you need to change the delimiter the <code>for /f</code> command is using. for example, you can use the pipe char.</p>
<pre><code>for /f "delims=|" %%f in ('dir /b c:\') do echo %%f
</code></pre>
<p><strong>Update 2</strong>: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the <code>usebackq</code> option on the <code>for</code>:</p>
<pre><code>for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f
</code></pre>
<p>And if you need to use output redirection or command piping, use the escape char (<code>^</code>):</p>
<pre><code>for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f
</code></pre>
|
<p>I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run <code>for /f "delims=|" %f in ('forfiles') do attrib -s -h -r %f</code>.</p>
| 21,801
|
<p>How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I'd prefer not to create a separate project for it or compile it as a DLL</p>
|
<p>Server controls should be compiled into a DLL. There should be no reason to be afraid of having an additional assembly in your project, and it helps create good project organization.</p>
<p>ASP.NET Server controls are actually custom classes in an assembly. They do not have an "ascx" markup file associated to them.</p>
<p>To use a ASP.NET Server Control, you need to tell ASP.NET where to look for its class.</p>
<p>First, create a Class Library project and add it to your solution, I'll call mine "CustomControls.dll".</p>
<p>Once there, add a simple class to be your webcontrol:</p>
<pre><code>public class Hello : System.Web.UI.WebControl
{
public override Render(HtmlTextWriter writer)
{
writer.Write("Hello World");
base.Render(writer);
}
}
</code></pre>
<p>Build your project, and add it as a reference to your main web project.</p>
<p>Now, in the ASPX page that you want to use this control, you need to register it, so add this as the first line in the aspx AFTER the Page Directive:</p>
<pre><code><%@ Register TagPrefix="Example" Namespace="CustomControls" Assembly = "CustomControls" %>
</code></pre>
<p>Now, you should have a control named <Example:Hello> available to you. It might take it a minute to show up in intellisense.</p>
|
<p>Create the class for the control and build the solution. If everything goes well the control should now be available on the toolbox.</p>
<p>Sometimes the VS doesn't update the toolbox. If that happens add the Register directive to the page:</p>
<pre><code><%@ Register Assembly="NAME_OF_THE_ASSEMBLY" Namespace="NAMESPACE_OF_THE_CUSTOM_CONTROL" TagPrefix="cc1" %>
</code></pre>
<p>then just use the control on the page:</p>
<pre><code><cc1:mycustompanel id="MyCustomPanel1" runat="server"><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></cc1:mycustompanel>
</code></pre>
| 39,408
|
<p>I'm having problem in the following line:</p>
<pre><code>rd.PrintOptions.PaperSize = PaperSize.PaperFanfoldStdGerman;
</code></pre>
<p>it throws an exception saying HRESULT: 0x8002000B (DISP_E_BADINDEX)) </p>
<p>if I skip this line, the same error eccurs here:</p>
<pre><code>rd.PrintOptions.ApplyPageMargins(config)
</code></pre>
<p>Did anyone have this problem before?
thanks!</p>
|
<p>Number of rows should not matter. Make sure the fields your searching on are indexed properly. If you only have 3 varchar(25) fields, then you probably need to add a primary key that is not a varchar.</p>
|
<p>For optimal reading you should have an index. A table exists to hold the rows it was designed to contain. As the number of rows increases, the value of the index comes into play and reading remains brisk.</p>
| 36,587
|
<p>How do I find the 'temp' directory in Linux? I am writing a platform neutral C++ function that returns the temp directory. In Mac and Windows, there is an API that returns these results. In Linux, I'm stumped.
</p>
|
<p>Check following variables:</p>
<ul>
<li>The environment variable <code>TMPDIR</code></li>
<li>The value of the <a href="http://www.gnu.org/software/libc/manual/html_node/Temporary-Files.html#index-P_005ftmpdir-1608" rel="noreferrer"><code>P_tmpdir</code> macro</a></li>
</ul>
<p>If all fails try to use the directory <code>/tmp</code>.</p>
<p>You can also use <code>tempnam</code> function to generate a unique temporary file name.</p>
|
<p>In standard c, you could try: P_tmpdir</p>
| 5,094
|
<p>I need to prevent a document from being saved / saved as (say from ms word). I've looked around and I havn't quite found a satifying answer. I've considered EFS... but I don't think it prevents the user from saving the document as... (though it prevents access to the original source file). Any ideas outthere?</p>
|
<p>Run it on completely locked-down system with read-only disk, no network and no removable drives. Access to the computer must be phisically restricted as well.</p>
<p>This should prevent Save As from working, but still won't prevent document from being copied (someone may take photo of the screen and OCR it).</p>
|
<p>It usually isn't worth it to disable Save As, because you need access to the original in order to open it in the first place. There are always ways to copy a file.</p>
<p>I had the same issue come up when someone asked me to disable Save As for a PDF.</p>
| 38,516
|
<p>I wrote a windows service a few months ago that would ping a Sharepoint list using _vti_bin/lists.asmx function GetListItemChanges. It was working fine until a few weeks ago when my company upgraded our Sharepoint instance to SP1.<br>
Now whenever my service attempts to access Sharepoint I receive an 401.1 authentication error:</p>
<p>Error:</p>
<blockquote>
<p>You are not authorized to view this page <br> You do not have permission to
view this directory or page using the credentials that you supplied. <br>Please
try the following: Contact the Web
site administrator if you believe you
should be able to view this directory
or page. <br>HTTP Error 401.1 -
Unauthorized: Access is denied due to
invalid credentials. <br>Internet
Information Services (IIS)</p>
</blockquote>
<p>I have checked and my privileges on the site have not changed. here is the code In which I call the list:</p>
<pre><code>Lists listsService = new Lists();
listsService.Credentials = new NetworkCredential("UserName", "Password", "domain");
Result = listsService.GetListItemChanges("List name", null, dTime.ToString(), null);
</code></pre>
<p>It has also been brought to my attention that basic authentication may have been disabled on our farm. I don't believe I'm using that but I may be mistaken. </p>
|
<p>Based upon the information provided, I doubt this is a programming error. Can you get access to the IIS Manager interface on the server hosting the SharePoint site? If so, check the valid authentication technologies permitted. Are anonymous connections allowed? Is Windows Integrated Authentication enabled? HTTP Basic auth? Ask your infrastructure/SharePoint people about the possibility of a double-hop (proxy). If so, that might work too, but it's a pain to setup (Kerberos delegation). The NetworkCredentials class appears to support all of the standard authentication schemes supported by IIS (except for forms):</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.net.networkcredential(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.net.networkcredential(VS.80).aspx</a></p>
<p>You might need to have the infrastructure people set SPNs for the SharePoint web front end:</p>
<p><a href="http://support.microsoft.com/kb/929650" rel="nofollow noreferrer">http://support.microsoft.com/kb/929650</a></p>
<p>I advise against changing anything via IIS Manager, however. Have your SharePoint Admin make the changes to the authentication techs permitted for the site via SharePoint Central Administration.</p>
<p>Regards,
Sam</p>
|
<p>Do you have proxies on your internal network?</p>
<p>I'm thinking along the lines of double-hop, and that Basic Auth is not prone to that but that NTLM is. If you have a proxy, then the double-hop is an issue. If you are accessing the machine directly and can only count one hop (service to web service) then this shouldn't be an issue.</p>
| 41,070
|
<p>I'm an expert C# 3 / .NET 3.5 programmer looking to start doing some runtime codegen using System.Reflection.Emit.DynamicMethod. I'd love to move up to the next level by becoming intimately familiar with IL.</p>
<p>Any pointers (pun intended)?</p>
|
<p>The best way to learn it, is to write something you understand, then look at the IL it created. Also, depending on what you are doing, you can use expression trees instead of emitting IL, and then when you compile the expression trees, those smart guys at microsoft create the IL for ya.</p>
|
<p><a href="https://rads.stackoverflow.com/amzn/click/com/1590596463" rel="nofollow noreferrer" rel="nofollow noreferrer">Expert .NET 2.0 IL Assembler.</a> Although this book may be a little dated now, it was still a great overview for me.</p>
| 18,786
|
<p>Which Database table Schema is more efficient and why?</p>
<pre><code>"Users (UserID, UserName, CompamyId)"
"Companies (CompamyId, CompanyName)"
</code></pre>
<p>OR</p>
<pre><code>"Users (UserID, UserName)"
"Companies (CompamyId, CompanyName)"
"UserCompanies (UserID, CompamyId)"
</code></pre>
<p>Given the fact that user and company have one-to-one relation.</p>
|
<p>For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries.</p>
|
<p>I think you mean "many to one" when it comes to users and companies - unless you plan on having a unique company for each user.</p>
<p>To answer your question, go with the first approach. One less table to store reduces space and will make your queries use less JOIN commands. Also, and more importantly, it correctly matches your desired input. The database schema should describe the format for all valid data - if it fits the format it should be considered valid. Since a user can only have one company it's possible to have incorrect data in your database if you use the second schema.</p>
| 5,976
|
<p>I love data visualisation and to spread that love I thought we could share our favourite examples of data visualisation:</p>
<p><strong>Chess moves</strong> <a href="http://turbulence.org/spotlight/thinking/chess.html" rel="noreferrer">http://turbulence.org/spotlight/thinking/chess.html</a></p>
<p><strong>Chris Harrison's Visualisations</strong> <a href="http://www.chrisharrison.net/projects/visualization.html" rel="noreferrer">http://www.chrisharrison.net/projects/visualization.html</a></p>
<p>I especially like the bible and Wikipedia visualisations.</p>
<hr>
<p>If you're interested in creating your own visualisations a good place to start would be to check out processing.js (<a href="http://ejohn.org/blog/processingjs/" rel="noreferrer">http://ejohn.org/blog/processingjs/</a>).</p>
|
<p><a href="http://infosthetics.com/" rel="nofollow noreferrer">Information Aesthetics</a>'s feed is on my home page and has been the source of many interesting visualizations since I've placed it there.</p>
|
<p>A friend of mine did this and got it exposed at MOMA in NY</p>
<p><a href="http://pmcruz.com/information-visualization/traffic-in-lisbon-condensed-in-one-day" rel="nofollow">http://pmcruz.com/information-visualization/traffic-in-lisbon-condensed-in-one-day</a></p>
<p>It represents the trafic in lisbon over time, it was done with processing and there is no map behind it, just the coordinates of cars with public gps moving around</p>
| 30,309
|
<p>Do you have pseudocode for field validation of the following items in the UK? I am from the USA, so I only know the ones in the USA right now.</p>
<ul>
<li>Address Line 1</li>
<li>Phone Number</li>
<li>Mobile Number (in case they have a special rule for this, which they might not)</li>
<li>Post Code</li>
</ul>
|
<p>Address line 1, if you want to validate what the user entered freeform, you're probably hosed. There's huge variability. You can use the PostCode Address File (see below) to assist,</p>
<p>Typically, if you want a "standard" address, UK-oriented websites ask for the postcode, then prompt the user to choose the correct address from all addresses at that postcode</p>
<p>Phone and mobile numbers. See here <a href="http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdom</a>. A script to validate these (in several languages) can be found here: <a href="http://www.braemoor.co.uk/software/telnumbers.shtml" rel="nofollow noreferrer">http://www.braemoor.co.uk/software/telnumbers.shtml</a></p>
<p>Post code format: <a href="http://en.wikipedia.org/wiki/UK_postcodes" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/UK_postcodes</a> (contains a regular expression for validation, and refers to the Postcode Address File which lists valid addresses)</p>
|
<p>I've started the code (or at least a bunch of RegEx patterns) for Django forms validation for GB telephone numbers <a href="https://github.com/django/django/pull/316/files" rel="nofollow">here</a>.<br>
With a basic explanation <a href="http://thedjangoforum.com/board/thread/1269/" rel="nofollow">here</a>.</p>
| 34,980
|
<p>Unlike C++, in C# you can't overload the assignment operator. </p>
<p>I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...</p>
<p>Here's an example:</p>
<pre><code>Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference
</code></pre>
<p>Is there a workaround for that issue?</p>
|
<p>It's still not at all clear to me that you really need this. Either:</p>
<ul>
<li>Your Number type should be a struct (which is probable - numbers are the most common example of structs). Note that all the types you want your type to act like (int, decimal etc) are structs.</li>
</ul>
<p>or:</p>
<ul>
<li>Your Number type should be immutable, making every mutation operation return a new instance, in which case you don't need the data to be copied on assignment anyway. (In fact, your type should be immutable whether or not it's a struct. Mutable structs are evil, and a number certainly shouldn't be a mutable reference type.)</li>
</ul>
|
<p>Maybe what you're looking for can be solved using C# accessors.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa287786(v=vs.71).aspx</a></p>
| 37,343
|
<p>I've got a project which requires a fairly complicated process and I want to make sure I know the best way to do this. I'm using ASP.net C# with Adobe Flex 3. The app server is Mosso (cloud server) and the file storage server is Amazon S3. The existing site can be viewed at <a href="https://www.noisetrade.com" rel="nofollow noreferrer">NoiseTrade.com</a></p>
<p>I need to do this:</p>
<ul>
<li>Allow users to upload MP3 files to
an album "widget" </li>
<li>After the user has uploaded their
album/widget, I need to
automatically zip the mp3 (for other
users to download) and upload the
zip along with the mp3 tracks to
Amazon S3</li>
</ul>
<p>I actually have this working already (using client side processing in Flex) but this no longer works because of Adobe's flash 10 "security" update. So now I need to implement this server-side.</p>
<p>The way I am thinking of doing this is:</p>
<ul>
<li>Store the mp3 in a temporary folder
on the app server</li>
<li>When the artist "publishes" create a
zip of the files in that folder
using a c# library</li>
<li>Start the amazon S3 upload process (zip and mp3s)
and email the user when it is
finished (as well as deleting the
temporary folder)</li>
</ul>
<p>The major problem I see with this approach is that if a user deletes or adds a track later on I'll have to update the zip file but the temporary files will not longer exist.</p>
<p>I'm at a loss at the best way to do this and would appreciate any advice you might have.</p>
<p>Thanks!</p>
|
<p>The bit about updating the zip but not having the temporary files if the user adds or removes a track leads me to suspect that you want to build zips containing multiple tracks, possibly complete albums. If this is incorrect and you're just putting a single mp3 into each zip, then StingyJack is right and you'll probably end up making the file (slightly) <em>larger</em> rather than smaller by zipping it.</p>
<p>If my interpretation is correct, then you're in luck. Command-line zip tools frequently have flags which can be used to add files to or delete files from an existing zip archive. You have not stated which library or other method you're using to do the zipping, but I expect that it probably has this capability as well.</p>
|
<p>MP3's are compressed. Why bother zipping them?</p>
| 35,175
|
<p>I found this <a href="http://pecl.php.net/package/threads" rel="noreferrer">PECL package called threads</a>, but there is not a release yet. And nothing is coming up on the PHP website.</p>
|
<p>From the PHP manual for the <a href="http://php.net/pthreads"><strong>pthreads</strong></a> extension:</p>
<blockquote>
<p>pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Stackables.</p>
</blockquote>
<p>As unbelievable as this sounds, it's entirely true. Today, PHP can multi-thread for those wishing to try it.</p>
<p>The first release of PHP4, 22 May 2000, PHP was shipped with a thread safe architecture - a way for it to execute multiple instances of it's interpreter in separate threads in multi-threaded SAPI ( Server API ) environments. Over the last 13 years, the design of this architecture has been maintained and advanced: It has been in production use on the worlds largest websites ever since.</p>
<p>Threading in user land was never a concern for the PHP team, and it remains as such today. You should understand that in the world where PHP does it's business, there's already a defined method of scaling - add hardware. Over the many years PHP has existed, hardware has got cheaper and cheaper and so this became less and less of a concern for the PHP team. While it was getting cheaper, it also got much more powerful; today, our mobile phones and tablets have dual and quad core architectures and plenty of RAM to go with it, our desktops and servers commonly have 8 or 16 cores, 16 and 32 gigabytes of RAM, though we may not always be able to have two within budget and having two desktops is rarely useful for most of us.</p>
<p>Additionally, PHP was written for the non-programmer, it is many hobbyists native tongue. The reason PHP is so easily adopted is because it is an easy language to learn and write. The reason PHP is so reliable today is because of the vast amount of work that goes into it's design, and every single decision made by the PHP group. It's reliability and sheer greatness keep it in the spot light, after all these years; where it's rivals have fallen to time or pressure. </p>
<p>Multi-threaded programming is not easy for most, even with the most coherent and reliable API, there are different things to think about, and many misconceptions. The PHP group do not wish for user land multi-threading to be a core feature, it has never been given serious attention - and rightly so. PHP should not be complex, for everyone.</p>
<p>All things considered, there are still benefits to be had from allowing PHP to utilize it's production ready and tested features to allow a means of making the most out of what we have, when adding more isn't always an option, and for a lot of tasks is never really needed.</p>
<p>pthreads achieves, for those wishing to explore it, an API that does allow a user to multi-thread PHP applications. It's API is very much a work in progress, and designated a beta level of stability and completeness.</p>
<p>It is common knowledge that some of the libraries PHP uses are not thread safe, it should be clear to the programmer that pthreads cannot change this, and does not attempt to try. However, any library that is thread safe is useable, as in any other thread safe setup of the interpreter.</p>
<p>pthreads utilizes Posix Threads ( even in Windows ), what the programmer creates are real threads of execution, but for those threads to be useful, they must be aware of PHP - able to execute user code, share variables and allow a useful means of communication ( synchronization ). So every thread is created with an instance of the interpreter, but by design, it's interpreter is isolated from all other instances of the interpreter - just like multi-threaded Server API environments. pthreads attempts to bridge the gap in a sane and safe way. Many of the concerns of the programmer of threads in C just aren't there for the programmer of pthreads, by design, pthreads is copy on read and copy on write ( RAM is cheap ), so no two instances ever manipulate the same physical data, but they can both affect data in another thread. The fact that PHP may use thread unsafe features in it's core programming is entirely irrelevant, user threads, and it's operations are completely safe.</p>
<p><strong>Why copy on read and copy on write:</strong></p>
<pre><code>public function run() {
...
(1) $this->data = $data;
...
(2) $this->other = someOperation($this->data);
...
}
(3) echo preg_match($pattern, $replace, $thread->data);
</code></pre>
<p>(1) While a read, and write lock are held on the pthreads object data store, data is copied from its original location in memory to the object store. pthreads does not adjust the refcount of the variable, Zend is able to free the original data if there are no further references to it.</p>
<p>(2) The argument to someOperation references the object store, the original data stored, which it itself a copy of the result of (1), is copied again for the engine into a zval container, while this occurs a read lock is held on the object store, the lock is released and the engine can execute the function. When the zval is created, it has a refcount of 0, enabling the engine to free the copy on completion of the operation, because no other references to it exist.</p>
<p>(3) The last argument to preg_match references the data store, a read lock is obtained, the data set in (1) is copied to a zval, again with a refcount of 0. The lock is released, The call to preg_match operates on a copy of data, that is itself a copy of the original data.</p>
<p><strong>Things to know:</strong></p>
<ul>
<li><p>The object store's hash table where data is stored, thread safe, is<br>
based on the TsHashTable shipped with PHP, by Zend.</p></li>
<li><p>The object store has a read and write lock, an additional access lock is provided for the TsHashTable such that if requires ( and it does, var_dump/print_r, direct access to properties as the PHP engine wants to reference them ) pthreads can manipulate the TsHashTable outside of the defined API.</p></li>
<li><p>The locks are only held while the copying operations occur, when the copies have been made the locks are released, in a sensible order.</p></li>
</ul>
<p><strong>This means:</strong></p>
<ul>
<li><p>When a write occurs, not only are a read and write lock held, but an
additional access lock. The table itself is locked down, there is no
possible way another context can lock, read, write or affect it.</p></li>
<li><p>When a read occurs, not only is the read lock held, but the
additional access lock too, again the table is locked down.</p></li>
</ul>
<p>No two contexts can physically nor concurrently access the same data from the object store, but writes made in any context with a reference will affect the data read in any context with a reference.</p>
<p>This is shared nothing architecture and the only way to exist is co-exist. Those a bit savvy will see that, there's a lot of copying going on here, and they will wonder if that is a good thing. Quite a lot of copying goes on within a dynamic runtime, that's the dynamics of a dynamic language. pthreads is implemented at the level of the object, because good control can be gained over one object, but methods - the code the programmer executes - have another context, free of locking and copies - the local method scope. The object scope in the case of a pthreads object should be treated as a way to share data among contexts, that is it's purpose. With this in mind you can adopt techniques to avoid locking the object store unless it's necessary, such as passing local scope variables to other methods in a threaded object rather than having them copy from the object store upon execution.</p>
<p>Most of the libraries and extensions available for PHP are thin wrappers around 3rd parties, PHP core functionality to a degree is the same thing. pthreads is not a thin wrapper around Posix Threads; it is a threading API based on Posix Threads. There is no point in implementing Threads in PHP that it's users do not understand or cannot use. There's no reason that a person with no knowledge of what a mutex is or does should not be able to take advantage of all that they have, both in terms of skill, and resources. An object functions like an object, but wherever two contexts would otherwise collide, pthreads provides stability and safety. </p>
<p>Anyone who has worked in java will see the similarities between a pthreads object and threading in java, those same people will have no doubt seen an error called ConcurrentModificationException - as it sounds an error raised by the java runtime if two threads write the same physical data concurrently. I understand why it exists, but it baffles me that with resources as cheap as they are, coupled with the fact the runtime is able to detect the concurrency at the exact and only time that safety could be achieved for the user, that it chooses to throw a possibly fatal error at runtime rather than manage the execution and access to the data.</p>
<p>No such stupid errors will be emitted by pthreads, the API is written to make threading as stable, and compatible as is possible, I believe.</p>
<p>Multi-threading isn't like using a new database, close attention should be paid to every word in the manual and examples shipped with pthreads.</p>
<p>Lastly, from the PHP manual:</p>
<blockquote>
<p>pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; that is the nature of experimentation. It's limitations - often imposed by the implementation - exist for good reason; the aim of pthreads is to provide a useable solution to multi-tasking in PHP at any level. In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.</p>
</blockquote>
|
<p>There is the rather obscure, and soon to be deprecated, feature called <a href="http://docs.php.net/manual/en/control-structures.declare.php#control-structures.declare.ticks" rel="nofollow noreferrer">ticks</a>. The only thing I have ever used it for, is to allow a script to capture SIGKILL (Ctrl+C) and close down gracefully.</p>
| 25,744
|
<p>I'm currently designing a RepRap 3D printer that will not have a heated bed. I have heard that it is possible to use a power brick with commercial printers lacking heatbeds. Is this possible with a RepRap printer using a RAMPS board?</p>
<p>I'm referring specifically to the TronXY X1 power brick. I was wondering if it we're possible to use the same TronXY X1 power brick with a standard RAMPS 1.4 board - rather than the special board the TronXY X1 uses.</p>
|
<p><strong>Printing speed is dependent by the firmware and physical properties of your printer</strong>.</p>
<p>Slicers typically compute the expected time by assuming the printer will execute <em>exactly</em> what it is instructed to do, but a printer is a real object, with mass and momentum, and stepper motors that have an upper limit for their power output and rotation speed.</p>
<p>So for example, the GCODE may say "extrude 200mm at 100mm/s" and the slicer will compute that operation as taking 2 seconds. However the printer will need to accelerate and decelerate at the extremes of the movement, and it may even be incapable of reaching speeds over 70mm/s, so the <em>actual</em> operation will likely take 3 seconds or more.</p>
<p>Accelerations and decelerations account for most of the difference between ideal time and real one, and since the number and intensity of those is totally dependent by the GCODE/model being printed, <strong>it is not possible to simply multiply the computed time for a given factor</strong> (for example <code>1.15</code>, as your question seems to imply). A large cylinder printed in vase mode will have a printing time much more similar to the computed one that an intricate model with a very complex surface, for example.</p>
<p>In recent years, slicers that are maintained by a printer manufacturer (cura, slic3r PE) have become better at estimating printing times for their own printers, as the settings of the firmware are accounted for in the actual estimating algorithm.</p>
<p>If you use Octoprint, you may have noticed that the time estimate octoprint gives improves over time, as <strong>octoprint will analyse the GCODE and measure the elapsed time, and will be able to guesstimate the real time with an increasingly degree of accuracy</strong>.</p>
|
<p>I use a Anet A8 which has a system acceleration and jerk of 400 and 20
When i slice with Cura, then I use a gcode without acceleration control, because the printer does this by its own and a combination with the gcode acceleration/jerk control gets me some strange behavior (e.g. sometimes some ultra slow movement in fine detail sections, or random nearly stopped movement)
But to get a realistic approximation for the print time, i enable the acceleration/jerk control in cura and then I get a really good result, that is really close to the real values. </p>
<p>And to be more specific to your question: It is e.g. 50mm/s >>maximum<< speed you can set, not a exactly and absolut speed.
If you know your printer you can also experiment with the following approach: Set the max speed really high, so that the max material volume per time is the limiting factor and set the acceleration and jerk as low as needed for good results. So that your printer will accelerate on long lines as long as it can up to the point it has to deaccelerate for the next corner. </p>
| 875
|
<p>What is the meaning of this attribute?</p>
<pre><code><System.ComponentModel.DataObjectMethod(ComponentModel.DataObjectMethodType.Select, True)> _
</code></pre>
|
<p><a href="http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=390" rel="nofollow noreferrer">This explains it perfectly</a></p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataobjectattribute.aspx" rel="nofollow noreferrer">DataObjectAttribute</a> "identifies a type as an object suitable for binding to an ObjectDataSource object."</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataobjectmethodattribute.aspx" rel="nofollow noreferrer">DataObjectMethodAttribute</a> classifies the methods of a class used as an ObjectDataSource with regard to the type of data method is supported (select, update, insert, delete) and whether it is the default. The particular attribute referenced marks the method as the default selection method for the class.</p>
| 49,790
|
<p>Is is possible to get login credentials such as name/id if user does login by OpenId?</p>
|
<p>There are two accepted methods for retrieving these kind of things by OpenID: SReg and Attribute Exchange (AX). Both of these are extensions to the standard OpenID specification; SReg is the older of the two and specifies a set of fields that can be requested and sent with authentication, whereas AX allows requesting of any attribute.</p>
<p>Both of the specification documents are pretty concise on how they work, although it's difficult to guage what the standard "names" are for attributes to be requested from AX. Usually, servers tend to implement the SReg names.</p>
<p><a href="http://openid.net/specs/openid-simple-registration-extension-1_0.html" rel="noreferrer">OpenID Simple Registration Extension Specification 1.0</a></p>
<p><a href="http://openid.net/specs/openid-attribute-exchange-1_0.html" rel="noreferrer">OpenID Attribute Exchange Specification 1.0 Final</a></p>
|
<p>You will not get their actual username (or password), but you will get their OpenID wich is unique.</p>
| 10,771
|
<p>Using <code>MySQL</code>, I can do something like:</p>
<pre><code>SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;
</code></pre>
<p><strong>My Output:</strong></p>
<pre><code>shopping
fishing
coding
</code></pre>
<p>but instead I just want 1 row, 1 col:</p>
<p><strong>Expected Output:</strong></p>
<pre><code>shopping, fishing, coding
</code></pre>
<p>The reason is that I'm selecting multiple values from multiple tables, and after all the joins I've got a lot more rows than I'd like.</p>
<p>I've looked for a function on <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws" rel="noreferrer">MySQL Doc</a> and it doesn't look like the <code>CONCAT</code> or <code>CONCAT_WS</code> functions accept result sets.</p>
<p>So does anyone here know how to do this?</p>
|
<p>You can use <a href="https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat" rel="noreferrer"><code>GROUP_CONCAT</code></a>:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Ludwig stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment14513101_276949">his comment,</a> you can add the <code>DISTINCT</code> operator to avoid duplicates:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Jan stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field#comment72475644_276949">their comment,</a> you can also sort the values before imploding it using <code>ORDER BY</code>:</p>
<pre><code>SELECT person_id,
GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;
</code></pre>
<p>As Dag stated in <a href="https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field/276949#comment12638055_276949">his comment,</a> there is a 1024 byte limit on the result. To solve this, run this query before your query:</p>
<pre><code>SET group_concat_max_len = 2048;
</code></pre>
<p>Of course, you can change <code>2048</code> according to your needs. To calculate and assign the value:</p>
<pre><code>SET group_concat_max_len = CAST(
(SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
FROM peoples_hobbies
GROUP BY person_id) AS UNSIGNED);
</code></pre>
|
<p>In sql server use string_agg to pivot a row field values into a column:</p>
<pre><code>select string_agg(field1, ', ') a FROM mytable
or
select string_agg(field1, ', ') within group (order by field1 dsc) a FROM mytable group by field2
</code></pre>
| 34,934
|
<p>I'm trying to use xcodebuild and OCUnit with my Continuous Integration server (<a href="http://www.jetbrains.com/teamcity/" rel="noreferrer">TeamCity</a>). </p>
<p>JetBrains offers test observer implementations for boost::test and CppUnit that format test output in a way that TeamCity can interpret. I need to do something similar for OCUnit if I want to use it.</p>
<p>There appears to be a SenTestObserver class in OCUnit but I'm ignorant of how exactly it should be used, and the <a href="http://www.sente.ch/software/ocunit/" rel="noreferrer">OCUnit homepage</a> doesn't seem to provide any documentation on the matter.</p>
|
<p>You can write your own observer by extending the SenTestObserver class and implementing the notification listeners</p>
<ul>
<li>(void) testSuiteDidStart:(NSNotification *) aNotification</li>
<li>(void) testSuiteDidStop:(NSNotification *) aNotification</li>
<li>(void) testCaseDidStart:(NSNotification *) aNotification</li>
<li>(void) testCaseDidStop:(NSNotification *) aNotification</li>
<li>(void) testCaseDidFail:(NSNotification *) aNotification</li>
</ul>
<p>then add an entry to the info.plist SenTestObserverClass with the name of your class.</p>
<p>At least in the version of OCUnit i'm familiar with SenTestObserver is equal parts useful/equal parts broken. I just skip it altogether and register for the notifications myself in my own class. (see SenTestSuiteRun.h and SenTestCaseRun.h for the defines of the notification names).</p>
<p>You can use the test and run properties of the notification to access the SenTestSuite and SenTestSuiteRun instances, and the run instance contains the info needed on the actual results.</p>
|
<p>I have implemented a simple Teamcity Adapter, you can view the <a href="https://gist.github.com/994882" rel="nofollow">gist here</a>. SenTestObserver isn't exactly broken, it simply doesn't adhere to the best practices:</p>
<p>This is what you need to call in your Observer subclass to have it properly registered:</p>
<pre><code>+(void)initialize
{
[[NSUserDefaults standardUserDefaults] setValue:@"TeamCityAdapter" forKey:@"SenTestObserverClass"];
// we need to force SenTestObserver to register us as a handler
// SenTestObserver is properly guarding against this invocation so nothing bad will hapen
// but this is required (bad design on SenTestObserver's side)...
[super initialize];
}
</code></pre>
<p>because SenTestObserver's initialize looks like this:</p>
<pre><code>+ (void) initialize
{
if ([self class] == [SenTestObserver class]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *registeredDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
@"SenTestLog" , @"SenTestObserverClass",
nil];
[defaults registerDefaults:registeredDefaults];
[NSClassFromString ([defaults objectForKey:@"SenTestObserverClass"]) class]; // make sure default observer is loaded
}
if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"SenTestObserverClass"] isEqualToString:NSStringFromClass(self)]) {
[self setCurrentObserver:self];
}
}
</code></pre>
<p>I hope this will help others out there looking for a teamcity adapter for OCUnit / SenTestingKit.</p>
| 30,755
|
<p>I am considering building a application using PRISM (Composite WPF Guidance/Library). The application modules will be vertically partitioned (i.e. Customers, Suppliers, Sales Orders, etc). This is still all relatively easy... I also have a Shell with a main region were all the work will happen but now I need the following behavior: I need a menu on my main Shell and when each one of the options gets clicked (like customers, suppliers, etc) I need to find the module and load it into the region (Only 1 view at a time)? </p>
<p>Does anybody know of any sample applications with this type of behavior? All the samples are more focused on having all the modules loaded on the main shell? And should my menu bar also be a module?</p>
<p>[<strong>UPDATE</strong>] How do I inject a module into a region based on it being selected from a menu? All the examples show that the module injects the view into the region on initialize? I need to only inject the view if the module is selected on a menu?</p>
|
<p>Just finished watching <a href="http://www.dnrtv.com/default.aspx?showNum=124" rel="nofollow noreferrer">Brian Noyes on Prism</a> at dnrTV. This answered all my question... </p>
|
<p>to save you time, check <a href="http://johnpapa.net/building-a-presentation-framework-with-prism-for-silverlight" rel="nofollow noreferrer">John Papa's Presentation Framework article</a>. It will be more easy if you have 3rd object(<code>Screen Conductor</code>) to handle your screens in showing or hiding from regions.</p>
| 7,181
|
<p>I'm trying to unit test a page in my ASP.NET MVC application that, when posted to, will delete a user's item. I want to restrict this page so that it can only be posted to by the owner of said item. Originally, I wanted to just stick a quick check in the controller that checked if the HttpContext.Current.User.Identity.Name is equal to the owner of the item, but I quickly realized that unit testing this would be difficult.</p>
<p>Should I create an interface that provides a way to access the current logged-in user's name?</p>
|
<p>The last line of your question is probably the quickest solution, however, I don't think you need to create the interface, <code>HttpContext.Current.User</code> is already an <code>IPrincipal</code> and <code>HttpContext.Current.User.Identity</code> is already an <code>IIdentity</code>.</p>
<p>If your checking logic uses either of those interfaces, the controller can be mocked to pass an IIdentity that you create instead of the HttpContext.Current.User.Identity</p>
<p>Hope that helps!</p>
|
<p>I use Thread.CurrentPrincipal.Identity.Name. It's trivial to create a GenericPrincipal for a unit test and attach it.</p>
| 37,902
|
<p>This isn't a question but I thought I'd start a thread where links to exceptionally useful (and widely applicable) vb6 code could be placed.</p>
<p>My choice is by someone called John Korejwa and is located on planet sourcecode at </p>
<p><a href="http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=50065&lngWId=1" rel="nofollow noreferrer">http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=50065&lngWId=1</a></p>
<p>Basically what it does is to overcome a serious deficiency in vb6 without resorting to 3rd party components</p>
<p>In vb6 pictures can only be stored as bitmaps. If your application involves capturing and storing images (such as document scans) this can require vastly greater hard disk space than if th images coulsd be stored as jpgs.</p>
<p>That's what this source code provides via a single class that incorporates jpeg compression code.</p>
<p>This limitation is the cause of innumerable questions on vb forums but this is the only code I've ever found that solves the problem just using code inside your vb6 program.</p>
|
<p><a href="http://www.vbaccelerator.com/home/index.asp" rel="noreferrer">http://www.vbaccelerator.com/home/index.asp</a></p>
<p>More useful VB6 code then you can shake a stick at :)</p>
|
<p><a href="http://www.freevbcode.com/" rel="nofollow noreferrer">FreeVBCode.com</a> has always been my favorite place to look before reinventing the wheel.</p>
| 28,818
|
<p>Most of our Eclipse projects have multiple source folders, for example:</p>
<ul>
<li>src/main/java</li>
<li>src/test/java</li>
</ul>
<p>When you right-click on a class and choose New JUnit Test, the default source folder for the new test is "src/main/java" (presumably the first source folder listed in the project properties).</p>
<p>Is there any way to change the default source folder for new JUnit tests, so that when I do the above action, the new test will be created in say the "src/test/java" folder by default?</p>
|
<p>I use <a href="http://moreunit.sourceforge.net/" rel="noreferrer">moreUnit</a>, an Eclipse plugin to assist writing unit tests. Among other features, it lets you configure the default source folder of tests.</p>
|
<p>Now you can use my fast code eclipse plug-in. With this plug-in you can configure the test path to be <code>src/test/java</code> only once. It also has a jump to the unit test feature. It is available at : <a href="http://fast-code.sourceforge.net/" rel="nofollow">http://fast-code.sourceforge.net/</a>.</p>
| 9,451
|
<p>For some reason the Windows command prompt is "special" in that you have to go to a properties dialog to resize it horizontally rather than just dragging the corner of the window like every other app. Unsurprisingly this feature made it into P-P-P-Powershell as well -- is there any way around this via command prompt replacement or Windows hackery?</p>
|
<p>2019 Update:</p>
<ul>
<li>Microsoft has released the terminal app on <a href="https://github.com/microsoft/terminal" rel="nofollow noreferrer">Github</a> & the <a href="https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701" rel="nofollow noreferrer">Windows Store</a>, and it has tabs, panels, acrylic transparency, and other features.</li>
</ul>
<p>2016 Update:</p>
<ul>
<li>Windows 10's default conhost UI has more features, including free resize, transparency, etc (this includes cmd & powershell)</li>
<li>I now use <a href="https://code.google.com/p/conemu-maximus5/" rel="nofollow noreferrer">ConEmu</a> (walkthrough <a href="http://www.hanselman.com/blog/ConEmuTheWindowsTerminalConsolePromptWeveBeenWaitingFor.aspx" rel="nofollow noreferrer">here</a>) which has many features including tabs & split panes.</li>
<li>Other options include <a href="http://cmder.net/" rel="nofollow noreferrer">Cmder</a> (which comes with additional tools built in), and <a href="https://chocolatey.org/packages/ConsoleZ" rel="nofollow noreferrer">ConsoleZ</a> (a fork of Console2).</li>
<li><a href="http://sourceforge.net/projects/console" rel="nofollow noreferrer">Console</a> appears to no longer be updated</li>
</ul>
|
<p>You might consider installing <a href="http://www.farmanager.com/" rel="nofollow noreferrer">FAR</a>. It's an excellent text mode file manager and much more. It could also be resized by dragging the corner of the window :)</p>
| 18,602
|
<p>I have a question about how to deploy WPF application into a PC without Framework 3.5.
If a PC just installs Windows XP and sp3, Is it possible to design a setup package that can install WPF Application directly on this PC?
<p>
The situation is like this:<p>
I designed a simple WPF Application. And I want to get its setup package.
When the customs get the package, they can install the application directly, even if their PCs do not have Framework3.5 installed.
<p>
Is it possible?
If it is possible, how can I do this?
<p>
//-----------------------------------------------------------<p>
I found Matt give a http://forums.microsoft.com/EmbeddedWindows/ShowPost.aspx?PostID=3967493&SiteID=47>solution
Is it the only solution?<p></p>
<p>You can delete .NET assemblies you don't use from the GAC as long as you test your app to make sure that you don't trim down too much. Majority of .NET assemblies are wrappers on top of Win32 API so they can be removed without affecting the OS.</p>
<ul>
<li>You can get the list of which assemblies you are using by looking at References node in Visual Studio solution explorer on your development machine. All dependencies are there (If assembly A depends on assembly B, both A and B mist be in the list) but there are some assemblies belonging to the runtime itself such as Accessibility.dll see the list below.</li>
<li>Make sure you use gacutil.exe (can be called from Visual Studio command prompt) to remove the assemblies. You have to run gacutil after you boot up your embedded image and have .NET installed. Just copy the SDK\v2.0\bin folder from Visual studio</li>
<li>gacutil.exe /l can be used to list all assemblies installed.
I used to try to run WPF application on WinPE with no .NET installed. I just manually install the CLR + about 30 dlls from .NET. Here is the list of all files required
10/19/2006 05:13 PM 10,752 Accessibility.dll
09/18/2006 01:32 PM 66,728 big5.nlp
09/18/2006 01:32 PM 82,172 bopomofo.nlp
11/01/2006 10:34 PM 17,920 Culture.dll
11/01/2006 10:34 PM 9,728 fusion.dll
09/18/2006 01:32 PM 116,756 ksc.nlp
11/01/2006 10:34 PM 326,656 mscorjit.dll
10/19/2006 05:14 PM 4,366,336 mscorlib.dll
11/01/2006 10:34 PM 330,752 mscorrc.dll
11/01/2006 10:34 PM 5,632,512 mscorwks.dll
09/18/2006 01:32 PM 59,342 normidna.nlp
09/18/2006 01:32 PM 45,794 normnfc.nlp
09/18/2006 01:32 PM 39,284 normnfd.nlp
09/18/2006 01:32 PM 66,384 normnfkc.nlp
09/18/2006 01:32 PM 60,294 normnfkd.nlp
09/18/2006 01:32 PM 83,748 prc.nlp
09/18/2006 01:32 PM 83,748 prcp.nlp
11/02/2006 04:36 AM 3,915,264 PresentationCore.dll
02/23/2007 06:06 PM 184,320 PresentationFramework.Aero.dll
02/23/2007 06:06 PM 126,976 PresentationFramework.Classic.dll
11/02/2006 04:36 AM 4,972,544 PresentationFramework.dll
02/23/2007 06:06 PM 376,832 PresentationFramework.Luna.dll
09/18/2006 01:32 PM 262,148 sortkey.nlp
09/18/2006 01:32 PM 20,320 sorttbls.nlp
10/19/2006 05:14 PM 413,696 System.configuration.dll
10/19/2006 05:14 PM 3,035,136 System.dll
10/19/2006 05:14 PM 704,512 System.Drawing.dll
10/19/2006 05:14 PM 5,414,912 System.Windows.Forms.dll
10/19/2006 05:14 PM 2,039,808 System.XML.dll
02/23/2007 06:06 PM 32,768 UIAutomationProvider.dll
02/23/2007 06:06 PM 86,016 UIAutomationTypes.dll
11/02/2006 04:36 AM 1,167,360 WindowsBase.dll
09/18/2006 01:33 PM 28,288 xjis.nlp</li>
</ul>
<p>Hope that helps</p>
<p>Matt</p>
|
<p>Visual Studio 2008 SP1 adds support for the "Client Profile" subset of the .NET Framework. If the Windows XP SP3 machines you're targeting don't have any version of the .NET Framework installed already, this will install a slimmed-down version of the Framework with the assemblies you need for a WPF app. Microsoft provides a bootstrapper installer that will install/update the .NET Framework on the client machine, then chain to your installer to install your application. Here are some links to get started:</p>
<ul>
<li>Overview of the <a href="http://msdn.microsoft.com/en-us/library/cc656912.aspx" rel="nofollow noreferrer">.NET Client Profile</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc656819.aspx" rel="nofollow noreferrer">Walkthrough: Deploying a .NET Framework Client Profile Application by using Windows Installer</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/cc656916.aspx" rel="nofollow noreferrer">Walkthrough: Deploying a .NET Framework Client Profile Application by using ClickOnce</a></li>
</ul>
|
<p>When you use ClickOnce, In your Deploy Option from Project Propertys, set your requireds assemblyes as included, then if you really needs some assemblyes, use gacutil.exe or drag and drop on your client local GAC</p>
| 23,225
|
<p>If i make a label in TFS, and later make a new label with the same name... then the old label is replaced by the new one. </p>
<p>How do I prevent TFS from overwriting a label?</p>
|
<p>The following MSDN article covers <a href="http://msdn.microsoft.com/en-us/library/9ew32kd1(VS.80).aspx" rel="nofollow noreferrer">using the Scope of a label to try and minimize the occurrences of these mishaps</a>:</p>
<blockquote>
<p><strong>Using the /Child Option to Avoid Labeling Mishaps</strong></p>
<p>If you issue a label command together with a pre-existing label name and an itemspec that includes files that are already marked by the same label, the value of the /child option determines whether the marked files are updated with new revision information. That is, the files are labeled by the same name, but have different scope.</p>
</blockquote>
|
<p>Thanks, that led me on the right track. </p>
<p>It seems that the label overwrite is a "feature" and not a bug. It's working as designed
sixletter's link above explains it, and below are two more with info about it.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms181439(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms181439(VS.80).aspx</a>
<a href="http://msdn.microsoft.com/en-us/library/ms181440(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms181440(VS.80).aspx</a></p>
<p>Apparently TFS labels are not a snaphot of a point in time like in other VCS's , though i do not fully understand the explanation.</p>
| 14,037
|
<p>How can we produce the effect of the red line under a bad spelling word like the image below :</p>
<p><a href="http://img505.imageshack.us/img505/7253/options285x395rg9.th.png" rel="nofollow noreferrer">alt text http://img505.imageshack.us/img505/7253/options285x395rg9.th.png</a></p>
<p><strong>Update</strong></p>
<p>I do not want to use Google or whatever spell program. I would like to know how to create the effect of the red line.</p>
|
<p>You can do this using a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox?view=windowsdesktop-6.0" rel="nofollow noreferrer">RichTextBox</a> control, which will allow you to set the underline style and underline color on any portion of text.</p>
<p>And here's an <a href="https://web.archive.org/web/20200803184227/http://geekswithblogs.net/pvidler/archive/2003/10/15/188.aspx" rel="nofollow noreferrer">example</a> doing exactly what you want to do.</p>
|
<p>use google's spellchecker</p>
<p><a href="http://www.asp101.com/articles/jeremy/googlespell/default.asp" rel="nofollow noreferrer">http://www.asp101.com/articles/jeremy/googlespell/default.asp</a></p>
| 21,633
|
<p>I need to round a value up to the nearest multiple of 2.5.</p>
<p>For example:<br>
6 --> 7.5<br>
7.6 --> 10<br>
etc. </p>
<p>This seems like the best way to do this?</p>
<pre><code> Function RoundToIncrement(ByVal originalNumber As Decimal, ByVal increment As Decimal) As Decimal
Dim num = Math.Round(originalNumber / increment, MidpointRounding.AwayFromZero) * increment
If originalNumber Mod increment <> 0 And num < originalNumber Then
num += increment
End If
Return num
End Function
</code></pre>
|
<p>Divide the number by 2.5, round up to the nearest integer, then multiply the result by 2.5.</p>
<p>You're close.</p>
<pre><code>Function RoundToIncrement(ByVal orignialNumber As Decimal, ByVal increment As Decimal) As Decimal
Return Math.Ceiling( orignialNumber / increment ) * increment
End Function
</code></pre>
<p>Math.Ceiling will always round non-integers up, so you don't need the post-adjustment.</p>
|
<pre><code> /*
This will round up (Math.Ceiling) or down (Math.Floor) based on the midpoint of the increment.
The other examples use Math.Ceiling and therefore always round up.
Assume the increment is 2.5 in this example and the number is 6.13
*/
var halfOfIncrement = Increment / 2; // 2.5 / 2 = 1.25
var floorResult = Math.Floor(originalNumber / Increment); //Math.Floor(6.13 / 2.5) = Math.Floor(2.452) = 2
var roundingThreshold = (floorResult * Increment) + halfOfIncrement; //(2 * 2.5) = 5 + 1.25 = 6.25
if (originalNumber >= roundingThreshold) //6.13 >= 6.25 == false therefore take Math.Floor(6.13/2.5) = Math.Floor(2.452) = 2 * 2.5 = 5
result = Math.Ceiling(originalNumber / Increment) * Increment;
else
result = Math.Floor(originalNumber / Increment) * Increment;
</code></pre>
| 28,133
|
<p>I am facing a problem.
I would like to localize my action names in my project so french people can have clean urls with french names.</p>
<p><a href="http://www.test.com/Home" rel="nofollow noreferrer">http://www.test.com/Home</a> should be <a href="http://www.test.com/Accueil" rel="nofollow noreferrer">http://www.test.com/Accueil</a></p>
<p>It is a good thing too for google indexing.
Moreover I would like to be Restful on the application, so I would like too keep english name because developers (even frenchies) prefer to work on english names.</p>
<p>I don't know if it's possible and how.</p>
<p>My first idea should be something like get the browser language, assign it to the CurrentThread.CurrentCulture, so I can select the view name I want.</p>
<p>Thank you very much for your answers.</p>
|
<p>you can do this when you register the routes in global.asax.</p>
<p>if normally you have this:</p>
<pre><code>routes.MapRoute("Catalog-Brands", "catalog/brand/", new {controller = "Brand", action = "Index", isActive = true});
</code></pre>
<p>you could make this one too (I don't know french, sorry)</p>
<pre><code>routes.MapRoute("Catalog-Brands-French", "french-catalog/french-brand/", new {controller = "Brand", action = "Index", isActive = true});
</code></pre>
<p>you could either make them all available globally or have separate:</p>
<pre><code>public static void RegisterUsRoutes
public static void RegisterFrenchRoutes
</code></pre>
<p>you'd have to make the decision at application startup though (you may or may not be able to register routes at runtime.)</p>
|
<p>If you can use ISAPIs, that is to say, if you control IIS, the best thing is to use a ISAPI I recommend you Ionics Isapi:
<a href="http://www.codeplex.com/IIRF" rel="nofollow noreferrer">http://www.codeplex.com/IIRF</a></p>
<p>It implements more or less what Rewrite mod in Apache does (redirections).</p>
| 40,760
|
<p>How can I check the existence of an element in jQuery?</p>
<p>The current code that I have is this:</p>
<pre><code>if ($(selector).length > 0) {
// Do something
}
</code></pre>
<p>Is there a more elegant way to approach this? Perhaps a plugin or a function?</p>
|
<p>In JavaScript, everything is 'truthy' or 'falsy', and for numbers <code>0</code> means <code>false</code>, everything else <code>true</code>. So you could write:</p>
<pre><code>if ($(selector).length)
</code></pre>
<p>You don't need that <code>>0</code> part.</p>
|
<p>Use the following syntax to check if the element actually exists using jQuery.</p>
<pre><code>let oElement = $(".myElementClass");
if(oElement[0]) {
// Do some jQuery operation here using oElement
}
else {
// Unable to fetch the object
}
</code></pre>
| 5,089
|
<p>The back button just causes my page to refresh. Is there a way around this without disabling the cache?</p>
|
<p>Try adding this to your HTML header:</p>
<pre><code><META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
</code></pre>
|
<p>where you click on product/image on page there call onclick javascript function i.e.</p>
<pre><code>function getHashOnBack(valueget)
{
location.hash = "#backTo=" + $(window).scrollTop();$(document).height();
}
</code></pre>
<p>Now, put</p>
<pre><code>$(document).ready(function ()
{
var ab = window.location.hash.substring(1).split("=");
if (ab[0] == "backTo")
{
// this would be called automatically when back putton pressed and hav #back=1234 etc. // value in url
$(window).scrollTop(parseInt(ab[1]));
}
}
</code></pre>
| 25,588
|
<p>By definition algorithms are independent from the medium they run on. E.g. I use Excel tables to play with data structures and to do some move/shuffling/marking experiments before implementing an algorithm in a programming language. </p>
<p>What tools and techniques do you use to design and simulate the function of an algorithm? How do you use drawing programs? A special specification language?</p>
|
<p>Algorithms are independent of language, true. But any medium you use is a language, period. Using Excel means you're using the excel "language" (rows, columns, cells, etc.) to express some of your algorithm. Maybe not the complete, finished product, but you've expressed it in Excel.</p>
<p>UML diagrams are a language for expressing an algorithm. A sketch on paper is a language for expression. It's hard to separate the platonic ideal algorithm from all concrete representations. No matter what you do, you're expressing it in some language.</p>
<p>The trick is to separate the algorithm from specific language features and limitations.</p>
<p>Any "informal" notation will help do this. English (or other natural language), mathematics, diagrams, etc., are all candidates for expressing an algorithm in a language that's free from implementation quirks and problems.</p>
<p>I start with an overview in English. Plain text, not even MS-Word or something where formatting is a distractor.</p>
<p>For really complex things, a little supplemental mathematics helps put formal assertions around the state of the program.</p>
<p>Also, UML diagrams help. I use <a href="http://argouml.tigris.org/" rel="nofollow noreferrer">Argo UML</a> -- cheap and effective.</p>
<p>For more on this topic, you want to read about <a href="http://en.wikipedia.org/wiki/Formal_verification" rel="nofollow noreferrer">formal verification</a> systems.</p>
|
<p>I guess it depends on the complexity of the algorithm.</p>
<p>Quite often I'll actually draw a quick sketch of a flowchart on some paper. There are some excellent diagramming tools available, but I still haven't found one that is as quick as a good old fashioned sketch on a piece of paper.</p>
<p>Other than that, I often end up throwing together a really 'quick and dirty' mock up of the algorithm in a VB.NET windows forms or console application. With some of the more recent features like LINQ-to-SQL, you can even put together prototypes that rely on database access in a very short space of time.</p>
| 42,175
|
<p>Conventional IPv4 dotted quad notation separates the address from the port with a colon, as in this example of a webserver on the loopback interface:</p>
<pre><code>127.0.0.1:80
</code></pre>
<p>but with IPv6 notation the address itself can contain colons. For example, this is the short form of the loopback address:</p>
<pre><code>::1
</code></pre>
<p>How are ports (or their functional equivalent) expressed in a textual representation of an IPv6 address/port endpoint? </p>
|
<p>They work almost the same as today. However, be sure you include <code>[]</code> around your IP.</p>
<p>For example : <a href="http://en.wikipedia.org/wiki/IPv6_address#Literal_IPv6_addresses_in_network_resource_identifiers" rel="noreferrer"><code>http://[1fff:0:a88:85a3::ac1f]:8001/index.html</code></a></p>
<p>Wikipedia has a pretty good article about IPv6: <a href="http://en.wikipedia.org/wiki/IPv6#Addressing" rel="noreferrer">http://en.wikipedia.org/wiki/IPv6#Addressing</a></p>
|
<p>They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.</p>
| 22,614
|
<p>I have a number of databases on a Windows 2000 Server running the 32 bit version of SQL Server 2000. I need to transfer all the data and settings to a new server running the 64 bit version of SQL 2008 on Windows 2003 64 bit.</p>
<p>Is this as simple as backing up the databases and restoring to the new server. Will this work with the system databases (master, model, msdb) as well? If not, is there a way to automate the process of moving across the user accounts and permissions?</p>
<p>Is anybody aware of any other gotchas?</p>
<p>Many thanks for any help.</p>
<p>[EDIT] I've successfully tested an upgrade to SQL2008 32-bit, I'm mostly concerned with any differences in the 64-bit version as I don't have a 64 bit server I can test on at the moment e.g. I know you can't restore a SQL2000 master database to 2008; can you restore a SQL2008 32bit master to SQL2008 64bit? Downtime during the migration is not a problem.</p>
|
<p>To transfer logins, you should be able to use the 'Transfer Logins Task' described in Books Online <a href="http://technet.microsoft.com/en-us/library/ms137870.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>Ross Mistry has published a few <a href="http://www.networkworld.com/community/node/30052" rel="nofollow noreferrer">articles</a> on SQL Server 2008 Installation Strategies and Best Practices. Also this <a href="http://www.dell.com/downloads/global/solutions/public/white_papers/SQL_2000_SQL_2008_Migration_Guide.pdf" rel="nofollow noreferrer">document</a>, although directed at specific hardware, contains useful info.</p>
<p>EDIT: Have you looked at the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F5A6C5E9-4CD9-4E42-A21C-7291E7F0F852&displaylang=en" rel="nofollow noreferrer">Microsoft SQL Server 2008 Upgrade Advisor</a>?</p>
|
<p>I would use the RedGate SQL Compare and SQL Data Compare. That would give you some assurances of the integrity of the database. However its not going to be an online migration of the data, you would have to prevent updates during the transition.</p>
| 39,701
|
<p>Does the change of macs over to Intel chips mean we are done with the bit twiddling on numbers in binary resources for cross platform data distributions?</p>
<p>Is that the last of this problem or are there some other platforms I'm not aware of?</p>
|
<p>You seem to forget the endianness transcends processor architectures. There are plenty of algorithms and protocols that demand a particular byte order. For example, I spent two weeks trying to get an MD5 hashing algorithm to work, only to realize that I had assumed network byte order (Big Endian) while Ronald Rivest had assumed (without stating so in the RFC) that the implementor would use Little Endian byte order.</p>
|
<p>Define PC, what do you consider a PC?</p>
<p>I am currently typing this from an Linux distribution that is running on an arm 9 processor, which can be set into different endianness, but the default is big endian. Little endian is used by Intel, AMD and Via (x86 compatible).</p>
<p>Endian-ness won't go away any time soon, anytime you transmit anything over the network you have to make sure that it is in the right endianness, since the endian specified by Internet Protocol is actually big endian. </p>
<p>See the <a href="http://en.wikipedia.org/wiki/Endianness#Endianness_in_networking" rel="nofollow noreferrer">Wikipedia article on Endianness</a> for more information.</p>
| 11,358
|
<p>I am using VS2008 and Resharper. Resharper creates a directory _Resharper.ProjectName. These files provide no value for source control that I am aware of and cause issues when committing changes. How can I get SVN to ignore them? I am using TortoiseSVN as my interface for SVN.</p>
<p>EDIT: You guys are fast.</p>
|
<p><a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-ignore.html" rel="noreferrer">Here's a link to show the ignoring process in TortoiseSVN</a></p>
|
<p>SVN only controls what you put into it when creating your repository. Don't just import your entire project folder but import a "clean" folder BEFORE doing a build. After the build you get all the object files or your _Resharper folder etc. but they are not version controlled.</p>
<p>I forgot: the <pre>svn:ignore</pre> command is another possibility to tell SVN to exclude certain files. You can add this as a property to the version controlled folders, e.g. with TortoiseSVN. </p>
| 9,484
|
<p>Basically what I need is an automated way to update the product version number in WiX (3.0 with Votive etc), and then get that version number into an Inno Setup "bootstrapper"</p>
<p>I pretty much have the process mostly automated, however version numbers still need to be updated manually which obviously isn't ideal, but I couldn't find how to pass in values to Inno Setup at compile time (and how to reference them), and in the WiX project I need to know how to reference the version number of a different project in the same solution in Visual Studio 2008</p>
|
<p>No need to pass anything! You can simply let the InnoSetup Preprocessor read the version info straight from the binary's version resource, e.g.:</p>
<pre><code>#define AppName "My App"
#define SrcApp "MyApp.exe"
#define FileVerStr GetFileVersion(SrcApp)
#define StripBuild(str VerStr) Copy(VerStr, 1, RPos(".", VerStr)-1)
#define AppVerStr StripBuild(FileVerStr)
[Setup]
AppName={#AppName}
AppVersion={#AppVerStr}
AppVerName={#AppName} {#AppVerStr}
UninstallDisplayName={#AppName} {#AppVerStr}
VersionInfoVersion={#FileVerStr}
VersionInfoTextVersion={#AppVerStr}
OutputBaseFilename=MyApp-{#FileVerStr}-setup
</code></pre>
<p>Before version 5.4.1 (2011-02-09) ISPP was not included in the default InnoSetup package. You had to download the InnoSetup Quick Start Pack: <a href="http://www.jrsoftware.org/isdl.php#qsp" rel="noreferrer">http://www.jrsoftware.org/isdl.php#qsp</a> (thanks @Gwyn, for the update)</p>
|
<p>I found this for the inno setup section which looks like it would work:</p>
<p><a href="http://agiletracksoftware.com/blog.html?id=4" rel="nofollow noreferrer">http://agiletracksoftware.com/blog.html?id=4</a></p>
| 46,656
|
<p>In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).</p>
<p>Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?</p>
<p>Edit to add: Thanks for the great answers. But what if you're <em>not</em> using locks; what if you're using <a href="http://en.wikipedia.org/wiki/Barrier_(computer_science)" rel="noreferrer">barriers</a> for example? Or code that uses primitives such as <a href="http://en.wikipedia.org/wiki/Compare_and_swap" rel="noreferrer">compare-and-swap</a> to directly and atomically modify a shared variable...</p>
|
<p>As long as you are using locks to control access to the variable, you do not need volatile on it. In fact, if you're putting volatile on any variable you're probably already wrong.</p>
<p><a href="http://web.archive.org/web/20190219170904/https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/" rel="nofollow noreferrer">https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/</a></p>
|
<p>Some people obviously are assuming that the compiler treats the synchronization calls as memory barriers. "Casey" is assuming there is exactly one CPU.</p>
<p>If the sync primitives are external functions and the symbols in question are visible outside the compilation unit (global names, exported pointer, exported function that may modify them) then the compiler will treat them -- or any other external function call -- as a memory fence with respect to all externally visible objects.</p>
<p>Otherwise, you are on your own. And volatile may be the best tool available for making the compiler produce correct, fast code. It generally won't be portable though, when you need volatile and what it actually does for you depends a lot on the system and compiler.</p>
| 10,363
|
<p>What is the difference between using system() to execute a binary and using the combination of fork/execvp. </p>
<p>Is there any security/portablility/performance difference.</p>
|
<p>System also uses a <code>fork</code>/<code>exec</code>... combination. If you do <code>fork</code>/<code>exec</code> yourself you can execute parallel to your running process, while <code>system</code> is blocking (includes the <code>wait</code>).
Also <code>system</code> executes the command not direct, but via a shell (which makes problems with setuid bit) and <code>system</code> blocks/ignores certain signals (SIGINT, SIGCHILD, SIGQUIT).</p>
|
<p>system() works on Windows but fork() doesn't.</p>
<p>Unless you use a compatibility layer such as Cygwin, but even then a fork can be very expensive.</p>
| 39,179
|
<p>We have a software product that evolves at the rhythm of clients' needs and of a more general roadmap.</p>
<p>Because we are in a SCRUM project environment, it happens very regurlarly that a new feature makes its way to the product, and then we are confronted with the choice of:</p>
<ul>
<li>implementing this feature in an already released branch (not really the point of having a branch, then)</li>
<li>making a new branch - but then we have a branch every three weeks, and it is just not maintanable anymore</li>
</ul>
<p>Not releasing the new feature is not an option, the clients don't want to wait for a long term milestone plan to get the features they want, and it's not always faisible to move the feature in a client module - sometimes we need to change the core of the product...</p>
<p>Has anyone any feedback on a good practice given those kind of constraints ?</p>
|
<p>I'd suggest the following, which we use in my current environment: treat the unplanned feature like you would a security fix.</p>
<ul>
<li>Each planned release (e.g. 3.0, 3.1) gets its own version number, and its own tag in source code. After it's released, you don't touch it.</li>
<li>New features after a planned release go into the next planned release (e.g. 3.2)</li>
<li>If you must modify a released version of the code, it's an "unplanned release" and gets a patch version number (e.g. 3.1.1, 3.1.2). All changes:
<ul>
<li>Get implemented in a new branch based off of the latest patch to that release (e.g. 3.1.1 is created from 3.1.0, 3.1.2 is created from 3.1.1)</li>
<li>Are immediately merged to trunk, so they also get into the next planned release</li>
</ul></li>
<li>After implementing the unplanned feature, you turn the branch into a tag (aka don't touch it anymore) and go back to working in the trunk.</li>
</ul>
<p>This way, each unplanned feature gets a branch, but only long enough to make a new release and merge into trunk. You do almost all of your work in one place - trunk - and don't have lots of merging work to do.</p>
|
<p>A new branch like( 'new_feature_branch') is there to materialize a <a href="https://stackoverflow.com/questions/16142#114384">development effort</a> which is not compatible with the current branch (like 'release_branch')</p>
<p>So if your current release_branch is not very active, you can use it for the new feature (provided you define a label <em>before</em> developing this new feature, in case you need to cancel that process and go back to the state previous this new feature)</p>
<p>Making a new branch can be a good solution provided it is merged back on a regular basis (every 3 weeks) on the release branch, and then left out. It is especially recommended if you have some activities on the release_branch (like some hot bug-fixing). then the two efforts need to be kept separated.</p>
<p>Basically, it all comes down to your <a href="https://stackoverflow.com/questions/216212#216228">merge workflow</a> definition.</p>
<p>Leave comments if you want me to detail some options you feel I did not address enough in depth.</p>
| 31,207
|
<p>I am using http remoting in C# to talk between two applications.
Earlier when I was running both applications on a single machine/two machines, it was very slow.
We have a proxy server to connect to the internet. We set "Bypass proxy server for local addresses" in IE and now when I run both applications on one machine the communication is happening quite fast. (by a factor of 10 nearly)</p>
<p>But if I run each application on a different machine then it is still slow, like it was the case before setting the "Bypass proxy server..."</p>
<p>Any insight will be helpful.</p>
|
<p>What sort of data are you sending, and at what rate? And are you using lots of calls to remote (<code>MarshalByRefObject</code>) objects?</p>
<p>In reality, it is hard to fully control the data with remoting. Personally, I would recommend something message-based, for example WCF. This makes the interfaces between systems much more explicit and predictable.</p>
<p>If the proxy is being a pinch-point, you can still bypass this for remote addresses via proxycfg.exe</p>
|
<p>There aren't a lot of remote calls, as feared.
A single remote call takes 10 secs on different machines while it takes only 350ms when on a single machine. </p>
<p>when I run proxycfg.exe, it shows "Direct Access (no proxy server)"</p>
| 48,915
|
<p>I am writing a QT application and I need to embed a terminal (we say,xterm) within a QDialog, like some KDE application (see kdevelop/kate/...).</p>
<p>I've been trying with:
- QX11EmbedContainer placed into the QLayout of my QDialog
- QProcess for the program I want to excecute</p>
<p>I expect the QProcess running within the QX11EmbedContainer, but it does not work.</p>
<p>The problem is that I can't put the xterm into the QX11EmbedContainer, the only thing I obtain is an xterm window (unfortunately separated from my QDialog).
Does anybody got the same problem?</p>
|
<p>Sorry, I've tried your solution before posting oh this site and it does not work.
I've solved switching to kdelibs and using those imports and this code</p>
<pre><code>#include <kparts/part.h>
#include <assert.h>
#include <kde_terminal_interface.h>
#include <kpluginfactory.h>
#include <klibloader.h>
</code></pre>
<hr>
<pre><code>KLibFactory* factory = KLibLoader::self()->factory( "libkonsolepart" );
KParts::Part* p = static_cast<KParts::Part*>(factory->create( this,"tralala",
QStringList() << "dio") );
assert(p);
setCentralWidget( p->widget() );
TerminalInterface *t = qobject_cast<TerminalInterface*>(p);
t->showShellInDir( QDir::home().path() );
</code></pre>
|
<p>You need to pass the window ID of the container to the xterm.</p>
<p>If you look at the example in the Qt help for QX11EmbedContainer, it just passes the window id to the QProcess. Change this to</p>
<pre><code> QProcess process(&container);
QString executable(app.arguments()[1]);
QStringList arguments;
arguments << "-into" << QString::number(container.winId());
process.start(executable, arguments);
</code></pre>
<p>where "-into" has been added to the arguments. From the XTerm man page:</p>
<blockquote>
<p>-into windowId</p>
<p>Given an X window identifier (a decimal integer), xterm
will reparent its top-level shell
widget to that window. This is used
to embed xterm within other applications.</p>
</blockquote>
| 39,297
|
<p>Please help! I'm really at my wits' end.
My program is a little personal notes manager (google for "cintanotes").
On some computers (and of course I own none of them) it crashes with an unhandled exception just after start.
Nothing special about these computers could be said, except that they tend to have AMD CPUs.</p>
<p>Environment: Windows XP, Visual C++ 2005/2008, raw WinApi.</p>
<p>Here is what is certain about this "Heisenbug":</p>
<p>1) The crash happens only in the Release version.</p>
<p>2) The crash goes away as soon as I remove all GDI-related stuff.</p>
<p>3) BoundChecker has no complains.</p>
<p>4) Writing a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?</p>
<p>Any ideas would be greatly appreciated!</p>
<p><strong>UPDATE: I've managed to get the app debugged on a "faulty" PC. The results:</strong></p>
<p>"Unhandled exception at 0x0044a26a in CintaNotes.exe: 0xC000001D: Illegal Instruction."</p>
<p>and code breaks on</p>
<p>0044A26A cvtsi2sd xmm1,dword ptr [esp+14h] </p>
<p><strong>So it seems that the problem was in the "Code Generation/Enable Enhanced Instruction Set" compiler option. It was set to "/arch:SSE2" and was crashing on the machines that didn't support SSE2. I've set this option to "Not Set" and the bug is gone. Phew!</strong></p>
<p>Thank you all very much for help!!</p>
|
<p>So it doesnnt crash when configuration is DEBUG Configuration? There are many things different than a RELEASE configruation:
1.) Initialization of globals
2.) Actual machine Code generated etc..</p>
<p>So first step is find out what are exact settings for each parameter in the RELEASE mode as compared to the DEBUG mode.</p>
<p>-AD</p>
|
<p>Most heisenbugs / release-only bugs are due to either flow of control that depends on reads from uninitialised memory / stale pointers / past end of buffers, or race conditions, or both.</p>
<p>Try overriding your allocators so they zero out memory when allocating. Does the problem go away (or become more reproducible?)</p>
<blockquote>
<p>Writig a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?</p>
</blockquote>
<p>Stack overflow! ;)</p>
| 16,017
|
<p>I have a SUM array formula that has multiple nested IF statements, making it very inefficient. My formula spans over 500 rows, but here is a simple version of it:</p>
<pre><code>{=SUM(IF(IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17>0,
IF(A1:A5>A7:A11,A1:A5,A7:A11)-A13:A17,0))}
</code></pre>
<p>As you can see, the first half of the formula checks where the array is greater than zero, and if they are, it sums those in the second part of the formula.</p>
<p>You will notice that the same IF statement is repeated in there twice, which to me is inefficient, but is the only way I could get the correct answer. </p>
<p>The example data I have is as follows:</p>
<p><a href="http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example.jpg" rel="nofollow noreferrer">Sample Data in spreadsheet http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example.jpg</a>
The answer should be 350 in this instance using the formula I mentioned above.</p>
<p>If I tried to put in a MAX statement within the array, therefore removing the test to find where it was greater than zero, so it was like this: </p>
<pre><code>{=SUM(MAX(IF(B2:B6>B8:B12,B2:B6,B8:B12)-B14:B18,0))}
</code></pre>
<p>However, it seems like it only calculates the first row of data in each range, and it gave me the wrong answer of 70.</p>
<p>Does anyone know a away that I can reduce the size of the formula or make it more efficient by not needing to repeat an IF statement in there?</p>
<hr>
<p><strong>UPDATE</strong> </p>
<p>Jimmy</p>
<p>The MAX formula you suggested didnt actually work for all scenarios.</p>
<p>If i changed my sample data in rows 1 to 5 as below (showing that some of the numbers are greater than their respective cells in rows 7 to 11, while some of the numbers are lower)</p>
<p><a href="http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example2.jpg" rel="nofollow noreferrer">Sample Data in spreadsheet http://clients.estatemaster.net/SecureClientSite/Download/TempFiles/example2.jpg</a></p>
<p>The correct answer im trying to achive is 310, however you suggested MAX formula gives an incorrect answer of 275.</p>
<p>Im guessing the formula needs to be an array function to give the correct answer. </p>
<p>Any other suggestions?</p>
|
<pre><code>=MAX( MAX( sum(A1:A5), sum(A7:A11) ) - sum(A13:A17), 0)
</code></pre>
|
<p>You may want to look into the VB Macro editor. In the Tools Menu, go to Macros and select Visual basic Editor. This gives a whole programming environment where you can write your own function.</p>
<p>VB is a simple programming language and google has all the guidebooks you need.</p>
<p>There, you can write a function like MySum() and have it do whatever math you really need it to, in a clear way written by yourself. </p>
<p>I pulled this off google, and it looks like a good guide to setting this all up.
<a href="http://office.microsoft.com/en-us/excel/HA011117011033.aspx" rel="nofollow noreferrer">http://office.microsoft.com/en-us/excel/HA011117011033.aspx</a></p>
| 40,790
|
<p>I am designing an part for my car. It is a panel for the rear door. I want to add it some cases for tools, but before going on, could you tell me:</p>
<p>It is a large flat panel, around 100cm by 35cm.</p>
<p><strong>Is it going to be suitable for printing in that ABS material? Is it too big?</strong></p>
<p><a href="https://i.stack.imgur.com/wqGB7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wqGB7.jpg" alt="enter image description here"></a></p>
|
<p>ABS would be fine, as a material, for the application.</p>
<p>The problem, given the scale, would be the printing device used. I would suggest that you have the piece cut to spec for you using a polycarbonate. </p>
<p>If you have access to a workshop you could do so yourself if you set up proper fencing using a larger sized bandsaw(with a very fine toothed blade), had rollers to help support the size of your piece(as it would not fit on the tool's platform) and likely need a second set of hands to help control the outfeed. You would also need to drill access for the cut out then cut the perimetre.</p>
<p>You could also consider printing(ABS) in smaller sections then fusing each section together edge to edge(solvent welding of ABS is very strong and permanent), if you were really dead set on using a typical 3D printer for this. It would, in theory, be possible, but it would be very tedious. The adhesives, and cleaner, would be available from any plumbing supply and/or (home depot, lowes, walmart et al.). If you go this route be sure to have ample ventilation and plan your work space well in advance. I would not recommend this option but it is "possible".</p>
<p>Given the scale of the piece though, and for sake of accuracy, going to a shop with CNC equipment and using polycarbonate would be your best bet.</p>
|
<p>It is a huge part that would not fit in most 3D printers, do you have access to a 3D printer this big? Even if it does fit it will take a long time to print.</p>
<p>Considering it's a simple flat shape, maybe laser cut / CNC acrylic or wood would be better, as you will have a stronger part, and most likely faster and cheaper.</p>
| 375
|
<p>I am sending the echo to mail function via PHP from variable that includes HTML code. The strange thing is, that this </p>
<pre><code><����}im�
</code></pre>
<p>shows up AFTER the string.. but I do not manipulate with it anymore. The charset of mail function (the attachment) is same as charset of HTML code.</p>
|
<p>Encoding problem, maybe it tries to display binary code?</p>
<p>You should use htmlentities if ou want to display HTML</p>
<blockquote>
<p>// Outputs: A 'quote' is</p>
<p><b>bold</b> echo</p>
<p>htmlentities($str);</p>
</blockquote>
|
<p>Those characters are probably "junk" data in your string. Depending on where the string is coming from these characters could be: extra TCP data in the socket after the HTML page, or extra data in the file after the HTML page, or someone else actually put these characters in their HTML page (perhaps their file was accidentally corrupted, or for some other reason).</p>
| 38,483
|
<p>I know it happens sometime before Load, but during what event exactly?</p>
|
<p>It's loaded into memory between init and load. See t<a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="noreferrer">his article</a> for a full break down of the page lifecycle.</p>
|
<p>The Viewstate is actually loaded in the OnPreLoad event of the page,Just after the Page_InitComplete.</p>
| 12,030
|
<p>In C++ program, I am trying to #import TLB of .NET out-of-proc server.</p>
<p>I get errors like:</p>
<blockquote>
<p>z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'</p>
<p>z:\server.tlh(111) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'</p>
<p>z:\server.tli(74) : error C2433: '_TypePtr' : 'inline' not permitted on data declarations</p>
<p>z:\server.tli(74) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p>
<p>z:\server.tli(74) : fatal error C1004: unexpected end of file found</p>
</blockquote>
<p>The TLH looks like:</p>
<pre><code>_bstr_t GetToString();
VARIANT_BOOL Equals (const _variant_t & obj);
long GetHashCode();
_TypePtr GetType();
long Open();
</code></pre>
<p>I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.</p>
<p>Some google research indicates I could <code>#import mscorlib.tlb</code> (or put it in path), but I can't get that to compile either.</p>
<p>Any tips?</p>
|
<p>Added no_namespace and raw_interfaces_only to my #import:</p>
<pre><code>#import "server.tlb" no_namespace named_guids
</code></pre>
<p>Also using TLBEXP.EXE instead of REGASM.EXE seems to help this issue.</p>
|
<p>Also, make sure your C# class doesn't have this attribute:</p>
<p>[ClassInterface(ClassInterfaceType.AutoDual)] <-- Seems to cause errors in C++ with _TypePtr</p>
| 3,382
|
<p>I am curious about the algorithm/principles behind the estimates that the slicing softwares provide. Is there a standard technique behind this and how accurate is it ?</p>
|
<p>Much of the software used in 3D printing is open-source, and so are some slicers. Cura, for instance, does (or did, this source code is from an older branch) its print time estimation in <a href="https://github.com/smorloc/Curation/blob/master/Cura/util/gcodeInterpreter.py" rel="noreferrer">gcodeInterpreter.py</a>.</p>
<p>The relevant portion of the source code is (simplified and with many lines removed for clarity):</p>
<pre><code> totalMoveTimeMinute = 0.0
pos = util3d.Vector3()
for line in gcodeFile:
G = self.getCodeInt(line, 'G')
if G is not None:
if G == 0 or G == 1: #Move
x = self.getCodeFloat(line, 'X')
y = self.getCodeFloat(line, 'Y')
z = self.getCodeFloat(line, 'Z')
e = self.getCodeFloat(line, 'E')
f = self.getCodeFloat(line, 'F')
oldPos = pos.copy()
pos.x = x
pos.y = y
pos.z = z
feedrate = f
currentE = e
totalMoveTimeMinute += (oldPos - pos).vsize() / feedRate
</code></pre>
<p>As you can see, (this version of) Cura simply:</p>
<ul>
<li><p>Loops over all the G-code instructions,</p></li>
<li><p>Computes the length of each move (in X/Y/Z) and divides that by the feedrate to get the time that move will take,</p></li>
<li><p>Sums this up over all the moves.</p></li>
</ul>
<p>and does not take into account:</p>
<ul>
<li><p>Acceleration or deceleration. It assumes the printer is always operating at the maximum feedrate,</p></li>
<li><p>The length of filament extruded. The feedrate is the speed for the move in (X,Y,Z,E), but Cura only looks at (X,Y,Z).</p></li>
<li><p>The time it takes to heat up the print bed/hotend or homing/autoleveling,</p></li>
<li><p>The effects of the printer slowing down if moves can not be read (from USB/SD-card) sufficiently fast (though this would be rather hard to include in any estimate).</p></li>
</ul>
<p>The accuracy of this estimate can be arbitrarily bad if the feedrate is set to some unrealistic value.</p>
<p>Newer versions of Cura use a much more advanced time estimate method, and it can be found in <a href="https://github.com/Ultimaker/CuraEngine/blob/master/src/timeEstimate.cpp" rel="noreferrer">timeEstimate.cpp</a>. It is much more complicated, and actually takes jerk/acceleration/deceleration into account. It is much more accurate.</p>
<p>We know <em>exactly</em> how 3D (open source) 3D printer firmwares work, so estimating print time is as easy as simulating execution of the G-code by your given firmware. There is no reason you can't get a really good estimation (if you take into account all of the intricacies of your given firmware's acceleration/deceleration techniques) but writing the code for it is rather involved.</p>
|
<p>Generally speaking, the typical algorithm takes into account the slicer's speed settings for specific features of the build, such as infill, perimeters, top/bottom layers, etc. The distance traveled by the nozzle at a specific speed for each feature is also part of the equations involved. There are some rather vague portions of the nozzle movement based on acceleration and other factors which makes the calculations less accurate.</p>
<blockquote>
<p>How accurate is it?</p>
</blockquote>
<p>Not too accurate. My experience with three different slicers is that it's never been within better than ten percent. I believe the various combinations of features of a build are not going to be identical from one model to the next, preventing even a ballpark figure to be created from previous builds.</p>
| 664
|
<p>I have stfw but I cannot find a simple / standalone way to create a webservice client in java.</p>
<p>Does anyone have a link/sample into this?</p>
|
<p>How about using <a href="http://ws.apache.org/axis2/" rel="nofollow noreferrer">Axis2</a>?</p>
<p>Just follow the <a href="http://ws.apache.org/axis2/1_4_1/quickstartguide.html" rel="nofollow noreferrer">quickstart guide</a> and you should be on your way.</p>
<p>Here is another more descriptive <a href="http://ws.apache.org/axis2/1_0/userguide3.html#Writing_Web_Service_Clients_using_Code_Generation_with_Data_Binding_Support" rel="nofollow noreferrer">guide</a></p>
|
<p>I presume you're referring to a SOAP web service? For a RESTful web service in which requests are submitted via HTTP GET, you really don't need anything more than a web browser.</p>
| 25,695
|
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p>
<pre><code>cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
</code></pre>
<p>How can I condense it? </p>
|
<p>Not totally sure this is what you want, but..</p>
<pre><code>cleaned = stringwithslashes.decode('string_escape')
</code></pre>
|
<p>Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.</p>
<p>Regular expressions to the rescue (code not tested):</p>
<pre><code>p = re.compile( '\\(\\\S)')
p.sub('\1',escapedstring)
</code></pre>
<p>In theory that takes anything of the form \\(not whitespace) and returns \(same char)</p>
<p>edit: Upon further inspection, Python regular expressions are broken as all hell;</p>
<pre><code>>>> escapedstring
'This is a \\n\\n\\n test'
>>> p = re.compile( r'\\(\S)' )
>>> p.sub(r"\1",escapedstring)
'This is a nnn test'
>>> p.sub(r"\\1",escapedstring)
'This is a \\1\\1\\1 test'
>>> p.sub(r"\\\1",escapedstring)
'This is a \\n\\n\\n test'
>>> p.sub(r"\(\1)",escapedstring)
'This is a \\(n)\\(n)\\(n) test'
</code></pre>
<p>In conclusion, what the hell, Python.</p>
| 3,437
|
<p>I understand that we can use SMS Sender in command line mode. But i been getting this error same as this article <a href="http://www.oreillynet.com/pub/a/wireless/2003/10/10/sms.html" rel="nofollow noreferrer">http://www.oreillynet.com/pub/a/wireless/2003/10/10/sms.html</a></p>
<p>The smssender.exe will use the last device that was successfully used to send messages in the Windows version of SMS Sender. But I tried it many times, and smssender.exe always complains that no last device was used. </p>
<p>Anyone have any idea about this?</p>
|
<p>Not a direct answer to your question, but might help..</p>
<p>Take a look at some of the sms gateway services out there.
I've used Kapow with a lot of success.</p>
<p><a href="http://www.kapow.co.uk/" rel="nofollow noreferrer">http://www.kapow.co.uk/</a></p>
<p>It's a UK company, but I'm sure you find one in your country.</p>
<p>Most services provide a nice easy to use web api and give you good reporting on delivery, etc. They usually don't come for free, but are comparable to your standard mobile rates for low volume and pretty cheap for higher volumes.</p>
|
<p>Just discovered the answer to your question nad it is really easy.... just use the first time the GUI version of SMSSENDER.EXE and in the Options menu, select enable logging... after thar you can start using the command line with success.</p>
| 23,036
|
<p>I am being sent an xml feed via multicast, but I don't know the multicast group address. Can I just use localhost instead?</p>
<pre><code>Socket socket =
new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
IPEndPoint ip = new IPEndPoint(IPAddress.Any,8888);
socket.Bind(ip);
socket.SetSocketOption
(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("127.0.0.1"),IPAddress.Any));
byte[] data = new byte[1024];
int length = socket.Receive(data);
...
</code></pre>
|
<p>No.</p>
<p>You (your client) needs to join the multicast group, you'll AddMembership to the multicast group IP, then connect.</p>
<p>Otherwise you won't be able to receive the multicast feed. Your code would work with a UDP broadcast though.</p>
|
<p>Unlike unicast, you do need to know the group address for multicast.</p>
| 37,196
|
<p>How can I deploy an iPhone application from Xcode to real iPhone device without having a US$99 Apple certificate?</p>
|
<p>It sounds like the application isn't signed. Download ldid from Cydia and then use it like so: <code>ldid -S /Applications/AccelerometerGraph.app/AccelerometerGraph</code></p>
<p>Also be sure that the binary is marked as executable: <code>chmod +x /Applications/AccelerometerGraph.app/AccelerometerGraph</code></p>
|
<p>There is no workaround. You can only ad hoc deploy apps if they are registered with your device. This prevents you from building your own app store.. </p>
| 30,583
|
<p>How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?</p>
|
<p>This guy seems to have your answer.</p>
<blockquote>
<p><a href="https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net" rel="noreferrer">https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net</a></p>
</blockquote>
<p>And in case the blog ever goes away or breaks the url, here's the github link:</p>
<blockquote>
<p><a href="https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs" rel="noreferrer">https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs</a></p>
</blockquote>
<hr>
<p>Usage of the Crc32 class from the blog post:</p>
<pre><code>Crc32 crc32 = new Crc32();
String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash);
</code></pre>
|
<p>Using the logic from the previous answer, this was my take:</p>
<pre><code>public class CRC32
{
private readonly uint[] ChecksumTable;
private readonly uint Polynomial = 0xEDB88320;
public CRC32()
{
ChecksumTable = new uint[0x100];
for (uint index = 0; index < 0x100; ++index)
{
uint item = index;
for (int bit = 0; bit < 8; ++bit)
item = ((item & 1) != 0) ? (Polynomial ^ (item >> 1)) : (item >> 1);
ChecksumTable[index] = item;
}
}
public byte[] ComputeHash(Stream stream)
{
uint result = 0xFFFFFFFF;
int current;
while ((current = stream.ReadByte()) != -1)
result = ChecksumTable[(result & 0xFF) ^ (byte)current] ^ (result >> 8);
byte[] hash = BitConverter.GetBytes(~result);
Array.Reverse(hash);
return hash;
}
public byte[] ComputeHash(byte[] data)
{
using (MemoryStream stream = new MemoryStream(data))
return ComputeHash(stream);
}
}
</code></pre>
| 2,960
|
<p>We are using classic asp to call a C# dll and in the C# dll we are using System.Drawing.Printing.PrinterSettings.InstalledPrinters to get a list of availabe printers. If the printers are not shared they will not show up when a user trys to print. The Local System account can see and print to them from a VB6 dll and Administrators can print just fine from the C# dll as you might expect. Is there some sort of permissions we need to grant the user so these printers will be available?</p>
|
<p>As I recall, running a website uses the Network User account, which may not have permission to view local printers.</p>
<p>There was a page on MSDN that said how you can impersonate another user that might have access to the printers, but I've not been able to find it.</p>
<p>Edit: I posted too soon. <a href="http://support.microsoft.com/kb/306158" rel="nofollow noreferrer">Here's the page</a>.</p>
<p>HTH</p>
|
<p>As I recall, running a website uses the Network User account, which may not have permission to view local printers.</p>
<p>There was a page on MSDN that said how you can impersonate another user that might have access to the printers, but I've not been able to find it.</p>
<p>Edit: I posted too soon. <a href="http://support.microsoft.com/kb/306158" rel="nofollow noreferrer">Here's the page</a>.</p>
<p>HTH</p>
| 3,554
|
<p>Came across this error today. Wondering if anyone can tell me what it means:</p>
<blockquote>
<blockquote>
<p>Cannot sort a row of size 9522, which is greater than the allowable maximum of 8094.</p>
</blockquote>
</blockquote>
<p>Is that 8094 bytes? Characters? Fields? Is this a problem joining multiple tables that are exceeding some limit?</p>
|
<p>In SQL 2000, the row limit is 8K bytes, which is the same size as a page in memory. </p>
<p>[Edit]</p>
<p>In 2005, the page size is the same (8K), but the database uses pointers on the row in the page to point to other pages that contain larger fields. This allows 2005 to overcome the 8K row size limitation.</p>
|
<p>That used to be a problem in SQL 2000, but I thought that was fixed in 2005.</p>
| 3,746
|
<p>I've just noticed this Meta post, <a href="https://meta.stackexchange.com/q/364007/280335">Testing three-vote close and reopen on 13 network sites</a> and I wondered whether we should employ it here, and what do other people think?</p>
<p>We are a smallish site, with a smallish number of active users (although it isn't <em>that</em> small, and is slowly growing over time, it should be noted). We don't have a problem with review queues building up <em>except</em> with the close votes. Some questions do seem to hang around for a while in the close queue.</p>
<p>The problem with the close vote review queue requiring 5 votes when there is a <em>limited</em> number of active reviewers (where two of which are moderators) is this: If a moderator votes, then the question is automatically closed, even if there aren't 5 votes - if a moderator casts the first vote to close then the question is closed straight away, without waiting for another four votes - so the vote is not democratic, but instead, dictatorial in nature. As such, moderators tend to not vote, unless the question blatantly needs closing (i.e. spam, vulgarity, etc.).</p>
<p>There are ways around this problem:</p>
<ul>
<li>sock puppets (moderators have a fake account to cast votes only in the review queue), or;</li>
<li>waiting for four votes and then a moderator casting the fifth vote (or waiting for three votes and then moderators agreeing (behind the scenes) to cast the final two votes, etc.)</li>
</ul>
<p>However, these aren't ideal, and just shortening the queue might make things better. This need not be a permanent change, I guess, so if this site, for some reason, eventually exploded in popularity, the review queue <em>could</em> go back to five votes (but I'm not 100 % sure about that, see the SE.Meta post above to check).</p>
<p>So... should SE.3DP jump on the "three votes to close" train? Or are things OK as they are? What do other users think? <em>Please</em> leave a comment or answer.</p>
<p>To make things super simple, and if you don't have time to write a comment or answer, you can just vote on the <strong>Yes</strong> answer or the <strong>No</strong> answer.</p>
<h3>End of voting date</h3>
<p>To give this vote an end point, and not make it so opened-ended, I guess we should tally a "final" vote on the 1<sup>st</sup> July 2021 - which is May 6 (trial start date) plus 45 days (length of trial) plus a little bit more. As we can't join the trial halfway through, there isn't much point to tallying up the votes before that.</p>
<p>At that point Catija will be sent the results.</p>
|
<h2>Yes, we should have a <em>three</em> vote close question review queue</h2>
|
<h2>No, we should stay with the <em>five</em> vote close question review queue</h2>
| 79
|
<p>Using MVC with an observer pattern, if a user action requires polling a device (such as a camera) for data, should the polling be done in the Controller and the result passed off the Model or should a request be sent to the Model and the Model itself performs the polling.</p>
<p>This question is my attempt to reconcile everything I am reading that touts the "skinny Controllers" maxim with my gut intuition that the Model should only be acting on data not acquiring it.</p>
<p>(Note: This question <em>might</em> be subjective. I'm not entirely sure that there is a one-true-answer to this question. If not, feel free to retag as I will be very interested to hear opinions on the subject.)</p>
|
<p>The syntax you're trying to use is new in <strong><a href="http://effbot.org/zone/element-xpath.htm" rel="noreferrer">ElementTree 1.3</a></strong>.</p>
<p>Such version is shipped with <strong>Python 2.7</strong> or higher.
If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.</p>
|
<p>There are several problems in this code.</p>
<ol>
<li><p>Python's buildin ElementTree (ET for short) has no real XPATH support; only a limited subset By example, it doesn't support <em>find-from-root</em> expressions like <code>//target</code>. </p>
<p>Notice: the <a href="http://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax" rel="noreferrer">documentation</a>
mentions "<strong>//</strong>", but only for children: So an expression as
<code>.//target</code> is valid; <code>//...</code> is not!</p>
<p>There is an alternative implementation: <a href="http://lxml.de" rel="noreferrer"><strong>lxml</strong></a> which is more rich. It's seams that documentation is used, for the build-in code. That does not match/work.</p></li>
<li><p>The <code>@name</code> notation selects xml-<strong>attributes</strong>; the <code>key=value</code> expression within an xml-tag.</p>
<p>So that name-value has to be 1 or 2 to select something in the given document. Or, one can search for targets with a child <strong>element</strong> <em>'a'</em>: <code>target[a]</code> (no @).</p></li>
</ol>
<p>For the given document, parsed with the build-in ElementTree (v1.3) to root, the following code is correct and working:</p>
<ul>
<li><code>root.findall(".//target")</code> Find both targets</li>
<li><code>root.findall(".//target/a")</code> Find two a-element</li>
<li><code>root.findall(".//target[a]")</code> This finds both target-element again, as both have an a-element</li>
<li><code>root.findall(".//target[@name='1']")</code> Find only the <em>first</em> target. Notice the quotes around 1 are needed; else a SyntaxError is raised</li>
<li><code>root.findall(".//target[a][@name='1']")</code> Also valid; to find that target</li>
<li><code>root.findall(".//target[@name='1']/a")</code> Finds only one a-element; ...</li>
</ul>
| 27,432
|
<p>Anyone know of some tutorial material for how to use Interface Builder for iPhone development? I can find sample projects and stuff and that's extremely helpful, but they do not reveal how things where setup in Interface Builder.</p>
|
<p>The Pragmatic Programmers have some <a href="http://www.pragprog.com/screencasts/v-bdiphone/writing-your-first-iphone-application" rel="nofollow noreferrer">screencasts</a> on building an iphone application. I haven't watched those, but I have watched some of their other videos and they were pretty good.</p>
<p>They've also got a free getting started with Xcode and Interface Builder episode, which may be what your looking for.</p>
|
<p>You can actually get a lot out of these screen-casts which are free as of now:
<a href="http://www.cocoacast.com/?q=blog/1" rel="nofollow noreferrer">http://www.cocoacast.com/?q=blog/1</a></p>
<p>Note that they are very 'connected' to the Aaron Hillegass book on Mac programming (which is also a great resource). Some of them show him using IB (but of course not all). The book is more focused on Mac then iPhone, but if you're just trying to get going it's a great point of departure. I'm working on my first iPhone project and had never programmed with Objective C, XCode IDE and Interface Builder. I read the first 200 pages and used Apple's docs after that. Now it's been several months and I found the above screen-cast and wished I had that getting started! Good luck</p>
| 46,499
|
<p>I have written something that uses the following includes:</p>
<pre><code>#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <commctrl.h>
</code></pre>
<p>This code works fine on 2 machines with the Platform SDK installed, but doesn't run (neither debug nor release versions) on clean installs of windows (VMs of course). It dies with the quite familiar:</p>
<pre><code>---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
---------------------------
C:\Documents and Settings\Someone\Desktop\DesktopRearranger.exe
This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
---------------------------
OK
---------------------------
</code></pre>
<p>How can I make it run on clean installs? Which dll is it using which it can't find? My bet is on commctrl, but can someone enlighten me on why it's isn't with every windows?</p>
<p>Further more, if anyone has tips on how to debug such a thing, as my CPP is already rusty, as it seems :)</p>
<p>Edit - What worked for me is downloading the Redistributable for Visual Studio 2008. I don't think it's a good solution - downloading a 2MB file and an install to run a simple 11K tool. I think I'll change the code to use LoadLibrary to get the 2 or 3 functions I need from comctl32.dll. Thanks everyone :)</p>
|
<p>Use Dependency Walker. Download and install from <a href="http://www.dependencywalker.com/" rel="noreferrer">http://www.dependencywalker.com/</a> (just unzip to install). Then load up your executable. The tool will highlight which DLL is missing. Then you can find the redistributable pack which you need to ship with your executable.</p>
<p>If you use VS2005, most cases will be covered by <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en" rel="noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyId=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en</a> which includes everything needed to run EXEs created with VS2005. Using depends.exe you may find a more lightweight solution, though.</p>
|
<p>I suspect it is trying to find a version of common controls that isn't installed. You may need a manifest file to map the version of common controls to your target operating system. Also, you may need to make sure you have installed the same VC runtimes that you were linked to.</p>
<p><a href="http://blogs.msdn.com/cjacks/archive/2006/08/21/711240.aspx" rel="nofollow noreferrer">Chris Jackson blog</a></p>
<p>EDIT: A little searching and I've confirmed (mostly) that it is the version of your VC++ runtimes that is to blame. You need to distribute the versions that you built with. The platform SDK usually includes a merge module of these for that purpose, but there is often a VCRedist.exe for them as well. Try looking Microsoft's downloads.</p>
<p><a href="http://support.microsoft.com/kb/948854" rel="nofollow noreferrer">KB94885</a></p>
| 18,765
|
<ol>
<li>Why is operator '&' defined for bool?, and operator '&&' is not? </li>
<li>How exactly does this 1) bool? & bool? and 2) bool? and bool work?</li>
</ol>
<p>Any other "interesting" operator semantics on Nullable? Any overloaded operators for generic T?</p>
|
<p>Operators on <code>Nullable<T></code> are "lifted" operators. What this means is: if T has the operator, T? will have the "lifted" counterpart.</p>
<p>&& and || aren't really operators in the same sense as & and | - for example, they can't be overloaded - from the ECMA spec 14.2.2 Operator overloading:</p>
<blockquote>
<p>The overloadable binary operators are:
+ - * / % & | ^ << >> == != > < >= <= Only the operators listed above can be
overloaded. In particular, it is not
possible to overload member access,
method invocation, or the =, &&, ||,
??, ?:, checked, unchecked, new,
typeof, as, and is operators.</p>
</blockquote>
<p>Likewise, from the ECMA spec, 14.2.7 Lifted operators, the lifted operators are:</p>
<blockquote>
<p>For the unary operators
+ ++ - -- ! ~</p>
<p>For the binary operators
+ - * / % & | ^ << >></p>
<p>For the equality operators
== !=</p>
<p>For the relational operators < > <= >=</p>
</blockquote>
<p>So basically, the short-circuiting operators aren't defined as lifted operators.</p>
<p>[edit: added crib sheet]</p>
<ul>
<li><p>Lifted operator: a compiler provided operator on <code>Nullable<T></code>, based on the operators of T - for example: the <code>int</code> "+" operator gets "lifted" onto <code>int?</code>, defined as:</p>
<p>(int? x, int? y) => (x.HasValue && y.HasValue) ? (x.Value + y.Value) : (int?) null;</p></li>
<li><p>Operator overloading: the act of providing a custom operator implementation for a given type; for example <code>decimal</code> and <code>DateTime</code> provide various operator overloads</p></li>
<li><p>Short-circuiting: the normal behavior of <code>&&</code> and <code>||</code> (in many languages, including C++ and C#) - i.e. the second operand <em>might not be evaluated</em> - i.e.</p>
<p>(expression1, expression2) => expression1() ? expression2() : false;</p></li>
</ul>
<p>Or perhaps a simpler example:</p>
<pre><code>bool someFlag = Method1() && Method2();
</code></pre>
<p>if <code>Method1()</code> returns false, then <code>Method2()</code> isn't executed (since the compiler already knows that the overall answer is false). This is important if <code>Method2()</code> has side-effects, since as saving to the database...</p>
|
<p>-- In addition, the logical && operator along with the || operator cannot be overloaded.</p>
<p>2) The reason that the bitwise operator works is because it operates on single bits, which is a simple 1 or 0. This is what boolean operators essentially are, true and false, 1 and 0.</p>
| 38,952
|
<p>Is there any way to add iCal event to the iPhone Calendar from the custom App?</p>
|
<p>Based on <a href="https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html#//apple_ref/doc/uid/TP40004775-SW1" rel="noreferrer">Apple Documentation</a>, this has changed a bit as of iOS 6.0.</p>
<p>1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block.</p>
<p>2) You need to commit your event now or pass the "commit" param to your save/remove call</p>
<p>Everything else stays the same...</p>
<p>Add the EventKit framework and <code>#import <EventKit/EventKit.h></code> to your code.</p>
<p>In my example, I have a NSString *savedEventId instance property.</p>
<p>To add an event:</p>
<pre><code> EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = @"Event Title";
event.startDate = [NSDate date]; //today
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later
}];
</code></pre>
<p>Remove the event:</p>
<pre><code> EKEventStore* store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];
if (eventToRemove) {
NSError* error = nil;
[store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
}
}];
</code></pre>
<p>This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is</p>
<p><em>Swift version</em></p>
<p>You need to import the EventKit framework</p>
<pre><code>import EventKit
</code></pre>
<p>Add event</p>
<pre><code>let store = EKEventStore()
store.requestAccessToEntityType(.Event) {(granted, error) in
if !granted { return }
var event = EKEvent(eventStore: store)
event.title = "Event Title"
event.startDate = NSDate() //today
event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting
event.calendar = store.defaultCalendarForNewEvents
do {
try store.saveEvent(event, span: .ThisEvent, commit: true)
self.savedEventId = event.eventIdentifier //save event id to access this particular event later
} catch {
// Display error to user
}
}
</code></pre>
<p>Remove event</p>
<pre><code>let store = EKEventStore()
store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in
if !granted { return }
let eventToRemove = store.eventWithIdentifier(self.savedEventId)
if eventToRemove != nil {
do {
try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)
} catch {
// Display error to user
}
}
}
</code></pre>
|
<p>The Google idea is a nice one, but has problems.</p>
<p>I can successfully open a Google calendar event screen - but only on the main desktop version, and it doesn't display properly on iPhone Safari. The Google mobile calendar, which does display properly on Safari, doesn't seem to work with the API to add events.</p>
<p>For the moment, I can't see a good way out of this one.</p>
| 30,560
|
<p>SQL Experts,</p>
<p>Is there an efficient way to group runs of data together using SQL?<br>
Or is it going to be more efficient to process the data in code. </p>
<p>For example if I have the following data:</p>
<pre><code>ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith
</code></pre>
<p>I need to display this:</p>
<pre><code>Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
John Smith
</code></pre>
<p>@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.</p>
|
<p>Try this:</p>
<pre><code>select n.name,
(select count(*)
from myTable n1
where n1.name = n.name and n1.id >= n.id and (n1.id <=
(
select isnull(min(nn.id), (select max(id) + 1 from myTable))
from myTable nn
where nn.id > n.id and nn.name <> n.name
)
))
from myTable n
where not exists (
select 1
from myTable n3
where n3.name = n.name and n3.id < n.id and n3.id > (
select isnull(max(n4.id), (select min(id) - 1 from myTable))
from myTable n4
where n4.id < n.id and n4.name <> n.name
)
)
</code></pre>
<p>I think that'll do what you want. Bit of a kludge though.</p>
<p>Phew! After a few edits I think I have all the edge cases sorted out.</p>
|
<p>For this particular case, all you need to do is group by the name and ask for the count, like this:</p>
<pre><code>select Name, count(*)
from MyTable
group by Name
</code></pre>
<p>That'll get you the count for each name as a second column.</p>
<p>You can get it all as one column by concatenating like this:</p>
<pre><code>select Name + ' (' + cast(count(*) as varchar) + ')'
from MyTable
group by Name
</code></pre>
| 4,166
|
<p>I need a thread to wait until a file is exist or created.
I have the following code so far:</p>
<pre><code>while(!receivedDataFile.isFileExists("receiveddata.txt"))
{
try {
Thead.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
}
</code></pre>
<p>When I run it, the following exception appears, and the thread ends:</p>
<pre><code>java.lang.InterruptedException: sleep interrupted
</code></pre>
|
<p>You should find out which thread interrupts that thread. Threads don’t do that on their own.</p>
|
<p>If all you want is a notification when a file is created, AND you can (and willing) to go native (JNI) AND you want only win32 support, you could use the code <a href="http://www2.hawaii.edu/~qzhang/FileSystemWatcher/index.html" rel="nofollow noreferrer" title="File system watcher using JNI (native)">here</a>.</p>
| 45,911
|
<p>How do you set up your .NET development tree? I use a structure like this:</p>
<pre><code>-projectname
--config (where I put the configuration files)
--doc (where I put all the document concerning the project: e-mails, documentation)
--tools (all the tools I use: Nunit, Moq)
--lib (all the libraries used by the solution: ninject or autofac)
--src
---app (sourcefiles)
---test (unittests)
solutionfile.sln
build.csproj
</code></pre>
<p>The sign "-" marks directories.</p>
<p>I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries. </p>
<p>Any thoughts on this?</p>
|
<p>We use a very similar layout as covered in JP Boodhoo's blog post titled <a href="http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/" rel="nofollow noreferrer">Directory Structure For Projects</a>.</p>
|
<p>At my place of work we have multiple projects, where each project gets its own sub-directory, like so:
-proj1<br>
--proj1.csproj<br>
-proj2<br>
--proj2.csproj<br>
-proj3<br>
--proj3.csproj<br>
solutionfile.sln </p>
<p>The rest of your setup looks okay, but I think you should figure out how you would incorporate multiple projects, for example a shared source library between multiple solutions.</p>
| 9,714
|
<p>I am currently plowing my way through <a href="http://www-128.ibm.com/developerworks/edu/os-dw-os-php-cake1.html" rel="nofollow noreferrer">IBM's tutorial on CakePHP</a></p>
<p>At one point I run into this snippet of code:</p>
<pre><code><?php
class Dealer extends AppModel {
var $name = 'Dealer';
var $hasMany = array (
'Product' => array(
'className' => 'Product',
'conditions'=>, // is this allowed?
'order'=>, // same thing here
'foreignKey'=>'dealer_id'
)
);
}
?>
</code></pre>
<p>When I run it I get the following error-message: "Parse error: syntax error, unexpected ',' in /Applications/MAMP/htdocs/cakephp/app/models/product.php on line 7"</p>
<p>I'm a n00b at PHP so my question is: is it allowed to make an array with keys without assigned values? Has anybody played around with this tut and know what is up?</p>
|
<p>Assign the value null instead of leaving anything out. The <a href="http://php.net/isset" rel="noreferrer">manual says</a></p>
<blockquote>
<p>isset() will return FALSE if testing a variable that has been set to NULL</p>
</blockquote>
<pre><code><?php
class Dealer extends AppModel
{
var $name = 'Dealer';
var $hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null,
'order'=> null,
'foreignKey'=>'dealer_id')
);
}
?>
</code></pre>
<p>This works fine.</p>
|
<p>It is legal, though as far as I'm aware, you have to explicitly say it's 'empty' by assigning null to it,</p>
<pre><code>$hasMany = array ('Product' => array(
'className' => 'Product',
'conditions'=> null, // is this allowed?
'order'=> null, // same thing here
'foreignKey'=>'dealer_id'));
</code></pre>
<p>The example you've given sounds very wrong, and probably shouldn't work, as it isn't.</p>
| 20,124
|
<p>I need to serialize the System.Configuration.SettingsProperty and System.Configuration.SettingsPropertyValue class object through WCF.</p>
|
<p>Using your own class is reasonable option. You can also use the VS designer settings if you want. </p>
<p>The VS designer keeps property settings in the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.applicationsettingsbase.aspx" rel="nofollow noreferrer">ApplicationSettingsBase</a> class. By default, these properties are serialized/deserialized into a per user XML file. Because there is no user context for a WCF service, this will not work. You can override this behavior by using a custom <a href="http://msdn.microsoft.com/en-us/library/system.configuration.settingsprovider.aspx" rel="nofollow noreferrer">SettingsProvider</a> which makes it pretty easy to keep the properties where ever you want. Just add the <code>SettingsProvider</code> attribute to the VS generated <code>Settings</code> class:</p>
<pre><code>[SettingsProvider(typeof(CustomSettingsProvider))]
internal sealed partial class Settings {
...
}
</code></pre>
<p>A good example of this is the <a href="http://msdn.microsoft.com/en-us/library/ms181001.aspx" rel="nofollow noreferrer">RegistrySettingsProvider</a>.</p>
<p>Edit: My initial read of your question thought you were asking how to persist settings in a WCF service. I see now you want to pass settings through WCF. The SettingsProvider class could also be used for this purpose.</p>
|
<p>I guess you're asking because you can't return a list of SettingProperty.
I would create a serializable class myself and load the properties there.</p>
| 20,605
|
<p>In XEmacs this is done by the calling the function char-to-ucs on a character. GNU Emacs does not seem to have this function. In GNU Emacs, characters seem to be ordinary integers. Running C-x = on a latin character reveals that the Emacs codepoint is different from the Unicode codepoint for the corresponding character. How do I find the Unicode codepoint of the character at point in GNU Emacs?</p>
|
<p>In a modern Emacs, M-x describe-char will tell you about the character at point.<br>
An example:</p>
<pre><code> character: ¢ (2210, #o4242, #x8a2, U+00A2)
charset: latin-iso8859-1
(Right-Hand Part of Latin Alphabet 1 (ISO/IEC 8859-1): ISO-IR-100.)
code point: #x22
syntax: w which means: word
category: l:Latin
buffer code: #x81 #xA2
file code: #xC2 #xA2 (encoded by coding system utf-8)
display: by this font (glyph code)
-apple-monaco-medium-r-normal--12-120-72-72-m-120-mac-roman (#xA2)
</code></pre>
<p>Note the U+00A2 in the first part, which gives the Unicode codepoint of the character.</p>
|
<p>Thanks for the quick answers. I looked at the source code for describe-char, and found the following snippet which solves my problem. I tested it in both XEmacs 21.4.13 Mule and GNU Emacs 22.1.1 and it seems to work.</p>
<pre><code>(or (get-char-property (point) 'untranslated-utf-8)
(encode-char (char-after) 'ucs))
</code></pre>
| 29,216
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.