instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Does WebSphere offer an HTTP input filter / firewall like mod_security?</p>
<p>I know that it's possible to have Apache be the HTTP server front-end to WebSphere, but that type of configuration is beyond my influence. We're stuck using just what WebSphere itself can do.</p>
<p>EDIT - To clarify, I am not looking for authentication, authorization, or non-repudiation aspects of security here. I want a rule-based HTTP firewall like mod_security that works on WebSphere.</p>
<p>Also, I know that in version 1.x, there was a partial implementation of mod_security in Java. We currently have a custom, in-house solution that is a work-alike, but less arbitrarily configurable. Thanks!</p>
|
<p>J2EE has a <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Security.html" rel="nofollow noreferrer">standard</a> way of <a href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Security4.html#67530" rel="nofollow noreferrer">securing</a> it's apps. I recommend using this. If what you are trying to do is oddball, you could look at <a href="http://publib.boulder.ibm.com/infocenter/wasinfo/v5r1//index.jsp?topic=/com.ibm.websphere.base.doc/info/aes/ae/rsec_customauth.html" rel="nofollow noreferrer">Custom User Registries (IBM specific)</a>, or implement a custom system all together with <a href="http://www.ibm.com/developerworks/java/library/j-pj2ee10.html" rel="nofollow noreferrer">Servlet Filters</a>.</p>
|
<p>There are many attacks that target the web server in front of your application server, so you should get control of the configuration of that web server too.</p>
| 21,738
|
<p>I have a sproc that returns a single line and column with a text, I need to set this text to a variable, something like:</p>
<pre><code>declare @bla varchar(100)
select @bla = sp_Name 9999, 99989999, 'A', 'S', null
</code></pre>
<p>but of course, this code doesn't work...</p>
<p>thanks!</p>
|
<p>If you are unable to change the stored procedure, another solution would be to define a temporary table, and insert the results into that</p>
<pre><code>DECLARE @Output VARCHAR(100)
CREATE TABLE #tmpTable
(
OutputValue VARCHAR(100)
)
INSERT INTO #tmpTable (OutputValue)
EXEC dbo.sp_name 9999, 99989999, 'A', 'S', null
SELECT
@Output = OutputValue
FROM
#tmpTable
DROP TABLE #tmpTable
</code></pre>
|
<p>If the stored procedure is returning a single value you could define one of the parameters on the stored procedure to be an OUTPUT variable, and then the stored procedure would set the value of the parameter</p>
<pre><code>CREATE PROCEDURE dbo.sp_Name
@In INT,
@Out VARCHAR(100) OUTPUT
AS
BEGIN
SELECT @Out = 'Test'
END
GO
</code></pre>
<p>And then, you get the output value as follows</p>
<pre><code>DECLARE @OUT VARCHAR(100)
EXEC sp_name 1, @Out OUTPUT
PRINT @Out
</code></pre>
| 26,029
|
<p>Data: a dependency list, already verified to be acyclic. So here, 'a' depends on 'b','c' (c depends on d), etc... </p>
<pre><code>A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
</code></pre>
<p>I'd like to have a top-down, recursive solution to let's say, find the chain starting at
'a': a, c, d, e, g, f, b</p>
<p>So, right now (a non-generator solution):</p>
<pre><code>def get_all(D,k):
L = []
def get2(D,k):
L.append(k)
for ii in D.get(k,[]):
get2(D, ii)
get2(D,k)
return L
</code></pre>
<p>Obviously, this is pretty weak :) I've been banging my head about how to how to get yields inside there, and I'd appreciate any py-foo y'all can bring to this.</p>
|
<p>Try this:</p>
<pre><code>#!/usr/bin/env python
def get_all(D, k):
yield k
for ii in D.get(k, []):
for jj in get_all(D, ii):
yield jj
A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
for ii in get_all(A,'a'):
print ii
</code></pre>
<p>Gives me </p>
<pre>
steve@rei:~/code/tmp
$ python recur.py
a
c
d
e
g
f
b
</pre>
|
<p>Try this:</p>
<pre><code>#!/usr/bin/env python
def get_all(D, k):
yield k
for ii in D.get(k, []):
for jj in get_all(D, ii):
yield jj
A = { 'a' : dict(b=1, c=1),
'c' : dict(d=1),
'd' : dict(e=1,f=1,g=1),
'h' : dict(j=1)
}
for ii in get_all(A,'a'):
print ii
</code></pre>
<p>Gives me </p>
<pre>
steve@rei:~/code/tmp
$ python recur.py
a
c
d
e
g
f
b
</pre>
| 13,397
|
<p>Something like this one on the Stackoverflow site would be nice! </p>
<p>Or something non-jQuery that doesn't conflict with jQuery $() tags would be great.</p>
|
<p>I'm surprised nobody has mentioned <strong><a href="http://markitup.jaysalvat.com/home/" rel="nofollow noreferrer">markitup</a></strong>:</p>
<p><em>markItUp! is a JavaScript plugin built on the jQuery library. It allows you to turn any textarea into a markup editor. Html, Textile, Wiki Syntax, Markdown, BBcode or even your own Markup system can be easily implemented.</em></p>
<p><img src="https://farm4.static.flickr.com/3498/3858805498_e52286c88c.jpg" alt="alt text"></p>
|
<p>Tiny MCE is the best IMHO - I have tired a ton of them and Tiny has the best over features, easy to create content templates, easy to set which CSS is shown in the editor and used to display it, very large API, great skins, ect...</p>
| 25,462
|
<p>I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree?</p>
<p>(I'm on a Windows system, but have Cygwin installed.)</p>
|
<p>I would rather go with the clearfsimport script, better equipped to import multiple times the same set of files, and automatically:</p>
<ul>
<li>add new files,</li>
<li>make new version of existing files previously imported (but modified in the source set of files re-imported)</li>
<li>remove files already imported but no longer present in the source set of files.</li>
<li>make a clear log of all operations made during the import process.</li>
</ul>
<p>So if your 'zip-file delivery needs to be updated on a regularly basis, clearfsimport is the way to go, but with the following options:</p>
<pre><code>clearfsimport -preview -rec -nset c:\sourceDir\* m:\MyView\MyVob\MyDestinationDirectory
</code></pre>
<p>Note the :</p>
<ul>
<li>-preview option: it will allow to check <em>what would happen</em> without actually doing anything.</li>
<li>'*' used only in Windows environment, in order to import the content of a directory</li>
<li>-nset option.</li>
</ul>
<p>From <a href="http://www.cmcrossroads.com/cgi-bin/cmwiki/view/CM/ClearFsImport" rel="noreferrer">CMWiki</a>, about that 'nset' option:</p>
<blockquote>
<p>By default, clearfsimport is meant to be used by the vob owner or a privileged user, but users often overlook the -nsetevent option, with which it may be used by any user.<br>
This option drives clearfsimport not to set the time stamps of elements to this of the source file object outside the vob (which requires privileged access).<br>
There is a minor non-obvious side-effect with this: once a version will have been created with a current time stamp, even the vob owner will not be able to import on top of it a version with an older (as it would be) time stamp, without this -nsetevent option. I.e. once you use this option, normal or privileged user, you are more or less bound to use it in the continuation. </p>
</blockquote>
|
<p>You can also add this command to your context menu with a small script...</p>
<p><a href="http://www.ibm.com/developerworks/rational/library/4687.html" rel="nofollow noreferrer">Ten best Triggers</a></p>
<p><strong>edit</strong>: oh, sorry. didn't saw that this was already suggested...</p>
| 16,744
|
<p>Does anyone have battle stories to share trying to use Visual Studio to develop applications for Unix? And I'm not talking using .NET with a Mono or Wine virtual platform running beneath.</p>
<p>Our company has about 20 developers all running Windows XP/Vista and developing primarily for Linux & Solaris. Until recently we all logged into a main Linux server and modified/built code the good old fashioned way: Emacs, Vi, dtpad - take your pick. Then someone said, "hey - we're living in the Dark Ages, we should be using an IDE".</p>
<p>So we tried out a few and decided that Visual Studio was the only one that would meet our performance needs (yes, I'm sure that IDE X is a very nice IDE, but we chose VS).</p>
<p>The problem is, how do you setup your environment to have the files available locally to VS, but also available to a build server? We settled with writing a Visual Studio plugin - it writes our files locally and to the build server whenever we hit "Save" and we have a bit fat "sync" button that we can push when our files change on the server side (for when we update to the latest files from our source control server). </p>
<p>The plugin also uses Visual Studio's external build system feature that ultimately just ssh's into the build server and calls our local "make" utility (which is Boost Build v2 - has great dependency checking, but is <em>really</em> slow to start as a result i.e. 30-60 seconds to begin). The results are piped back into Visual Studio so the developer can click on the error and be taken to the appropriate line of code (quite slick actually). The build server uses GCC and cross-compiles all of our Solaris builds.</p>
<p>But even after we've done all this, I can't help but sigh whenever I start to write code in Visual Studio. I click a file, start typing, and VS chugs to catch up with me.</p>
<p>Is there anything more annoying than having to stop and wait for your tools? Are the benefits worth the frustration?</p>
<p>Thoughts, stories, help?</p>
|
<p><em>VS chugs to catch up with me.</em> <br>
Hmmm ... you machine needs more memory & grunt. Never had performance problems with mine.</p>
<p>I've about a decade's experience doing exactly what you're proposing, most of it in the finance industry, developing real-time systems for customers in the banking, stock exchanges, stock brokerage niches.</p>
<p>Before proceeding further, I need to confess that all this was done in VS6 + CVS, and of late, SVN.</p>
<p><strong>Source Code Versioning</strong> </p>
<p>Developers have separate sourcesafe repositories so that they can store their work and check it packages of work at logical milestones. When they feel they want to do an integration test, we run a script that checks it into SVN. </p>
<p>Once checked into SVN, we've a process that kicks off that will automatically generate relevant makefiles to compile them on the target machines for continuous integration.</p>
<p>We've another set of scripts that synchs new stuff from SVN to the folders that VS looks after. There's a bit of gap because VS can't automatically pick up new files; we usually handle that manually. This only happens regularly the first few days of the project.</p>
<p>That's an overview of how we maintain codes. I have to say, I've probably glossed over some details (let me know if you're interested).</p>
<p><strong>Coding</strong></p>
<p>From the coding aspect, we rely heavily on the pre-processors (i.e. #define, etc) and flags in the makefile to shape compilation process. For cross platform portability, we use GCC. A few times, we were force to use aCC on HP-UX and some other compilers, but we did not have much grief. The only thing that is a constant pain, is that we had to watch out for thread heap spaces across platforms. The compiler does not spare us from that.</p>
<p><strong>Why?</strong></p>
<p>The question is usually, "Why the h*ll would you even what to have such a complicated way of development?". Our answer is usually another question that goes, "Have you any clue how insane it is to debug a multi-threaded application by examining the core dump or using gdb?". Basically, the fact that we can trace/step through each line of code when you're debugging an obscure bug, makes it all worth the effort!</p>
<p>Plus!... VS's intellisense feature makes it so easy to find the method/attribute belonging to classes. I also heard the VS2008 has refactoring capabilities. I've shifted my focus to Java on Eclipse that has both features. You'd be more productive focusing coding business logic rather than devote energy making your mind do stuff like <em>remember</em>!</p>
<p>Also! ... We'd end up with a product that can run on both Windows and Linux!</p>
<p>Good luck!</p>
|
<p>We are using a similar solution to what you described.</p>
<p>We have our code stored on the Windows side of the world and UNIX (QNX 4.25 to be exact) has access though an NFS mount (thanks to UNIX services for Windows). We have an ssh into UNIX to run make and the pipe to output into VS. Accessing the code is fast, builds are a little slower than before, but our longest compile is currently less than two minutes, not a big deal.</p>
<p>Using VS for UNIX development has been worth the effort to set it up, because we now have IntelliSense. Less typing = happy developer.</p>
| 3,640
|
<p>When using TempData, my understanding is that it will keep whatever you put in it around for only one request. So when using TempData to retain data across a redirect (in order to use the Post-Request-Get pattern), isn't it possible that some other request from the user could come into the server in between the response sending the redirect and the user's browser requesting the redirected-to page? In which case the get would no longer have the TempData available, correct?</p>
<p>Now, I understand that something like that happening would be very rare, but taking into consideration that the user might have another page open in another tab, and there might be either ajax or timed callback requests occuring on that page, it suddenly doesn't seem all that impossible to me. Is it just generally considered to be too remote to worry about, or am I misunderstanding something?</p>
<p>Edit: To be more specific about the scenario I was asking about.</p>
<ol>
<li>In Tab 1 the user browses to a page
with a post form</li>
<li>In Tab 2 the user browsers to another page on the site that does
ajax callbacks on a timer</li>
<li>In Tab 1, the user posts the form to the server</li>
<li>When the server receives the post, it saves some data in TempData
and sends back a redirect response</li>
<li>In tab 2, the timed ajax callback happens, sending a GET request to the server. The TempData is removed from the session</li>
<li>In tab 1, the browser receives the redirect and issues a GET request</li>
<li>The server processes the GET request and looks for the TempData, but it's not there anymore</li>
</ol>
|
<p>Well, browsing the ASP.NET MVC code shows that the while TempData is stored in the session, it is removed from the session when it is loaded. And it gets loaded in the Controller's ExecuteCore() method.</p>
<p>So I think that would mean that yes, you entirely could run into a race condition where a request from a different browser tab (you had a pretty good example) could cause this problem. But that would depend on each browser's model for handling requests. A browser might serialize all requests to the same server so that only one executes at a time. In reality, they won't do that, though, they'll cap it at the max which is (I think) 5 concurrent requests to the same server.</p>
<p>Given that an ASP.NET MVC site could be services requests to any browser (it's the web, afterall :) ) it is a real scenario, albeit probably a rare one, as you said.</p>
|
<p>TempData makes use of the Session object, which does not suffer this problem, AFAIK. Have you run into a specific problem with this?</p>
| 29,171
|
<p>Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database.</p>
<h2>Contents of <code>database.yml</code></h2>
<pre><code>development:
adapter: sqlserver
database: APPS_SETUP
Host: WindowsVT06\SQLEXPRESS
Username: se
Password: paswd
</code></pre>
<p>Run <code>rake db:migrate</code> from myapp directory</p>
<pre><code>----------
rake aborted!
no such file to load -- deprecated
</code></pre>
<h2><strong>ADO</strong></h2>
<p>I have dbi 0.4.0 installed and have created the ADO folder in</p>
<p><code>C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO</code></p>
<p>I got the ado.rb from the dbi 0.2.2</p>
<p>What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres.</p>
<p>****UPDATE****</p>
<p>I have installed the activerecord-sqlserver-adapter gem from --source=<a href="http://gems.rubyonrails.org" rel="nofollow noreferrer">http://gems.rubyonrails.org</a></p>
<p>Still not working.</p>
<p>I have verified that I can connect to the database by logging into SQL Management Studio with the credentials.</p>
<hr>
<p><strong>rake db:migrate --trace</strong></p>
<hr>
<pre><code>PS C:\Inetpub\wwwroot\myapp> rake db:migrate --trace
(in C:/Inetpub/wwwroot/myapp)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
rake aborted!
no such file to load -- deprecated
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin
gs'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver
_adapter.rb:29:in `sqlserver_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `send'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `connection='
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:260:in `retrieve_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:78:in `connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate'
C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31
C:/Ruby/bin/rake:19:in `load'
C:/Ruby/bin/rake:19
PS C:\Inetpub\wwwroot\myapp>
</code></pre>
|
<p>I ran into the same problem yesterday. Apparently 'deprecated' is a gem, so you want to run "gem install deprecated" to grab and install the latest version. Good luck.</p>
|
<p>I too had faced this problem. There is another work around.
You can create a DSN for the app db from control panel->admin tools->Odbc.
Database.yml file should look like below:</p>
<pre><code>adapter: sqlserver
mode: odbc
dsn: DSN_NAME
host: localhost
database: App_development
username: uname
password: password
</code></pre>
<p>I tried using the deprecated gem, wasn't of much use.
I had tried installing an ADO adaptor too which rendered useless.</p>
| 15,850
|
<p>I need a well tested Regular Expression (.net style preferred), or some other simple bit of code that will parse a USA/CA phone number into component parts, so:</p>
<ul>
<li>3035551234122</li>
<li>1-303-555-1234x122</li>
<li>(303)555-1234-122</li>
<li>1 (303) 555 -1234-122</li>
</ul>
<p>etc...</p>
<p>all parse into:</p>
<ul>
<li>AreaCode: 303</li>
<li>Exchange: 555</li>
<li>Suffix: 1234</li>
<li>Extension: 122</li>
</ul>
|
<p>None of the answers given so far was robust enough for me, so I continued looking for something better, and I found it:</p>
<p><a href="https://github.com/googlei18n/libphonenumber" rel="nofollow noreferrer">Google's library for dealing with phone numbers</a></p>
<p>I hope it is also useful for you.</p>
|
<p>here's a method easier on the eyes provided by the Z Directory (vettrasoft.com),
geared towards American phone numbers:</p>
<pre><code>string_o s2, s1 = "888/872.7676";
z_fix_phone_number (s1, s2);
cout << s2.print(); // prints "+1 (888) 872-7676"
phone_number_o pho = s2;
pho.store_save();
</code></pre>
<p>the last line stores the number to database table "phone_number".
column values: country_code = "1", area_code = "888", exchange = "872",
etc.</p>
| 28,150
|
<p>How do I convert a hex string to an integer?</p>
<pre><code>"0xffff" ⟶ 65535
"ffff" ⟶ 65535
</code></pre>
|
<p><strong>Without</strong> the <code>0x</code> prefix, you need to specify the base explicitly, otherwise there's no way to tell:</p>
<pre><code>x = int("deadbeef", 16)
</code></pre>
<p><strong>With</strong> the <code>0x</code> prefix, Python can distinguish hex and decimal automatically:</p>
<pre><code>>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
</code></pre>
<p>(You <em>must</em> specify <code>0</code> as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, <a href="https://docs.python.org/library/functions.html#int" rel="noreferrer"><code>int()</code></a> will assume base-10.)</p>
|
<p>The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)</p>
<p><strong>Example</strong> </p>
<pre><code>a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
</code></pre>
| 25,714
|
<p>I want to test some PHP on my local machine running Windows XP Professional. I'm familiar with coding PHP for upload, but not with running a web server.</p>
<p><strong>What is the easiest way to set up a test environment?</strong> Step-by-step instructions would be great if you can give them.</p>
<p>(I see WAMP recommended in <a href="https://stackoverflow.com/questions/125022/install-php-on-xp-iis-51">this thread</a> - thoughts?)</p>
<h2>Update - a year later</h2>
<p>A little self-promotion: after using XAMPP for a long time, I began to want things it didn't include. (Support for PDO was a big one - every time I tried to enable pdo and mysqli simultaneously, something crashed.) I eventually worked through the process of installing Apache, PHP, MySQL, and PHPMyAdmin individually, and <a href="http://sleeplessgeek.blogspot.com/2010/01/setting-up-apache-php-mysql-phpmyadmin.html" rel="nofollow noreferrer">documented the process with screen shots on my blog.</a></p>
<p>Some of the configuration that I was able to do this way could have been done in XAMPP, but it was only because I had to set things up myself that I discovered new things (like being able to serve files out of c:\whatever instead of c:\program files\apache\htdocs).</p>
<p>On the whole, I'm happier with having installed these items separately. But XAMPP was a good (and easy) package to start with, and served me well while I used it.</p>
|
<p><a href="https://i.stack.imgur.com/8PuYL.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8PuYL.gif" alt="alt text"></a><br>
<sub>(source: <a href="http://www.apachefriends.org/images/1240.jpg" rel="nofollow noreferrer">apachefriends.org</a>)</sub> </p>
<p><a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">Xampp</a> is the simplest. You can setup everything in a Step by Step and if you require further configuration (Virtual Server, extension) you have the normal php.ini and other file in the directory that you can edit yourself.</p>
<p>Here is the <a href="http://www.apachefriends.org/en/xampp-windows.html#522" rel="nofollow noreferrer">Step By Step installation</a> for Windows.</p>
|
<p><a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow noreferrer">XAMPP from ApacheFriends</a> is pretty simple to set up and use.</p>
<p><strong>note</strong> the site appears to be down as at 15:02 UTC on 3rd Dec 2008<br>
<strong>note again</strong> and it is back!</p>
| 43,780
|
<p>I have a custom UILabel subclass for displaying currency values. I only want the user to be able to enter digits and let the view format those digits into a currency value -- like a cash register. This makes UITextField an inappropriate choice for this kind of input.</p>
<p>I've already overridden hitTest: so that the UILabel will return itself -- this is apparently a bug. Also, I've overridden both canBecomeFirstResponder and becomeFirstResponder to return YES. Neither of these methods are being called, though.</p>
<p>I only want to let the user type numbers and use the backspace key. I've implemented UITextInputTraits, but the keyboard does not appear. So, can this be done? And does if so, what am I missing?</p>
|
<p>Just recently I had the same issue. Here is what I did:</p>
<p>I created a class to hold just an id and the text for each object (in my case I called it a sku (item number) and a description). This creates a smaller object that uses less memory since it is only used for searching. I'll still grab the full-blown objects from the database after I find matches.</p>
<pre><code>public class SmallItem
{
private int _sku;
public int Sku
{
get { return _sku; }
set { _sku = value; }
}
// Size of max description size + 1 for null terminator.
private char[] _description = new char[36];
public char[] Description
{
get { return _description; }
set { _description = value; }
}
public SmallItem()
{
}
}
</code></pre>
<p>After this class is created, you can then create an array (I actually used a List in my case) of these objects and use it for searching throughout your application. The initialization of this list takes a bit of time, but you only need to worry about this at start up. Basically just run a query on your database and grab the data you need to create this list.</p>
<p>Once you have a list, you can quickly go through it searching for any words you want. Since it's a contains, it must also find words within words (e.g. drill would return drill, drillbit, drills etc.). To do this, we wrote a home-grown, unmanaged c# contains function. It takes in a string array of words (so you can search for more than one word... we use it for "AND" searches... the description must contain all words passed in... "OR" is not currently supported in this example). As it searches through the list of words it builds a list of IDs, which are then passed back to the calling function. Once you have a list of IDs, you can easily run a fast query in your database to return the full-blown objects based on a fast indexed ID number. I should mention that we also limit the maximum number of results returned. This could be taken out. It's just handy if someone types in something like "e" as their search term. That's going to return a lot of results.</p>
<p>Here's the example of custom Contains function:</p>
<pre><code>public static int[] Contains(string[] descriptionTerms, int maxResults, List<SmallItem> itemList)
{
// Don't allow more than the maximum allowable results constant.
int[] matchingSkus = new int[maxResults];
// Indexes and counters.
int matchNumber = 0;
int currentWord = 0;
int totalWords = descriptionTerms.Count() - 1; // - 1 because it will be used with 0 based array indexes
bool matchedWord;
try
{
/* Character array of character arrays. Each array is a word we want to match.
* We need the + 1 because totalWords had - 1 (We are setting a size/length here,
* so it is not 0 based... we used - 1 on totalWords because it is used for 0
* based index referencing.)
* */
char[][] allWordsToMatch = new char[totalWords + 1][];
// Character array to hold the current word to match.
char[] wordToMatch = new char[36]; // Max allowable word size + null terminator... I just picked 36 to be consistent with max description size.
// Loop through the original string array or words to match and create the character arrays.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
char[] desc = new char[descriptionTerms[currentWord].Length + 1];
Array.Copy(descriptionTerms[currentWord].ToUpper().ToCharArray(), desc, descriptionTerms[currentWord].Length);
allWordsToMatch[currentWord] = desc;
}
// Offsets for description and filter(word to match) pointers.
int descriptionOffset = 0, filterOffset = 0;
// Loop through the list of items trying to find matching words.
foreach (SmallItem i in itemList)
{
// If we have reached our maximum allowable matches, we should stop searching and just return the results.
if (matchNumber == maxResults)
break;
// Loop through the "words to match" filter list.
for (currentWord = 0; currentWord <= totalWords; currentWord++)
{
// Reset our match flag and current word to match.
matchedWord = false;
wordToMatch = allWordsToMatch[currentWord];
// Delving into unmanaged code for SCREAMING performance ;)
unsafe
{
// Pointer to the description of the current item on the list (starting at first char).
fixed (char* pdesc = &i.Description[0])
{
// Pointer to the current word we are trying to match (starting at first char).
fixed (char* pfilter = &wordToMatch[0])
{
// Reset the description offset.
descriptionOffset = 0;
// Continue our search on the current word until we hit a null terminator for the char array.
while (*(pdesc + descriptionOffset) != '\0')
{
// We've matched the first character of the word we're trying to match.
if (*(pdesc + descriptionOffset) == *pfilter)
{
// Reset the filter offset.
filterOffset = 0;
/* Keep moving the offsets together while we have consecutive character matches. Once we hit a non-match
* or a null terminator, we need to jump out of this loop.
* */
while (*(pfilter + filterOffset) != '\0' && *(pfilter + filterOffset) == *(pdesc + descriptionOffset))
{
// Increase the offsets together to the next character.
++filterOffset;
++descriptionOffset;
}
// We hit matches all the way to the null terminator. The entire word was a match.
if (*(pfilter + filterOffset) == '\0')
{
// If our current word matched is the last word on the match list, we have matched all words.
if (currentWord == totalWords)
{
// Add the sku as a match.
matchingSkus[matchNumber] = i.Sku.ToString();
matchNumber++;
/* Break out of this item description. We have matched all needed words and can move to
* the next item.
* */
break;
}
/* We've matched a word, but still have more words left in our list of words to match.
* Set our match flag to true, which will mean we continue continue to search for the
* next word on the list.
* */
matchedWord = true;
}
}
// No match on the current character. Move to next one.
descriptionOffset++;
}
/* The current word had no match, so no sense in looking for the rest of the words. Break to the
* next item description.
* */
if (!matchedWord)
break;
}
}
}
}
};
// We have our list of matching skus. We'll resize the array and pass it back.
Array.Resize(ref matchingSkus, matchNumber);
return matchingSkus;
}
catch (Exception ex)
{
// Handle the exception
}
}
</code></pre>
<p>Once you have the list of matching skus, you can iterate through the array and build a query command that only returns the matching skus.</p>
<p>For an idea of performance, here's what we have found (doing the following steps):</p>
<ul>
<li>Search ~171,000 items</li>
<li>Create list of all matching items</li>
<li>Query the database, returning only the matching items</li>
<li>Build full-blown items (similar to SmallItem class, but a lot more fields)</li>
<li>Populate a datagrid with the full-blow item objects.</li>
</ul>
<p>On our mobile units, the entire process takes 2-4 seconds (takes 2 if we hit our match limit before we have searched all items... takes 4 seconds if we have to scan every item).</p>
<p>I've also tried doing this without unmanaged code and using String.IndexOf (and tried String.Contains... had same performance as IndexOf as it should). That way was much slower... about 25 seconds.</p>
<p>I've also tried using a StreamReader and a file containing lines of [Sku Number]|[Description]. The code was similar to the unmanaged code example. This way took about 15 seconds for an entire scan. Not too bad for speed, but not great. The file and StreamReader method has one advantage over the way I showed you though. The file can be created ahead of time. The way I showed you requires the memory and the initial time to load the List when the application starts up. For our 171,000 items, this takes about 2 minutes. If you can afford to wait for that initial load each time the app starts up (which can be done on a separate thread of course), then searching this way is the fastest way (that I've found at least).</p>
<p>Hope that helps.</p>
<p>PS - Thanks to Dolch for helping with some of the unmanaged code.</p>
|
<p>You could try Lucene.Net. I'm not sure how well it's suited to mobile devices, but it is billed as a "high-performance, full-featured text search engine library".</p>
<p><a href="http://incubator.apache.org/lucene.net/" rel="nofollow noreferrer">http://incubator.apache.org/lucene.net/</a>
<a href="http://lucene.apache.org/java/docs/" rel="nofollow noreferrer">http://lucene.apache.org/java/docs/</a></p>
| 34,865
|
<p>I'm making another app's window topmost to ensure that a click in my app brings the other's dialog into views. The problem I'm having is that I don't get focus back to my app after the call. If the other app has more windows one of them ends up with focus, and otherwise no window (looking at the taskbar only) gets focus. Where should I start investigating the issue? </p>
<p>My code for making the other app topmost is:</p>
<pre><code>Process p = Process.GetProcessById(trackedProcessID);
IntPtr h = p.MainWindowHandle;
uint TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE | SWP_ASYNCWINDOWPOS;
SetWindowPos(h, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
</code></pre>
<p>with constants as</p>
<pre><code>public static readonly uint SWP_NOMOVE = 0x0002;
public static readonly uint SWP_NOSIZE = 0x0001;
public static readonly uint SWP_ASYNCWINDOWPOS = 0x4000;
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
</code></pre>
|
<p>Related: <a href="https://stackoverflow.com/questions/48288/unexpected-behaviour-of-processmainwindowhandle">Unexpected behaviour of Process.MainWindowHandle</a></p>
<p>Basically MainWindowHandle gives you the current top-most window of the process despite what the documentation says.</p>
<p>That explains why the main window of your other process doesn't necessarily get focus.</p>
<p>Your other problem is because you are not returning focus to your app after giving it away.</p>
<p>Actually, the correct term for what you are doing is establishing <a href="http://en.wikipedia.org/wiki/Z-order" rel="nofollow noreferrer">z-order</a>.</p>
<p>Instead of trying to control z-order - which cannot be guaranteed - you might be better off sending messages to the other process.</p>
|
<p>[Actual solution used]</p>
<p>So far I'm going with sending the window handle of the calling window to the target app, and getting it to push it back on top when finished. It is a real pain as I will have ~50 windows to deal with, but it seems stable. The next approach, if this turns out to have problems, will be to call back to the calling app and ask it to push the window to the foreground, but I'd rather not as it introduces a possiblity that the user can do something to the calling app while the message is in transit (only a problem if there is a lot of messages comming in on the same transport protocol, which could well happen)</p>
<p>Do not try to use the incoming window handle and set the parent of any window shown in the target app to that handle, it only makes the shown dialog to appear within the bounds of the calling app window, and cropped if necessary - useless</p>
<p>Many thanks for the answers above to the question</p>
| 28,515
|
<p>I have a situation where I might have multiple instances of a program running at once, and it's important that just one specific function not be executing in more than one of these instances at once.</p>
<p>Is this the proper way to use a mutex to prevent this from happening?</p>
<pre><code>lock (this.GetType()) {
_log.Info("Doing Sync");
DoSync();
_log.Info("Sync Completed");
}
</code></pre>
|
<p>You said multiple instances of one application, so we're talking about two program.exe's running, right? The lock statement won't lock across multiple programs, just within the program. If you want a true Mutex, look at the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.mutex" rel="nofollow noreferrer">System.Threading.Mutex</a> object.</p>
<p>Here is a usage example:</p>
<pre><code>bool createdNew;
using (Mutex mtx = new Mutex(false, "MyAwesomeMutex", out createdNew))
{
try
{
mtx.WaitOne();
MessageBox.Show("Click OK to release the mutex.");
}
finally
{
mtx.ReleaseMutex();
}
}
</code></pre>
<p>The createdNew variable will let you know whether or not it was created the first time. It only tells you if it has been created, though. If you want to acquire the lock, you need to call WaitOne and then call ReleaseMutex to release it. If you just want to see if you created a Mutex, just constructing it is fine.</p>
|
<p>TheSeeker is correct.</p>
<p>Jeff Richter's advice in <a href="http://books.google.com/books?id=C-V_AAAACAAJ&dq=clr+via+c%23&ei=k6TBSPjYOomUzATIs8WIDg" rel="nofollow noreferrer">Clr Via C#</a> (p638-9) on locking is to create a private object specifically for the purpose of being locked.</p>
<pre><code>private Object _lock = new Object();
// usage
lock( _lock )
{
// thread-safe code here..
}
</code></pre>
<p>This works because _lock cannot be locked by anything outside the current class.</p>
<p>EDIT: this is applicable to threads executing within a single process. @David Mohundro's answer is correct for inter-process locking.</p>
| 6,908
|
<p>I currently use a DataTable to get results from a database which I can use in my code.</p>
<p>However, many example on the web show using a DataSet instead and accessing the table(s) through the collections method.</p>
<p>Is there any advantage, performance wise or otherwise, of using DataSets or DataTables as a storage method for SQL results?</p>
|
<p>It really depends on the sort of data you're bringing back. Since a DataSet is (in effect) just a collection of DataTable objects, you can return multiple distinct sets of data into a single, and therefore more manageable, object. </p>
<p>Performance-wise, you're more likely to get inefficiency from unoptimized queries than from the "wrong" choice of .NET construct. At least, that's been my experience.</p>
|
<p>A DataTable object represents tabular data as an in-memory, tabular cache of rows, columns, and constraints.
The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects.</p>
| 2,442
|
<p>I am developing a cocoa application that will be making heavy use of both web services and a standard dbms (most likely MySQL) and I am wondering if anyone has a good option for a database library or ORM solution they have used. CoreData is not an option due to the need to support a standard DBMS and to be able to modify the data outside of the normal application operation.</p>
<p>I have found a number of possible options from new open source libraries:
<a href="http://github.com/aptiva/activerecord/tree/master" rel="noreferrer">http://github.com/aptiva/activerecord/tree/master</a></p>
<p>To writing my own wrapper for the C MySQL api.</p>
<p>Any advice is welcome,</p>
<p>Thanks!</p>
<p>Paul</p>
|
<p>We faced a similar question when we first started work on <a href="http://checkoutapp.com" rel="noreferrer">Checkout</a>, our solution was to code the entire app in Python, using PyObjC. Checkout 1 had an sqlite backend, Checkout 2 has a postgres backend.</p>
<p>There are a couple of really mature and powerful ORMs on the Pyton side, such as <a href="http://www.sqlobject.org/" rel="noreferrer">SQLObject</a>, which is pretty simple to work with (we used it for Checkout 1.0) and <a href="http://www.sqlalchemy.org/" rel="noreferrer">SQLAlchemy</a>, which is more powerful but a bit harder to wrap your brain around (we used it for Checkout 2.0).</p>
<p>One approach you could evaluate, is building the application in Objective-C, but writing the data model and database connectivity/adminstration code in Python. You can use PyObjC to create a plugin bundle from this code, that you then load into your app That's more or less the approach we took for Checkout Server, which uses a Foundation command-line tool to administer a postgres server and the databases in it, this CLI tool in turn loads in a Python plugin bundle that has all of the actual database code in it. End-users mostly interact with the database through a System Preferences pane, that has no clue what the database looks like, but instead uses the command-line tool to interact with it.</p>
<p>Loading a plugin is simple:</p>
<pre><code>NSBundle *pluginBundle = [NSBundle bundleWithPath:pluginPath];
[pluginBundle load];
</code></pre>
<p>You will probably need to create .h files for the classes in your bundle that you want to have access to from your Obj-C code.</p>
|
<p>I've also implemented a simple object persistence framework based on sqlite, but it certainly wasn't trivial to do. I agree with eJames' conclusion- don't implement one yourself if you don't have to.</p>
<p>If you aren't committed to programming in Objective-C you might want to take a look at PyObjC which would allow you to program the database portion in Python. You can use the MySQLdb module for DB access and there are plenty of tutorials online for its use. It isn't hard to stuff the data back into Cocoa/CF classes and pass them back to your app.</p>
<p>The main caveat with PyObjC is that at the moment it doesn't work with Tiger.</p>
| 40,004
|
<p>I'd like to know if it's possible to compile an .swf file at runtime via C# (would be called via a Flex Application). I've read some articles about using fsch.exe, but nothing that gave any concrete examples.</p>
<p>I'm fairly certain this is possible, so a secondary question is whether it's feasible on a medium scale. I'd like to allow users to configure an swf, and then compile those settings directly into the swf for delivery rather than relying on external data storage for holding configuration details.</p>
<p>Thanks in advance for any assistance you can offer - </p>
<p>Bill</p>
|
<p>That's not a problem. The order of rows returned by a SQL SELECT is undefined unless it has an <code>ORDER BY</code>. The order you get them is usually influenced by the order they are stored in the table and/or the indices that are used by the statement.</p>
<p>So depending on that order without using <code>ORDER BY</code> is a very, very bad idea.</p>
<p>If you need them in some order, simply specify that.</p>
<p>It is important that a table is a <a href="http://en.wikipedia.org/wiki/Set_(mathematics)" rel="noreferrer">set</a> of rows and not a <a href="http://en.wikipedia.org/wiki/Sequence" rel="noreferrer">sequence</a> of rows.</p>
|
<p>The rows are returned in whatever their physical order on disk is; you can reorder them physically using the <code>CLUSTER</code> SQL command, but due to the way Postgres works they'll become unordered as soon as you start modifying rows.</p>
<p>For what you're doing an <code>ORDER BY</code> is the right answer.</p>
| 48,240
|
<p>I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added. </p>
<p>Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?</p>
|
<p>I'll add my voice to the noise and take a stab at making things clear:</p>
<h2>C# Generics allow you to declare something like this.</h2>
<pre><code>List<Person> foo = new List<Person>();
</code></pre>
<p>and then the compiler will prevent you from putting things that aren't <code>Person</code> into the list.<br />
Behind the scenes the C# compiler is just putting <code>List<Person></code> into the .NET dll file, but at runtime the JIT compiler goes and builds a new set of code, as if you had written a special list class just for containing people - something like <code>ListOfPerson</code>.</p>
<p>The benefit of this is that it makes it really fast. There's no casting or any other stuff, and because the dll contains the information that this is a List of <code>Person</code>, other code that looks at it later on using reflection can tell that it contains <code>Person</code> objects (so you get intellisense and so on).</p>
<p>The downside of this is that old C# 1.0 and 1.1 code (before they added generics) doesn't understand these new <code>List<something></code>, so you have to manually convert things back to plain old <code>List</code> to interoperate with them. This is not that big of a problem, because C# 2.0 binary code is not backwards compatible. The only time this will ever happen is if you're upgrading some old C# 1.0/1.1 code to C# 2.0</p>
<h2>Java Generics allow you to declare something like this.</h2>
<pre><code>ArrayList<Person> foo = new ArrayList<Person>();
</code></pre>
<p>On the surface it looks the same, and it sort-of is. The compiler will also prevent you from putting things that aren't <code>Person</code> into the list.</p>
<p>The difference is what happens behind the scenes. Unlike C#, Java does not go and build a special <code>ListOfPerson</code> - it just uses the plain old <code>ArrayList</code> which has always been in Java. When you get things out of the array, the usual <code>Person p = (Person)foo.get(1);</code> casting-dance still has to be done. The compiler is saving you the key-presses, but the speed hit/casting is still incurred just like it always was.<br />
When people mention "Type Erasure" this is what they're talking about. The compiler inserts the casts for you, and then 'erases' the fact that it's meant to be a list of <code>Person</code> not just <code>Object</code></p>
<p>The benefit of this approach is that old code which doesn't understand generics doesn't have to care. It's still dealing with the same old <code>ArrayList</code> as it always has. This is more important in the java world because they wanted to support compiling code using Java 5 with generics, and having it run on old 1.4 or previous JVM's, which microsoft deliberately decided not to bother with.</p>
<p>The downside is the speed hit I mentioned previously, and also because there is no <code>ListOfPerson</code> pseudo-class or anything like that going into the .class files, code that looks at it later on (with reflection, or if you pull it out of another collection where it's been converted into <code>Object</code> or so on) can't tell in any way that it's meant to be a list containing only <code>Person</code> and not just any other array list.</p>
<h2>C++ Templates allow you to declare something like this</h2>
<pre><code>std::list<Person>* foo = new std::list<Person>();
</code></pre>
<p>It looks like C# and Java generics, and it will do what you think it should do, but behind the scenes different things are happening.</p>
<p>It has the most in common with C# generics in that it builds special <code>pseudo-classes</code> rather than just throwing the type information away like java does, but it's a whole different kettle of fish.</p>
<p>Both C# and Java produce output which is designed for virtual machines. If you write some code which has a <code>Person</code> class in it, in both cases some information about a <code>Person</code> class will go into the .dll or .class file, and the JVM/CLR will do stuff with this.</p>
<p>C++ produces raw x86 binary code. Everything is <em>not</em> an object, and there's no underlying virtual machine which needs to know about a <code>Person</code> class. There's no boxing or unboxing, and functions don't have to belong to classes, or indeed anything.</p>
<p>Because of this, the C++ compiler places no restrictions on what you can do with templates - basically any code you could write manually, you can get templates to write for you.<br />
The most obvious example is adding things:</p>
<p>In C# and Java, the generics system needs to know what methods are available for a class, and it needs to pass this down to the virtual machine. The only way to tell it this is by either hard-coding the actual class in, or using interfaces. For example:</p>
<pre><code>string addNames<T>( T first, T second ) { return first.Name() + second.Name(); }
</code></pre>
<p>That code won't compile in C# or Java, because it doesn't know that the type <code>T</code> actually provides a method called Name(). You have to tell it - in C# like this:</p>
<pre><code>interface IHasName{ string Name(); };
string addNames<T>( T first, T second ) where T : IHasName { .... }
</code></pre>
<p>And then you have to make sure the things you pass to addNames implement the IHasName interface and so on. The java syntax is different (<code><T extends IHasName></code>), but it suffers from the same problems.</p>
<p>The 'classic' case for this problem is trying to write a function which does this</p>
<pre><code>string addNames<T>( T first, T second ) { return first + second; }
</code></pre>
<p>You can't actually write this code because there are no ways to declare an interface with the <code>+</code> method in it. You fail.</p>
<p>C++ suffers from none of these problems. The compiler doesn't care about passing types down to any VM's - if both your objects have a .Name() function, it will compile. If they don't, it won't. Simple.</p>
<p>So, there you have it :-)</p>
|
<p>NB: I don't have enough point to comment, so feel free to move this as a comment to appropriate answer.</p>
<p>Contrary to popular believe, which I never understand where it came from, .net implemented true generics without breaking backward compatibility, and they spent explicit effort for that.
You don't have to change your non-generic .net 1.0 code into generics just to be used in .net 2.0. Both the generic and non-generic lists are still available in .Net framework 2.0 even until 4.0, exactly for nothing else but backward compatibility reason. Therefore old codes that still used non-generic ArrayList will still work, and use the same ArrayList class as before.
Backward code compatibility is always maintained since 1.0 till now... So even in .net 4.0, you still have to option to use any non-generics class from 1.0 BCL if you choose to do so.</p>
<p>So I don't think java has to break backward compatibility to support true generics.</p>
| 5,163
|
<p>I work on a Webproject using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> and CakePHP. I use <a href="http://www.appelsiini.net/projects/jeditable" rel="nofollow noreferrer">jeditable</a> as an inplace edit plugin. For textareas I extend it using the <a href="http://www.appelsiini.net/2008/4/autogrow-textarea-for-jeditable" rel="nofollow noreferrer">autogrow plugin</a>.</p>
<p>Well, I have two problems with this:</p>
<ul>
<li>First, autogrow does only work on Firefox, not on IE, Safari, Opera and Chrome.</li>
<li>Second, I need a callback event for jeditable, when its finished showing the edit-component, to recalculate the <a href="http://kelvinluck.com/assets/jquery/jScrollPane/jScrollPane.html" rel="nofollow noreferrer">scrollbar</a></li>
</ul>
<p>Im not so familiar with Javascript, so i can't extend/correct this two libraries by my own. Has anyone used another js-library for inplace edit with auto growing textareas (no complete editors like TinyMCE, I need a solution for plain text)?</p>
<p>I also found <a href="http://plugins.jquery.com/project/Growfield" rel="nofollow noreferrer">Growfield</a>, it would work for other browsers, but there's no jeditable integration...</p>
<p><em>(sorry for my english)</em></p>
|
<p>I didn't see any problems using Autogrow with jeditable in any browsers but here is an implementation of Growfield with jeditable. It works much in the same way that the Autogrow plugin for jeditable does. You create a special input type for jeditable and just apply .growfield() to it. The necessary javascript is below, a demo can be <a href="http://alexcpendletonapps.appspot.com/editauto/growfield.html" rel="nofollow noreferrer" title="found here">found here</a>.</p>
<pre><code><script type="text/javascript">
/* This is the growfield integration into jeditable
You can use almost any field plugin you'd like if you create an input type for it.
It just needs the "element" function (to create the editable field) and the "plugin"
function which applies the effect to the field. This is very close to the code in the
jquery.jeditable.autogrow.js input type that comes with jeditable.
*/
$.editable.addInputType('growfield', {
element : function(settings, original) {
var textarea = $('<textarea>');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else {
textarea.width(settings.width);
}
// will execute when textarea is rendered
textarea.ready(function() {
// implement your scroll pane code here
});
$(this).append(textarea);
return(textarea);
},
plugin : function(settings, original) {
// applies the growfield effect to the in-place edit field
$('textarea', this).growfield(settings.growfield);
}
});
/* jeditable initialization */
$(function() {
$('.editable_textarea').editable('postto.html', {
type: "growfield", // tells jeditable to use your growfield input type from above
submit: 'OK', // this and below are optional
tooltip: "Click to edit...",
onblur: "ignore",
growfield: { } // use this to pass options to the growfield that gets created
});
})
</code></pre>
<p></p>
|
<p><strong>Thank you Alex!</strong> Your growfield-Plugin works.
In meantime I managed to solve the other problem. I took another <a href="http://flesler.blogspot.com/2007/10/jqueryscrollto.html" rel="nofollow noreferrer">Scroll-Library</a> and hacked a callback event into the jeditable-plugin. It was not that hard as I thought...</p>
| 18,345
|
<p>Can you suggest some good MVC framework for perl -- one I am aware of is <a href="http://www.catalystframework.org/" rel="noreferrer">catalyst</a></p>
<p>The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.</p>
|
<p>I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework. </p>
<p>In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives.</p>
<p>If Catalyst doesn't seem right to you, then you could build upon the lightweight framework <a href="http://cgi-app.org/" rel="noreferrer">CGI::Application</a> to suit your needs or take a look at some of the lesser known MVC frameworks like <a href="http://pagekit.org/" rel="noreferrer">PageKit</a> and <a href="http://maypole.perl.org/" rel="noreferrer">Maypole</a>.</p>
|
<p>I have built some applications with <a href="https://metacpan.org/pod/Kelp" rel="nofollow">Kelp</a>, it's easy to learn and very helpful.</p>
| 6,734
|
<p>Given the code from the <a href="http://railscasts.com/episodes/75" rel="nofollow noreferrer">Complex Form part III</a> how would you go about testing the virtual attribute?</p>
<pre><code> def new_task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
</code></pre>
<p>I am currently trying to test it like this:</p>
<pre><code> def test_adding_task_to_project
p = Project.new
params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
p.new_tasks_attributes=(params)
p.save
assert p.tasks.length == 1
end
</code></pre>
<p>But I am getting the following error:</p>
<blockquote>
<p>NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String</p>
</blockquote>
<p>Any suggestions on improving this test would be greatly appreciated.</p>
|
<p>It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:</p>
<pre><code>def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
</code></pre>
|
<p>Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?</p>
<p>Also, params looks odd to me. Is tasks.build() expecting input like this: <code>["new_tasks_attribute", {"name" => "paint fence"}]</code> ?</p>
<p>If not, maybe you actually want Hash#each_key() instead of Hash#each()?</p>
<p>Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.</p>
| 11,872
|
<p>I have a undirected graph with about 100 nodes and about 200 edges. One node is labelled 'start', one is 'end', and there's about a dozen labelled 'mustpass'.</p>
<p>I need to find the shortest path through this graph that starts at 'start', ends at 'end', <strong>and passes through all of the 'mustpass' nodes (in any order).</strong></p>
<p>( <a href="http://3e.org/local/maize-graph.png" rel="noreferrer">http://3e.org/local/maize-graph.png</a> / <a href="http://3e.org/local/maize-graph.dot.txt" rel="noreferrer">http://3e.org/local/maize-graph.dot.txt</a> is the graph in question - it represents a corn maze in Lancaster, PA)</p>
|
<p>Everyone else comparing this to the Travelling Salesman Problem probably hasn't read your question carefully. In TSP, the objective is to find the shortest cycle that visits <em>all</em> the vertices (a Hamiltonian cycle) -- it corresponds to having <em>every</em> node labelled 'mustpass'.</p>
<p>In your case, given that you have only about a dozen labelled 'mustpass', and given that 12! is rather small (479001600), you can simply try all permutations of only the 'mustpass' nodes, and look at the shortest path from 'start' to 'end' that visits the 'mustpass' nodes in that order -- it will simply be the concatenation of the shortest paths between every two consecutive nodes in that list.</p>
<p>In other words, first find the shortest distance between each pair of vertices (you can use Dijkstra's algorithm or others, but with those small numbers (100 nodes), even the simplest-to-code <a href="http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm" rel="noreferrer">Floyd-Warshall algorithm</a> will run in time). Then, once you have this in a table, try all permutations of your 'mustpass' nodes, and the rest.</p>
<p>Something like this:</p>
<pre><code>//Precomputation: Find all pairs shortest paths, e.g. using Floyd-Warshall
n = number of nodes
for i=1 to n: for j=1 to n: d[i][j]=INF
for k=1 to n:
for i=1 to n:
for j=1 to n:
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
//That *really* gives the shortest distance between every pair of nodes! :-)
//Now try all permutations
shortest = INF
for each permutation a[1],a[2],...a[k] of the 'mustpass' nodes:
shortest = min(shortest, d['start'][a[1]]+d[a[1]][a[2]]+...+d[a[k]]['end'])
print shortest
</code></pre>
<p>(Of course that's not real code, and if you want the actual path you'll have to keep track of which permutation gives the shortest distance, and also what the all-pairs shortest paths are, but you get the idea.) </p>
<p>It will run in at most a few seconds on any reasonable language :)<br/>
[If you have n nodes and k 'mustpass' nodes, its running time is O(n<sup>3</sup>) for the Floyd-Warshall part, and O(k!n) for the all permutations part, and 100^3+(12!)(100) is practically peanuts unless you have some really restrictive constraints.]</p>
|
<p>How about using brute force on the dozen 'must visit' nodes. You can cover all the possible combinations of 12 nodes easily enough, and this leaves you with an optimal circuit you can follow to cover them.</p>
<p>Now your problem is simplified to one of finding optimal routes from the start node to the circuit, which you then follow around until you've covered them, and then find the route from that to the end.</p>
<p>Final path is composed of :</p>
<p>start -> path to circuit* -> circuit of must visit nodes -> path to end* -> end</p>
<p>You find the paths I marked with * like this </p>
<p>Do an A* search from the start node to every point on the circuit
for each of these do an A* search from the next and previous node on the circuit to the end (because you can follow the circuit round in either direction)
What you end up with is a lot of search paths, and you can choose the one with the lowest cost. </p>
<p>There's lots of room for optimization by caching the searches, but I think this will generate good solutions.</p>
<p>It doesn't go anywhere near looking for an optimal solution though, because that could involve leaving the must visit circuit within the search. </p>
| 27,438
|
<p>JPEG, GIF and PNG can be displayed with the img tag and will work in all browsers, the object element can be use for displaying images specifying its MIME type, but what other graphic formats are supported by img or object tag in most browsers without installing plugins? (TIF, SVG, PCX, PICT, etc..) </p>
|
<p>There's an excellent <a href="http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support" rel="noreferrer">chart on wikipedia</a> that lists common image types and their support by browser.</p>
<p>The file types you listed (jpg, gif and png) seem to be the main formats supported by nearly every browser, albeit with certain caveats:</p>
<blockquote>
<p>Internet Explorer supports PNG images but is unable to correctly display images with gamma correction or color correction. Versions of Internet Explorer prior to version 7 are unable to correctly display images with alpha channel (for transparency) without additional coding</p>
</blockquote>
|
<p>Until 2006, IE didn't deal properly with PNGs that used the alpha channel, while Firefox and other (nearly) standards conforming browsers did. There is still a lot of IE 6 out there, judging by my apache logs.</p>
| 22,226
|
<p>ActiveReports seems like a powerful flexible tool, but if you make a mistake anywhere, you get an exception "data member not found. please check your datasource and datamember properties". </p>
<p>There is no indication as to which datasource/datamember is at fault or what subreport the problem lies in, but Active Reports must know this!</p>
<p>The stack trace is no use, as the error is thrown after the report.run() method is invoked from deep within code generated by Active Reports itself.</p>
<p>Does anybody have a solution other than commenting out one subreport after another and checking all fields in turn?</p>
|
<p>I was getting the same error while trying to pass a raw dataset to a report as below:
<p>
...
<p>
<code>Dim rpt as New ActiveReport</code>
<p>
<code>With rpt</code>
<p>
<code>.DataSource = _data</code>
<p>
<code>.Run()</code>
<p>
<code>End With</code>
<p>
...
<p>
I specified a table in the dataset and the error went away.
<p>
...
<p>
<code>.DataSource = _data.Tables(0)</code>
<p>
...
`</p>
|
<p>Unfortunately I don't know a way to immediately tell which subreport that error is coming from. Indeed, that error message should be improved when you're using subreports. I will report it to the ActiveReports development team. </p>
| 19,276
|
<p>As I continue my quest of learning functional programming, I've come
to wonder if there may be alternatives to my default "procedural" way
of thinking. To be more specific, I'm looking at a function I
wrote. Here is what it does:</p>
<pre><code>Swap two elements of an unordered list of numbers, such that one of the elements
is now in the right place
Add the sum of the swapped values to an accumulated total
Repeat until list is sorted
</code></pre>
<p>So, right now I'm using a standard loop* with an accum variable to do
the above. It works fine and all, and there's certainly nothing wrong
with iteration in real life, but as the point of this exercise is to
expand my way of thinking, I'm curious if there is a more functional
approach to the above algorithm. </p>
<p>Thanks!</p>
<p>*(Actually recursion, but whatever)</p>
|
<p>If your software is open source you can use <a href="http://launchpad.net" rel="nofollow noreferrer">Launchpad</a> for translating.</p>
|
<p>I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team. </p>
<p>Anyway, bravo for internationalizing your application. Good luck!</p>
| 41,102
|
<p>My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a <code>URLConnection</code>. </p>
<p>How can I specify this?</p>
|
<p>This should do the trick:</p>
<pre><code>URL url = new URL(yourUrlHere);
Proxy proxy = new Proxy(Proxy.Type.DIRECT,
new InetSocketAddress(
InetAddress.getByAddress(
new byte[]{your, ip, interface, here}), yourTcpPortHere));
URLConnection conn = url.openConnection(proxy);
</code></pre>
<p>And you are done.
Dont forget to handle exceptions nicely and off course change the values to suit your scenario.</p>
<p>Ah and I omitted the import statements</p>
|
<p>Setting manually socket work fine ...</p>
<pre><code>private HttpsURLConnection openConnection(URL src, URL dest, SSLContext sslContext)
throws IOException, ProtocolException {
HttpsURLConnection connection = (HttpsURLConnection) dest.openConnection();
HttpsHostNameVerifier httpsHostNameVerifier = new HttpsHostNameVerifier();
connection.setHostnameVerifier(httpsHostNameVerifier);
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setRequestMethod(POST_METHOD);
connection.setRequestProperty(CONTENT_TYPE, SoapConstants.CONTENT_TYPE_HEADER);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
if ( src!=null ) {
InetAddress inetAddress = InetAddress.getByName(src.getHost());
int destPort = dest.getPort();
if ( destPort <=0 )
destPort=SERVER_HTTPS_PORT;
int srcPort = src.getPort();
if ( srcPort <=0 )
srcPort=CLIENT_HTTPS_PORT;
connectionSocket = connection.getSSLSocketFactory().createSocket(dest.getHost(), destPort, inetAddress, srcPort);
}
connection.connect();
return connection;
}
</code></pre>
| 11,707
|
<p>I have a database with a table Customers that have some data<br><br>
I have another database in the office that everything is the same, but my table Customers is empty<br><br>
How can I create a sql file in SQL Server 2005 (T-SQL) that takes everything on the table Customers from the first database, creates a, let's say, buildcustomers.sql, I zip that file, copy it across the network, execute it in my SQL Server and voila! my table Customers is full<br>
<br>
How can I do the same for a whole database?</p>
|
<p>This functionality is already built in to Sql Server Management Studio 2008. </p>
<p>Just download <a href="http://www.microsoft.com/sqlserver/2008/en/us/trial-software.aspx" rel="noreferrer">the trial</a> and only install the client tools (which shouldn't expire). Use Management Studio 2008 to connect to your 2005 database (its backwards compatible).</p>
<ol>
<li>Right click your database</li>
<li>Choose <strong>Tasks</strong> > <strong>Generate Scripts</strong></li>
<li>Press Next, select your database again</li>
<li>On the 'Choose Script Options' screen, there is an option called <strong>Script Data</strong> which will generate SQL insert statements for all your data.</li>
</ol>
<p>(Note: for SQL Server Management Studio 2008 R2, the option is called "Types of data to script" and is the last one in the General section. The choices are "data only", "schema and data", and "schema only")</p>
<p><img src="https://imgur.com/xM9nm.jpg" alt="alt text">
<img src="https://imgur.com/wV1BV.jpg" alt="alt text"></p>
|
<p>If both databases resides in the same instance of SQL Server, ie use same connection, this SQL might be helpful:</p>
<pre><code>INSERT INTO [DestinationDB].[schema].[table] ([column])
SELECT [column] FROM [OriginDB].[schema].[table]
GO
</code></pre>
| 4,073
|
<p>I have a fingerprint image taken from a sliding scanner. However the output does not have clean background. It looks like this:</p>
<p><a href="http://img208.imageshack.us/img208/2622/dirtyie0.png">dirty http://img208.imageshack.us/img208/2622/dirtyie0.png</a></p>
<p>I want to remove the background so that further processing will be more accurate. Something like this:</p>
<p><a href="http://img515.imageshack.us/img515/7530/cleanhh6.png">cleaned http://img515.imageshack.us/img515/7530/cleanhh6.png</a></p>
<p>How to do that? What image processing technique (if any) can be used? Thank you.</p>
|
<p>You might try an edge detection filter. That would help remove the background noise, and might sharpen up the fingerprint features for the rest of the processing.</p>
<p><a href="http://en.wikipedia.org/wiki/Canny_edge_detector" rel="noreferrer">Canny edge detector</a> might be a good one to try first. There's even a <a href="http://matlabserver.cs.rug.nl/cannyedgedetectionweb/web/index.html" rel="noreferrer">free web implementations you can try</a> and a <a href="http://www.tomgibara.com/computer-vision/canny-edge-detector" rel="noreferrer">public-domain Java implementation available</a>.</p>
<p>EDIT: Was curious how it would work, so I tried the web implementation on default settings -- not too bad. It does seem to come up with a few "phantom" features in there, but overall it looks a bit easier to process.</p>
<p><a href="http://img356.imageshack.us/img356/5/ml00055edgedetectionwp7.png" rel="noreferrer">alt text http://img356.imageshack.us/img356/5/ml00055edgedetectionwp7.png</a></p>
|
<p>To start, I'd increase the contrast to 100% to get a pure black and white image (not greyscale).</p>
| 27,750
|
<p>Is there a built in way to determine if a component is fully visible in a Flex application (i.e. not offscreen one way or the other). If not how would I go about figurin it out?</p>
<p>I want to show or hide additional 'next' and 'previous' buttons if my primary 'next' and 'previous' buttons are off screen.</p>
<p>What event would be best to listen to to 'recalculate' ? stage.resize?</p>
<p>thanks!</p>
|
<p>here is a method for calculating if the component is within the bounds of the stage, it will not however tell you if the component is being hidden by another component, or if the component is being hidden because it is outside the bounds of another container.</p>
<pre><code>public function isComponentWithinStage(c:UIComponent):Boolean {
var tl:Point = c.localToGlobal(new Point(0, 0));
var br:Point = c.localToGlobal(new Point(c.width, c.height));
//are we off the left or top of stage?
if ( tl.x < 0 || tl.y < 0 ) {
return false;
}
var stage:Stage = Application.application.stage;
//off the right or bottom of stage?
if ( br.x > stage.width || br.y > stage.height ) {
return false;
}
return true;
}
</code></pre>
|
<p>Could you give the specifics of the visible item and the container(s) it's in? Is it a matter of having to scroll some container to get to the buttons? Or is it a matter of someone has dragged a child window of a flexlib:MDICanvas partially off screen? </p>
<p>I think it's going to come down to if the x,y position of the component is beyond the width and height of its container, (and so on up through the parent containers until you reach your top level Application.)</p>
| 34,993
|
<p>I have form with 2 DDL named</p>
<p>State and City</p>
<p>State:</p>
<pre><code><asp:UpdatePanel ID="States" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="States"EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="States" runat="server"
AutoPostBack="True" DataSourceID="StatesObjectDataSource"
AppendDataBoundItems="true"
onselectedindexchanged="States_SelectedIndexChanged">
<asp:ListItem Value="-1" Text="- None -"/>
</asp:DropDownList>
<asp:ObjectDataSource ID="StatesObjectDataSource" runat="server"
onselecting="StatesObjectDataSource_Selecting"
SelectMethod="GetStates"
TypeName="Something">
</asp:ObjectDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</code></pre>
<p>City:</p>
<pre><code><asp:DropDownList ID="Cities" runat="server">
</asp:DropDownList>
</code></pre>
<p>When they choose a state I want to populate the Cities DDL with all the cities for that state.</p>
<p>In code behind I am able to get to </p>
<pre><code>States_SelectedIndexChanged(object sender, EventArgs e)
</code></pre>
<p>and i try to populate the Cities DDL by this</p>
<pre><code>Cities.Items.Add(new ListItem(city,city));
</code></pre>
<p>However, I do not see my Cities DDL populated</p>
|
<p>I recommend creating a private property in the ViewState that holds the collection of physical objects. Then add the object to that list then databind the list of objects to the drop down.</p>
<p>Page Behind</p>
<pre><code><asp:DropDownList runat="server" ID="ddlCity" DataValueField="Key" DataTextField="Value">
</asp:DropDownList>
</code></pre>
<p>Code Behind</p>
<pre><code>private List<KeyValuePair<string, string>> ListData
{
get { return (List<KeyValuePair<string, string>>) (ViewState["ListData"] ??
(ViewState["ListData"] = new List<KeyValuePair<string, string>>())); }
set { ViewState["ListData"] = value; }
}
protected void States_SelectedIndexChanged_SelectedIndexChanged(object sender, EventArgs e)
{
ListData.Add(new KeyValuePair<string, string>(ddlCitys.SelectedValue, ddlCitys.SelectedValue));
ddlCitys.DataSource = ListData;
ddlCitys.DataBind();
}
</code></pre>
<p>The get statement also employs lazy loading on the ListData property so you will never encounter a null reference exception when accessing the list.</p>
|
<p>If at all possible, I would suggest using the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/CascadingDropDown/CascadingDropDown.aspx" rel="nofollow noreferrer">CascadingDropDown Extender</a> instead of the UpdatePanel. There's no use reinventing that wheel, and the Toolkit control uses web services instead of partial postbacks (much faster).</p>
| 38,446
|
<p>If tan(x) = y and atan(y) = x why Math.Atan(Math.Tan(x)) != x?</p>
<p>I´m trying to calculate x in something like: </p>
<pre><code>tan(2/x +3) = 5
</code></pre>
<p>so </p>
<pre><code>atan(tan(2/x + 3) = atan(5)
</code></pre>
<p>and so on... but I´ve tried this: </p>
<pre><code>double d = Math.Atan(Math.Tan(10));
</code></pre>
<p>and d != 10. Why?</p>
|
<ol>
<li>The tangent function is periodic with period pi, and is invertible <em>only</em> if you restrict it to a subset of its domain over which it is injective. Usually the choice of such set is the open interval ]-pi/2, pi/2[, hence the arctan function will always return a point in that interval. In your case, 10 = 3*pi + 0.57522... Thus, the arctan of the tangent of 10 will return 0.57522... </li>
<li>Note that the arctan function, defined as above, <em>is</em> injective and defined over all the real numbers, hence the converse of your problem <pre><code>math.tan(math.atan(x)) == x </code></pre>
indeed holds for each x (except for numerical errors).</li>
<li>In order to deal with numerical errors, you should never perform comparisons between the results of floating point computations using == or !=. Use <pre><code>abs(number1 - number2) < epsilon // ==
abs(number1 - number2) >= epsilon // !=
</code></pre> instead, where epsilon is a small positive constant.</li>
</ol>
|
<p>In general, when you are dealing with floating point numbers, you are dealing with approximations. There are numbers that cannot be represented exactly, and the tan and arctan operations are themselves only approximate.</p>
<p>If you want to compare floating point numbers, you need to ask if they are nearly equal, or equivalently, if the difference is less than some small value, and think carefully what you are doing.</p>
<p>Here is are some FAQS (for c++, but the idea is the same), that talk a bit about some of the oddities of floating point numbers:</p>
<p><a href="http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.16" rel="nofollow noreferrer">FAQ 29.16</a><br>
<a href="http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17" rel="nofollow noreferrer">FAQ 29.17</a><br>
<a href="http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18" rel="nofollow noreferrer">FAQ 29.18</a> </p>
<p>Edit: Looking at the other answers, I realise that the main problem is probably that tan isn't invertible, but the approximation issue is worth considering too, whenever you test floating point numbers for equality. </p>
<p>Looking at the .net documentation for <a href="http://msdn.microsoft.com/en-us/library/system.math.atan.aspx" rel="nofollow noreferrer">Math.Atan</a>, atan produces a value between -π/2 and ≤ π/2, which doesn't include 10. That I think is the usual range for arctan. </p>
| 40,142
|
<p>I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about <a href="https://rads.stackoverflow.com/amzn/click/com/0070004846" rel="noreferrer" rel="nofollow noreferrer">Structure and Interpretations of Computer Programs</a>, but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary.</p>
<p>So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages?</p>
|
<p><a href="http://www.ccs.neu.edu/home/matthias/BTLS/" rel="noreferrer">The Little Schemer</a> teaches recursion really well, and it's fun and simple to read. </p>
<p>I also liked <a href="http://www.scheme.com/tspl3/" rel="noreferrer">The Scheme Programming Language</a> for a broader introduction into the language. </p>
|
<p>I have heard good things about <a href="https://rads.stackoverflow.com/amzn/click/com/0201342758" rel="nofollow noreferrer" rel="nofollow noreferrer">Haskell Functional Programming</a>, but I also found this <a href="http://www.amazon.com/LISP-Functional-Programming-Books/lm/36GEU8N3B2JPW" rel="nofollow noreferrer">list</a> of functional programming books at amazon that might be helpful to you.</p>
| 4,313
|
<p>I have a MySQL table LOGIN_LOG with fields ID, PLAYER, TIMESTAMP and ACTION. ACTION can be either 'login' or 'logout'. Only around 20% of the logins have an accompanying logout row. For those that do, I want to calculate the average duration.</p>
<p>I'm thinking of something like</p>
<pre><code>select avg(LL2.TIMESTAMP - LL1.TIMESTAMP)
from LOGIN_LOG LL1
inner join LOGIN_LOG LL2 on LL1.PLAYER = LL2.PLAYER and LL2.TIMESTAMP > LL1.TIMESTAMP
left join LOGIN_LOG LL3 on LL3.PLAYER = LL1.PLAYER
and LL3.TIMESTAMP between LL1.TIMESTAMP + 1 and LL2.TIMESTAMP - 1
and LL3.ACTION = 'login'
where LL1.ACTION = 'login' and LL2.ACTION = 'logout' and isnull(LL3.ID)
</code></pre>
<p>is this the best way to do it, or is there one more efficient?</p>
|
<p>Given the data you have, there probably isn't anything much faster you can do because you have to look at a LOGIN and a LOGOUT record, and ensure there is no other LOGIN (or LOGOUT?) record for the same user between the two.</p>
<p>Alternatively, find a way to ensure that a disconnect records a logout, so that the data is complete (instead of 20% complete). However, the query probably still has to ensure that the criteria are all met, so it won't help the query all that much.</p>
<p>If you can get the data into a format where the LOGIN and corresponding LOGOUT times are both in the same record, then you can simplify the query immensely. I'm not clear if the SessionManager does that for you.</p>
|
<p>Do you have a SessionManager type object that can timeout sessions? Because a timeout could be logged there, and you could get the last activity time from that and the timeout period.</p>
<p>Or you log all activity on the website/service, and thus you can query website/service visit duration directly, and see what activities they performed. For a website, Apache log analysers can probably generate the required stats.</p>
| 45,660
|
<p>We are moving our database server to a bigger box. I have several databases with full text indexes. What is the best way to move the full text indexes?</p>
|
<p>I find backup and restore is the only reliable way to move databases. The FTS should move with it when you do that. Detaching and reattaching databases never really sits well with me. </p>
|
<p>If you are moving the databases, move the folders that contain the FTS information and you should be fine.</p>
<p>If you're doing a restore, you should be fine as is.</p>
| 25,262
|
<p>I think I've declared a Vector with an object correctly. But, I don't know how to access it's members when looping with Iterator.</p>
<p>In my code, the line --->> cout << " " << *Iter;</p>
<p>How do I print the contents of the members? Like *Iter.m_PackLine ???</p>
<p>Not sure if I used the correct terminology, but appreciate the help! Thanks</p>
<pre><code>class CFileInfo
{
public:
std::string m_PackLine;
std::string m_FileDateTime;
int m_NumDownloads;
};
void main()
{
CFileInfo packInfo;
vector<CFileInfo, CFileInfo&> unsortedFiles;
vector<CFileInfo, CFileInfo&>::iterator Iter;
packInfo.m_PackLine = "Sample Line 1";
packInfo.m_FileDateTime = "06/22/2008 04:34";
packInfo.m_NumDownloads = 0;
unsortedFiles.push_back(packInfo);
packInfo.m_PackLine = "Sample Line 2";
packInfo.m_FileDateTime = "12/05/2007 14:54";
packInfo.m_NumDownloads = 1;
unsortedFiles.push_back(packInfo);
for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ )
{
cout << " " << *Iter; // !!! THIS IS WHERE I GET STUMPED
// How do I output values of the object members?
}
} // end main
</code></pre>
|
<pre><code>cout << " " << *Iter;
</code></pre>
<p>will only work if <code>CFileInfo</code> has an overloaded <code>operator<<</code> that can output your struct. You can output individual members of the struct instead like this:</p>
<pre><code>cout << " " << Iter->m_PackLine;
</code></pre>
<p>Alternatively, the following is equivalent to that:</p>
<pre><code>cout << " " << (*Iter).m_PackLine;
</code></pre>
<p>You have to put parentheses around *Iter, since the member-access operator binds thighter otherwise.</p>
<p>On a side-node, make your main function return int instead of void. making it return void is not valid in C++.</p>
<hr>
<p>You declare the vector like this:</p>
<pre><code>vector<CFileInfo, CFileInfo&> unsortedFiles;
</code></pre>
<p>The second argument to <code>vector</code> should be another thing. It's not needed for your code to give the vector a second argument at all. Just use this:</p>
<pre><code>vector<CFileInfo> unsortedFiles;
</code></pre>
<hr>
<p>Another thing i noticed is you increment the iterator using <code>Iter++</code> (called <code>postfix increment</code>). For iterators, always prefer <code>++Iter</code>, which is called <code>prefix increment</code>. </p>
|
<p>Thanks all, wish I could grant multiple points for the answers :)</p>
<p>litb also pointed out a problem I was having in my declaration of the vector. I removed the second argument in the vector declaration and it worked.</p>
<p>Stackoverflow parsed out some of my code, I'll be more careful in posting next time.</p>
| 41,700
|
<p>I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible.</p>
|
<p>I'm going to assume you mean "workspace", not "workstation", as your question doesn't quite make sense to me otherwise.</p>
<p>In Visual Studio, go to the Source Control Explorer (View->Other Windows->Source Control Explorer). At the top of the source control explorer window you should have a toolbar with a few buttons. Somewhere on that toolbar (for me it's at the right) there should be a Workspace dropdown. Just select the workspace you want to use from that dropdown.</p>
|
<p>I don't entirely understand your question.</p>
<p>Are you saying that files you check out on one machine seems to be unaccessible on another of your machines? I'd say that would be entirely by design, as now you have a file that has local modifications done on one machine, which may or may not be available on your other machines.</p>
<p>When you say <em>checked out by somebody else</em>, what does that mean exactly? How are you verifying this, what are you looking at?</p>
<p>Or do you mean something else? In that case, please elaborate.</p>
| 4,223
|
<p>I have log4net running on my AsP.NET site. I'm able to log messages to my DB Table, but it isn't logging the ThreadContext properties. For example:</p>
<pre><code>ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString();
ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
</code></pre>
<p>My log4net.config adds those values as parameters into my SQL DB table:</p>
<pre><code><parameter>
<parameterName value="@URL"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{log4net:Url}"/>
</layout>
</parameter>
<parameter>
<parameterName value="@HttpReferer"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{log4net:HttpReferer}"/>
</layout>
</parameter>
</code></pre>
<p>As I debug, I see that those ThreadContext properties are being set, but they aren't getting into the DB. </p>
<p>How can I get that to work?</p>
|
<p>So, it turns out the config was to blame. It was slightly wrong:</p>
<p>Original:</p>
<pre><code><conversionPattern value="%property{log4net:HttpReferer}"/>
</code></pre>
<p>Changed:</p>
<pre><code><conversionPattern value="%property{HttpReferer}"/>
</code></pre>
<p>I had to take out the "log4net:" inside of property. </p>
<p>What's odd is that one property still required log4net:propertyName. I have absolutely no idea why it works this way, but that's the fix that worked!</p>
|
<p>Can you turn on log4net verbose/debug/show sql to see what its doing at that level? Is there perhaps another bit of config thats needed to tie it all together?</p>
| 22,681
|
<p>What's a quick-and-dirty way to make sure that only one instance of a shell script is running at a given time?</p>
|
<p>Use <a href="http://linux.die.net/man/1/flock" rel="noreferrer"><code>flock(1)</code></a> to make an exclusive scoped lock a on file descriptor. This way you can even synchronize different parts of the script.</p>
<pre><code>#!/bin/bash
(
# Wait for lock on /var/lock/.myscript.exclusivelock (fd 200) for 10 seconds
flock -x -w 10 200 || exit 1
# Do stuff
) 200>/var/lock/.myscript.exclusivelock
</code></pre>
<p>This ensures that code between <code>(</code> and <code>)</code> is run only by one process at a time and that the process doesn’t wait too long for a lock.</p>
<p>Caveat: this particular command is a part of <a href="http://en.wikipedia.org/wiki/Util-linux" rel="noreferrer"><code>util-linux</code></a>. If you run an operating system other than Linux, it may or may not be available.</p>
|
<p>Try something like the below,</p>
<pre><code>ab=`ps -ef | grep -v grep | grep -wc processname`
</code></pre>
<p>Then match the variable with 1 using an if loop.</p>
| 22,428
|
<p>I've read a lot of comments mention in passing that the BlackBerry threading model deviates from the Java standard and can cause issues, but no amount of googling has enlightened me on what this means exactly.</p>
<p>I've been developing a fairly large business application for the BlackBerry and, although I don't really have any previous experience with Java multi-threaded applications, haven't come across any issue that we've been able to blame on threading, other than what we caused ourselves.</p>
<p>Can someone describe exactly how the BlackBerry threading model is different, and how I as a developer should take that into account? Obviously any links on the topic would also be great.</p>
|
<p>1.UI
User interface operations <strong>always</strong> need to run in the UI thread. To execute such functions like <code>LabelField.setText("foo");</code> you need to do:</p>
<pre><code>UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
myLabelField.setText("foo");
myLabelField.setDirty(true);
}
});
</code></pre>
<p>Pretty easy, huh? </p>
<p>2.Network
Network operation should <strong>never</strong> run within the UI thread. To do such things do:</p>
<pre><code>new Thread(){
public void run(){
HttpConnection hc =
(HttpConnection)Connector.open("http://www.stackoverflow.com");
}
}.start();
</code></pre>
<p>These two main principle are very important. You should always take care of in which thread you are operating.</p>
|
<p>The only issue I can think of is discussed in the answer to <a href="https://stackoverflow.com/questions/292587/interacting-with-ui-threads-in-javaj2me">another stackoverflow question</a>.</p>
| 46,451
|
<p>Warning: this is the actual code generated from my system:</p>
<pre><code>;WITH RESULTS AS (
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = m.APPL_CD
AND cat.ALBASE = m.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
GROUP BY m.APPL_CD, m.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = c.APPL_CD
AND cat.ALBASE = c.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
GROUP BY c.APPL_CD, c.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
ON m.[YEAR] = c.[YEAR]
AND m.[MONTH] = c.[MONTH]
AND m.[BANK_NO] = c.[BANK_NO]
AND m.[COST_CENTER] = c.[COST_CENTER]
AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]
AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]
AND m.[APPL_CD] = c.[APPL_CD]
AND m.[ALBASE] = c.[ALBASE]
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = m.APPL_CD
AND cat.ALBASE = m.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
WHERE c.[YEAR] IS NULL
GROUP BY m.APPL_CD, m.ALBASE
UNION
SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value
FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK)
RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)
ON m.[YEAR] = c.[YEAR]
AND m.[MONTH] = c.[MONTH]
AND m.[BANK_NO] = c.[BANK_NO]
AND m.[COST_CENTER] = c.[COST_CENTER]
AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]
AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]
AND m.[APPL_CD] = c.[APPL_CD]
AND m.[ALBASE] = c.[ALBASE]
INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)
ON cat.APPL_CD = c.APPL_CD
AND cat.ALBASE = c.ALBASE
AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'
WHERE m.[YEAR] IS NULL
GROUP BY c.APPL_CD, c.ALBASE
) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure
</code></pre>
<p>The code just sits there, no locking or blocking.</p>
<p>The individual components of the UNION return in a few seconds each. The code works in general for checking the output results of all the other programs in the STAT group, but just halts for this one.</p>
<p>Remove the CTE, no effect, sits there for 30 minutes/an hour, however long you care to wait before cancelling.</p>
<p>Remove the UNION, and the 4 result sets return in 11 seconds, total of 19 records accross all 4 result sets.</p>
<p>Run just the first two together - works fine, run just the last 2 together, also fine. First 3 together, fine, too.</p>
<p>I've already modified the code to output these to a #temp table, for other requirements, so I'm just going to change it to output each to the #temp table in sequence, but I have never seen SQL just stop like that with no evidence of blocking or anything.</p>
|
<p>Change to UNION ALL, since you'll never have dupes (the Measure column is hard coded to be different). UNION must first sort the rows, and then find dupes and eliminate.</p>
<p>My real guess is it's a parallelization issue. Try adding OPTION (MAXDOP 1) at the end.</p>
|
<p>If you can post the query execution plan in XML format, that'll help us determine what parts of the query are causing problems. In SSMS, click Query, Display Estimated Execution Plan, and when it comes up, right-click on it and save as XML.</p>
| 19,846
|
<p>Here's the situation:</p>
<p>I have one VS2005 solution with two projects: MyDll (DLL), MyDllUnitTest (console EXE).</p>
<p>In MyDll I have a class called MyClass which is internal to the DLL and should not be exported. I want to test it in MyDllUnitTest, so I added a test suite class called MyClassTest, where I create instances of MyClass and test them.</p>
<p>My question: how can I link the object file of MyClass, created by building MyDll, to the MyDllUnitTest EXE? I don't want to build MyClass in MyDllUnitTest and I don't want to export the class.</p>
<p>I tried using the same <em>Intermediate Directory</em> for both projects (so object files are in the same directory) and using the References feature of VS2005 (right click project --> References --> Add New Reference...), but it didn't work - I still get a linking error (LNK2001).</p>
<p><strong>Edit:</strong> I don't want to have the same source file in two projects - consider the face that I have many MyClass/MyClassTest, which means I have to duplicate each MyClass to a different project.
I know it is possible to use the same object file in two projects, I've seen it done before but forgot how.</p>
<p><strong>Edit:</strong> I've decided to put the files in both projects, so they are compiled twice. It turns out the "Reference" feature works automatically - but only for static lib projects.</p>
|
<p>I don't understand why you don't want to build it in your dll project. As long as both projects are using the same source file, they will both generate the same object file (assuming compiler options are set the same way).</p>
<p>If you want to test the dll without exporting the class itself (I presume this is because exporting classes in a dll is usually a bad idea), consider exporting a "factory" function from the dll. It would have a signature like:</p>
<pre><code>extern "C" MyClass *CreateMyClass();
</code></pre>
<p>This function would create an object of MyClass and return a pointer to it. Your unit test can then do whatever it needs with the returned class object.</p>
|
<p>I think you also need to explicitly add the .obj file to your list of additional dependencies in your project linker settings.</p>
| 32,699
|
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p>
<p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p>
<p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
|
<p>I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:</p>
<pre><code>def serve_forever(self):
"""Handle one request at a time until doomsday."""
while 1:
self.handle_request()
</code></pre>
<p>You could replace (in subclass) <code>while 1</code> with <code>while self.should_be_running</code>, and modify that value from a different thread. Something like:</p>
<pre><code>def stop_serving_forever(self):
"""Stop handling requests"""
self.should_be_running = 0
# Make a fake request to the server, to really force it to stop.
# Otherwise it will just stop on the next request.
# (Exercise for the reader.)
self.make_a_fake_request_to_myself()
</code></pre>
<p>Edit: I dug up the actual code I used at the time:</p>
<pre><code>class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
stopped = False
allow_reuse_address = True
def __init__(self, *args, **kw):
SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
self.register_function(lambda: 'OK', 'ping')
def serve_forever(self):
while not self.stopped:
self.handle_request()
def force_stop(self):
self.server_close()
self.stopped = True
self.create_dummy_request()
def create_dummy_request(self):
server = xmlrpclib.Server('http://%s:%s' % self.server_address)
server.ping()
</code></pre>
|
<p>Here's a context-flavored version for Python 3.7+ which I prefer because it cleans up automatically <em>and</em> you can specify the directory to serve:</p>
<pre><code>from contextlib import contextmanager
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
@contextmanager
def http_server(host: str, port: int, directory: str):
server = ThreadingHTTPServer(
(host, port), partial(SimpleHTTPRequestHandler, directory=directory)
)
server_thread = Thread(target=server.serve_forever, name="http_server")
server_thread.start()
try:
yield
finally:
server.shutdown()
server_thread.join()
def usage_example():
import time
with http_server("127.0.0.1", 8087, "."):
# now you can use the web server
time.sleep(100)
</code></pre>
| 33,718
|
<p>In another question on SO I answered with code like the one below and got a comment that the LINQ-query probably was evaluated in every iteration of the for/each. Is that true?</p>
<p>I know that LINQ-querys does not executes before its items is evaluated so it seems possible that this way to iterate the result can make it run on every iteration? </p>
<pre><code>Dim d = New Dictionary(Of String, String)()
d.Add("Teststring", "Hello")
d.Add("1TestString1", "World")
d.Add("2TestString2", "Test")
For Each i As String In From e In d Where e.Value.StartsWith("W") Select e.Key
MsgBox("This key has a matching value:" & i)
Next
</code></pre>
|
<p>NO... in a foreach, the "GetEnumerator" is called only once (ever), and that is used going forward.</p>
<p>EDIT: I put a statement here about the result set being stored temporarily... that's only true for some cases... not this one, so I took it out.</p>
<p>EDIT: Please forgive this for being overly verbose... but I wanted to <em>show</em> you what is happening... so here's a Console app :)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foreach (string item in MyCustomEnumerator()
.Where(item => item.StartsWith("abc")))
{
Console.WriteLine(item);
}
}
static IEnumerable<string> MyCustomEnumerator()
{
Console.WriteLine(DateTime.Now);
yield return "abc1";
Console.WriteLine(DateTime.Now);
yield return "abc2";
Console.WriteLine(DateTime.Now);
yield return "abc3";
Console.WriteLine(DateTime.Now);
yield return "xxx";
}
}
}
</code></pre>
<p>EDIT: This will result in a DateTime, then abc1, then a DateTime, then abc2, then a DateTime, then abc3, then a DateTime.</p>
|
<p>I looked up the FOR EACH...NEXT statement and it seems like Visual Basic evaluates the collection only once, before the loop begins, so it should not run the query on every iteration.</p>
<blockquote>
<p>Number of Iterations. Visual Basic
evaluates the collection only once,
before the loop begins. If your
statement block changes element or
group, these changes do not affect the
iteration of the loop.</p>
</blockquote>
| 43,142
|
<p>I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage.</p>
<p>I created a task to run under my admin user, and to start the program, <em>cmd</em> with the arguments <em>/c net start mssqlserver</em>. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:</p>
<p><em>action "C:\Windows\system32\cmd.EXE" with return code 2</em>.</p>
<p>Any suggestions?</p>
|
<p>Use an enum:</p>
<pre><code>public enum Foo {
INSTANCE;
}
</code></pre>
<p>Joshua Bloch explained this approach in his <a href="http://sites.google.com/site/io/effective-java-reloaded" rel="noreferrer">Effective Java Reloaded</a> talk at Google I/O 2008: <a href="http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s" rel="noreferrer">link to video</a>. Also see slides 30-32 of his presentation (<a href="https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0" rel="noreferrer">effective_java_reloaded.pdf</a>):</p>
<blockquote>
<h3>The Right Way to Implement a Serializable Singleton</h3>
<pre><code>public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
</code></pre>
</blockquote>
<p><strong>Edit:</strong> An <a href="http://www.ddj.com/java/208403883?pgno=3" rel="noreferrer">online portion of "Effective Java"</a> says: </p>
<blockquote>
<p>"This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, <strong>a single-element enum type is the best way to implement a singleton</strong>."</p>
</blockquote>
|
<p>Sometimes a simple "<strong><code>static Foo foo = new Foo();</code></strong>" is not enough. Just think of some basic data insertion you want to do.</p>
<p>On the other hand you would have to synchronize any method that instantiates the singleton variable as such. Synchronisation is not bad as such, but it can lead to performance issues or locking (in very very rare situations using this example. The solution is</p>
<pre><code>public class Singleton {
private static Singleton instance = null;
static {
instance = new Singleton();
// do some of your instantiation stuff here
}
private Singleton() {
if(instance!=null) {
throw new ErrorYouWant("Singleton double-instantiation, should never happen!");
}
}
public static getSingleton() {
return instance;
}
}
</code></pre>
<p>Now what happens? The class is loaded via the class loader. Directly after the class was interpreted from a byte Array, the VM executes the <strong>static { }</strong> - block. that's the whole secret: The static-block is only called once, the time the given class (name) of the given package is loaded by this one class loader.</p>
| 9,613
|
<p>Using groovy, would you expect better performance in terms of speed and memory overhead to read and query JSON vs XML? </p>
|
<p>JSON is smaller and simpler than XML. I'd bet that JSON is faster to parse.</p>
<p>YAML would be faster still.</p>
|
<p>XML has a bit more overhead than JSON because of the angle brackets and extra information and what not. Any good parser should be able to parse JSON faster than XML for this reason.</p>
| 21,721
|
<p>The <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="nofollow noreferrer">C# 3.0 spec</a> has the following code example in section 10.6.1.3 "Output parameters":</p>
<pre><code>using System;
class Test
{
static void SplitPath(string path, out string dir, out string name) {
int i = path.Length;
while (i > 0) {
char ch = path[i – 1];
if (ch == '\\' || ch == '/' || ch == ':') break;
i--;
}
dir = path.Substring(0, i);
name = path.Substring(i);
}
static void Main() {
string dir, name;
SplitPath("c:\\Windows\\System\\hello.txt", out dir, out name);
Console.WriteLine(dir);
Console.WriteLine(name);
}
}
</code></pre>
<p>I cannot get this code to compile in VS2005/C#2.0. Did the behavior of strings in C# 3.0 change so that a string can be referred as a char[] array without explicitly converting it (the statement "ch = path[i - 1]")?</p>
|
<p>It is an invalid character '–'. Change '–' to '-'</p>
|
<p>According MSDN ( <a href="http://msdn.microsoft.com/en-us/library/362314fe(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/362314fe(VS.71).aspx</a> ) this was even possible in .net 1.1 you can of course have a</p>
<p>string myString = "Filip Ekberg";</p>
<p>And then access the first char by doing myString[0]</p>
| 43,885
|
<p>Are there any open source algorithms in c# that solve the problem of creating a difference between two text files?</p>
<p>It would be super cool if it had some way of highlighting what exact areas where changed in the text document also.</p>
|
<p>There is <a href="http://www.menees.com/Diff.Net.htm" rel="nofollow noreferrer">Menees Diff</a> which will provide you with a C# diff implementation. The source code is included. I've used it in the past with good success wrapping it in my own implemenation.</p>
|
<p>Check out <a href="http://en.wikipedia.org/wiki/Diff" rel="noreferrer">diff</a>. Here it is <a href="http://www.gnu.org/software/diffutils/diffutils.html" rel="noreferrer">in the gnu project</a> (open source, of course), and many more links to implementations are found in the wikipedia article. A comparison of different such programs is found <a href="http://en.wikipedia.org/wiki/Comparison_of_file_comparison_tools" rel="noreferrer">here</a>.</p>
| 9,096
|
<p>How do you handle database exceptions in your application?<br>
Are you trying to validate data prior passing it to DB or just relying on DB schema validation logic?<br>
Do you try to recover from some kind of DB errors (e.g. timeouts)?</p>
<p>Here are some approaches:</p>
<ol>
<li>Validate data prior passing it to DB</li>
<li>Left validation to DB and handle DB exceptions properly</li>
<li>Validate on both sides</li>
<li>Validate some obvious constraints in business logic and left complex validation to DB </li>
</ol>
<p>What approach do you use? Why?</p>
<p><strong>Updates:</strong> </p>
<p>I'm glad to see growing discussion.<br>
Let’s try to sum up community answers. </p>
<p>Suggestions: </p>
<ul>
<li>Validate on both sides</li>
<li>Check business logic constraints on
client side, let DB do integrity checks <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39406">from hamishmcn</a></li>
<li>Check early to avoid bothering DB <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39461">from ajmastrean</a></li>
<li>Check early to improve user experience <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39428">from Will</a></li>
<li>Keep DB interacting code in place to
simplify development <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39406">from hamishmcn</a></li>
<li>Object-relational mapping (NHibernate, Linq, etc.) can help you to deal with constrains <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39461">from ajmastrean</a></li>
<li>Client side validation is necessary for security reasons <a href="https://stackoverflow.com/questions/39371/database-exception-handling-best-practices#39487">from Seb Nilsson</a></li>
</ul>
<p>Do you have anything else to say? This is converted to Validation specific question. We are missing the core, i.e. "Database related Error best practices" which ones to handle and Which ones to Bubble up?</p>
|
<p>@aku: DRY is nice, but its not always possible. Validation is one of those places, as you will have three completely different and unrelated places where validation is not only possible but absolutely needed: Within the UI, within the business logic, and within the database.</p>
<p>Think of a web application. You want to reduce trips to the server, so you include javascript validation of client data entry. But you can't trust what the user enters, so you must perform validation within your business logic before touching the database. And the database must have its own validation in order to prevent data corruption. </p>
<p>There's no clean way to unify these three different types of validation within a single component. </p>
<p>There are some attempts being made to unify cross-cutting responsibilities like validation within policy injectors like the P&P group's <a href="http://blogs.msdn.com/tomholl/archive/2007/02/23/announcing-the-policy-injection-application-block.aspx" rel="noreferrer">Policy Injection Application Block</a> combined with their <a href="http://rds.yahoo.com/_ylt=A0geu.w0Or1ImvQAR19XNyoA;_ylu=X3oDMTBybnZlZnRlBHNlYwNzcgRwb3MDMQRjb2xvA2FjMgR2dGlkAw--/SIG=13f2oa1b9/EXP=1220447156/**http%3a//blogs.msdn.com/tomholl/archive/2006/11/27/validation-application-block-revealed.aspx" rel="noreferrer">Validation Application Block</a>, but these are still code based. If you have validation that's not in code, you still have to maintain parallel logic separately...</p>
|
<p>The sorts of apps that I was writing (I've since moved jobs) were in-house fat-client apps.<br>
I would try to keep the business logic in the client, and do more mechanical validation on the db (ie validation that only related to the procedure's ability to run, as opposed to higher level validation).<br>
In short, validate where you can, and try to keep related types of validation together.</p>
| 6,039
|
<p>I want something like an <a href="http://en.wikipedia.org/wiki/Map_%28C++%29" rel="nofollow noreferrer">std::map</a>, but I only want to see if the item exists or not, I don't actually need a key AND a value. What should I use?</p>
|
<p>Looks like you need a <a href="http://en.cppreference.com/w/cpp/container/set" rel="nofollow noreferrer">std::set</a>.</p>
|
<p>You can keep using std::map for the desired purpose.</p>
<p>To check if a particular item (of key type) exists in the map or not, you can use following code:</p>
<pre><code>if (mapObj.count(item) != 0)
{
// item exists
}
</code></pre>
<p>As answered earlier, std::set will do the job as well. Interestingly both, set and map are represented as Trees internally.</p>
| 15,193
|
<p>I have Swing java application with network communications to several "Players" that are represented as player objects, each with their own communication thread. The app has a "Team" object managing all player objects. Several UI components listen to events passed from the players through the Team object. </p>
<p>In my design, the team object fires all events on the Swing thread using invokeLater, so that the rest of my application does not need to bother with threading issues. However, I don't know how I can test the Team class in a JUnit test.</p>
<p>A little more background. At first I had the Team object fire its events on the player object threads (no thread switching at all). The Team unit test succeeded, but I got into many threading issues in my UI with invokeLaters and synchronized all over the place. I then decided to simplify the threading model by having the Team object fire events on the Swing thread, but now the Team unit test fails because it does not receive the events. What to do?</p>
<p>A solution that comes to mind is to introduce an extra object on top of Team that does the thread switch and keep the original unit test intact, but I do not like the idea of introducing complexity in production code just to make a unit test succeed.</p>
|
<p>Maybe you can use easymock to isolate the classes you want to test, and have the mock objects receive the events and check that they're fired.</p>
<p>I'd recommend EasyMock: <a href="http://www.easymock.org/" rel="nofollow noreferrer">http://www.easymock.org/</a></p>
<p>From your story it feels that your unittests are more integration tests, and very intricate. If that's the case, try to simplify and isolate. You've probably read <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm" rel="nofollow noreferrer">http://junit.sourceforge.net/doc/testinfected/testing.htm</a></p>
<p>I hope this helps.</p>
|
<p>Maybe you can use easymock to isolate the classes you want to test, and have the mock objects receive the events and check that they're fired.</p>
<p>I'd recommend EasyMock: <a href="http://www.easymock.org/" rel="nofollow noreferrer">http://www.easymock.org/</a></p>
<p>From your story it feels that your unittests are more integration tests, and very intricate. If that's the case, try to simplify and isolate. You've probably read <a href="http://junit.sourceforge.net/doc/testinfected/testing.htm" rel="nofollow noreferrer">http://junit.sourceforge.net/doc/testinfected/testing.htm</a></p>
<p>I hope this helps.</p>
| 42,670
|
<p>Can any one explain why the output of this code is only 'hello' and what this code means?</p>
<pre><code>( 0, characterArray, 0, characterArray.Length );
</code></pre>
<p>The output is showing:</p>
<p><PRE>The character array is: hello</PRE></p>
<p>The code follows:</p>
<pre><code>string string1 = "hello there";
char[] characterArray = new char[ 5 ];
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < characterArray.Length; i++ )
Console.Write( characterArray[ i ] );
</code></pre>
|
<p>It's because your array is only set for 5 characters. Expand it to 11 and it will work.</p>
<p>Here is what the Copyto is:</p>
<pre><code>public void CopyTo(
int sourceIndex,
char[] destination,
int destinationIndex,
int count
)
</code></pre>
<pre>
Parameters
sourceIndex
Type: System..::.Int32
A character position in this instance.
destination
Type: array[]()[]
An array of Unicode characters.
destinationIndex
Type: System..::.Int32
An array element in destination.
count
Type: System..::.Int32
The number of characters in this instance to copy to destination.
</pre>
<p>Taken from: <a href="http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx</a></p>
|
<p>That's because your character array size is only 5. if you want the whole string as an array, you can you string.ToCharArray instead</p>
| 46,051
|
<p>One of the nice feature of the Image control is that we can specified an Uri as the ImageSource and the image is automatically downloaded for us. This is great! <strong>However, the control doesn't seem to have a property indicating if the image loading is in progress or not.</strong></p>
<p>Is there a property telling us the status (Downloading, Downloaded, etc.) of the Image control?</p>
<p>Thanks!</p>
|
<p>As long as your ImageSource is a BitmapImage you could use the BitmapImage.DownloadCompleted event. The only problem I have found so far is that it only works from C#, so you would lose some flexibility. I'm guessing you could access that event from XAML, but I'm not sure how. The following sample starts loading the image with the click of a button, and updates a label when the image finished loading.</p>
<p>XAML:</p>
<pre><code><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="50" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Image x:Name="image" Grid.Row="2"/>
<Label x:Name="label" Content="aaa" Grid.Row="1" />
<Button Click="Button_Click" Content="Click to load image" Grid.Row="0" />
</Grid>
</code></pre>
<p>Code:</p>
<pre><code>private void Button_Click(object sender, RoutedEventArgs e)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.DecodePixelHeight = 100;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.UriSource = new Uri("bigImageUri");
bi.EndInit();
bi.DownloadCompleted += new EventHandler(bi_DownloadCompleted);
image.Source = bi;
}
void bi_DownloadCompleted(object sender, EventArgs e)
{
label.Content = "dl completed";
}
</code></pre>
<p>Hope it helps!</p>
|
<p>Hmm - that's a good question. I looked at the ImageSource class's documentation on MSDN, and it doesn't look like there is anything on there to get that information.</p>
<p>That being said, could you start the download manually and set the Image control's Source property once that download finishes? You'd know for sure if the download was completed...</p>
| 42,713
|
<p>What is a good free library for editing MP3s/FLACs. </p>
<p>By editing I mean:</p>
<ul>
<li>Cutting audio file into multiple parts</li>
<li>Joining multiple audio files together</li>
<li>Increase playback speed of file without affecting the pitch (eg. podcasts up to 1.3x)</li>
<li>Re-encoding audio file from Flac -> MP3 or vice versa</li>
</ul>
<p>I don't mean software, I mean a library that I can use within another application. Programming language agnostic.</p>
|
<p>Just about every language has bindings to C, so you'll probably want to get the applicable C libraries for encoding/decoding mp3's and FLAC files. This list might include</p>
<p>libFLAC <a href="http://flac.sourceforge.net/api/index.html" rel="nofollow noreferrer">http://flac.sourceforge.net/api/index.html</a> FLAC encoding/decoding<br>
LAME <a href="http://lame.sourceforge.net/index.php" rel="nofollow noreferrer">http://lame.sourceforge.net/index.php</a> MP3 encoding<br>
MAD <a href="http://www.underbit.com/products/mad/" rel="nofollow noreferrer">http://www.underbit.com/products/mad/</a> MP3 decoding </p>
<p>The rest of your signal processing needs could be gathered around a single popular API such as LADSPA <a href="http://www.ladspa.org/" rel="nofollow noreferrer">http://www.ladspa.org/</a>.</p>
<p>Here's a stretching / pitch shifting library: <a href="http://www.breakfastquay.com/rubberband/" rel="nofollow noreferrer">http://www.breakfastquay.com/rubberband/</a></p>
<p>Most audio processing programs have a certain internal format they use. That keeps things simple. Everything coming in gets converted to the same format. Once you've standardized the internal format, cutting and splicing audio data is about as difficult as cutting and splicing strings. You don't really need a library for that.</p>
|
<p>I use <a href="http://audacity.sourceforge.net/" rel="nofollow noreferrer">Audacity</a> for all my editing needs</p>
<blockquote>
<p>Audacity is a free, easy-to-use audio
editor and recorder for Windows, Mac
OS X, GNU/Linux and other operating
systems. You can use Audacity to:</p>
<pre><code>* Record live audio.
* Convert tapes and records into digital recordings or CDs.
* Edit Ogg Vorbis, MP3, WAV or AIFF sound files.
* Cut, copy, splice or mix sounds together.
* Change the speed or pitch of a recording.
</code></pre>
</blockquote>
| 3,986
|
<p>If you create an ASP.NET web file project you have direct access to the Profile information in the web.config file. If you convert that to a Web App and have been using ProfileCommon etc. then you have to jump through a whole bunch of hoops to get your web app to work.</p>
<p>Why wasn't the Profile provider built into the ASP.NET web app projects like it was with the web file projects?</p>
|
<p>The profile provider uses the ASP.NET Build Provider system, which doesn't work with Web Application Projects.</p>
<blockquote>
<p>Adding a customized BuildProvider
class to the Web.config file works in
an ASP.NET Web site but does not work
in an ASP.NET Web application project.
In a Web application project, the code
that is generated by the BuildProvider
class cannot be included in the
application.</p>
</blockquote>
<p>source: <a href="http://msdn.microsoft.com/en-us/library/system.web.compilation.buildprovider.aspx" rel="nofollow noreferrer">MSDN Build Provider documentation</a></p>
|
<p>Actually, Microsoft does have a solution for this known issue.
It's the "Web Profiler Builder". I used it for my Web App and it works great.
<a href="http://code.msdn.microsoft.com/WebProfileBuilder/Release/ProjectReleases.aspx?ReleaseId=980" rel="nofollow noreferrer">http://code.msdn.microsoft.com/WebProfileBuilder/Release/ProjectReleases.aspx?ReleaseId=980</a></p>
| 3,366
|
<p>The following is a question I asked on my blog a few months back but I still haven't got a proper answer to. Then a couple of days ago I was asked if I had the answer so I decided to copy the question in here where it will get a much more exposure by willing-and-able developers. Anyways, here goes...</p>
<hr>
<p>I have been working on an ASP.NET web application that utilizes the <a href="http://www.codeplex.com/AtlasControlToolkit" rel="nofollow noreferrer">AJAX Control Toolkit</a> controls to extend the usability of the application. In addition, the application is a serious business application that requires security, including encryption, authentication and authorization. And the HTTP session is an InProc mode session that expires in the default time of 20 minutes.</p>
<p>This of course means that if the user leaves a page on his browser for over 20 minutes the session has expired and any post back to the server will redirect the browser to the sign in page. However, if the page, for example, contains the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/" rel="nofollow noreferrer">AutoCompleteExtender</a> control from the <a href="http://www.codeplex.com/AtlasControlToolkit" rel="nofollow noreferrer">AJAX Control Toolkit</a>, the user might get back to his browser and start using the extender's functionality, requiring behind the scene callbacks, but will realize that the control simply doesn't work - no error not redirection to the sign in page!?</p>
<hr>
<p>Like I said, I don't have a solution so I ended up putting the <a href="http://www.imaginativeuniversal.com/ct.ashx?id=78b1cd2d-5352-4845-b381-6ac2c4b07c44&url=http%3a%2f%2fwww.imaginativeuniversal.com%2fSessionExpiredMonitorWithASPNETAJAX.aspx" rel="nofollow noreferrer">SessionExpiredMonitor</a> (by Herr <a href="http://www.imaginativeuniversal.com/ASPNETAJAXServerControlsAndExtenders.aspx" rel="nofollow noreferrer">Ziffer</a>) on all my pages (in my MasterPage), which results in every page auto signing out in 19 minutes and then redirecting the browser to the sign in page. However, I don't find this to be a solution so if you can figure this out then please let me know. Thank you very much.</p>
|
<p>On the server side you can detect that the session is expired and return a strong typed exception. On the browser side, you can specifically detect for that error and simply have the page refresh. This assumes that when your page posts back for the refresh that your application detects expired sessions and has them login again.</p>
|
<p>What's wrong with redirecting the user to the login page after his session actually expired? From a user point of view I do really prefer this over not noticing an expired session, filling out some way too long form and actually notice the expiration on submit.
It's at least a very user friendly solution to the problem.</p>
| 32,101
|
<p>Thanks for reading this.</p>
<p>I am dynamically generating some data which includes a select drop-down with a text box next to it. If the user clicks the select, I am dynamically populating it (code below). I have a class on the select and I was hoping the following code would work. I tested it with an ID on the select and putting the ONE on the ID I got it to work. However, in changing the code to reference a class (since there will be multiple data groups that include a select with a text box next to it) and <code>$(this)</code>, I could not get it to work. Any ideas would be helpful. Thanks</p>
<p>The relevance of the text box next to the select is the second part of the code...to update the text box when an option is selected in the select</p>
<p><code>.one</code> is so the select is updated only once, then the <code>.bind</code> allows any options selected to be placed in the adjacent text box.</p>
<pre><code>$('.classSelect').one("click",
function() {
$.ajax({
type: "post",
url: myURL ,
dataType: "text",
data: {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
},
success:
function(request) {
$(this).html(request); // populate select box
} // End success
}); // End ajax method
$(this).bind("click",
function() {
$(this).next().val($(this).val());
}); // End BIND
}); // End One
<select id="mySelect" class="classSelect"></select>
<input type="text">
</code></pre>
|
<p><code>$(this)</code> is only relevant within the scope of the function. outside of the function though, it loses that reference:</p>
<pre><code>$('.classSelect').one("click", function() {
$(this); // refers to $('.classSelect')
$.ajax({
// content
$(this); // does not refer to $('.classSelect')
});
});
</code></pre>
<p>a better way to handle this may be:</p>
<pre><code>$('.classSelect').one("click", function() {
var e = $(this);
$.ajax({
...
success : function(request) {
e.html(request);
}
}); // end ajax
$(this).bind('click', function() {
// bind stuff
}); // end bind
}); // end one
</code></pre>
<p>by the way, are you familiar with the <a href="http://docs.jquery.com/Ajax/load" rel="noreferrer"><code>load()</code></a> method? i find it easier for basic ajax (as it acts on the wrapped set, instead of it being a standalone function like <code>$.ajax()</code>. here's how i would rewrite this using <code>load()</code>:</p>
<pre><code>$('.classSelect').one('click', function() {
var options = {
type : 'post',
dataType : 'text',
data : {
'_service' : myService,
'_program' : myProgram ,
'param' : myParams
}
} // end options
// load() will automatically load your .classSelect with the results
$(this).load(myUrl, options);
$(this).click(function() {
// etc...
}); // end click
}); // end one
</code></pre>
|
<p>That is matching one select. You need to match multiple elements so you want</p>
<pre><code>$("select[class='classSelect']") ...
</code></pre>
| 37,161
|
<p>I'm looking for a good ssh console plugin for Eclipse, and can't find much at all. Would anyone have some good leads on one?</p>
|
<p>In Eclipse 3.4.1, there is the Remote Systems Explorer perspective that allows you to create and connect to SSH terminals (<a href="http://www.eclipse.org/dsdp/tm/tutorial/" rel="noreferrer">here</a>)</p>
|
<p>You can also try the <a href="https://code.google.com/p/elt/" rel="nofollow">Terminal plug-in for Eclipse</a></p>
<blockquote>
<p>This plug-in provides a fully-working, command-line terminal to
Eclipse 3.7 or later (yes, even 4.2!) It works on Linux and MacOS
only.</p>
</blockquote>
<p>More info at: <a href="http://alexruiz.developerblogs.com/?p=2428" rel="nofollow">http://alexruiz.developerblogs.com/?p=2428</a></p>
| 43,348
|
<p>Heavy emphasis on simple. I've never made an installer and I'd rather not have to learn much. A system that I could hand a pile of files to and it would make some smart guesses about where to put them would be ideal.</p>
<p>Go ahead and answer the general question.</p>
<p>However In my cases I'm stuck with some extra constraints. The program to be installed is written in VB6 (or is it 5?) and a few previous versions of VB, so it's <em>not</em> going to be updated any time soon. I have a running install and will have a Clean VM to play with So I'll be doing a loop of: run the install, find where it's broken, fix it, add that to the installer, revert the VM, try again. If anyone has a better approach I'm open to suggestions.</p>
<p>I <em>MUST</em> get it working on XP and I'd really like to also have something that will work on newer versions of Windows as well.</p>
|
<p><a href="http://www.jrsoftware.org/" rel="noreferrer">InnoSetup</a> or <a href="http://nsis.sourceforge.net/" rel="noreferrer">NSIS</a>, whichever seems easier to you. <a href="http://www.istool.org" rel="noreferrer">ISTool</a> is a nice GUI tool for InnoSetup which makes creating setup scripts even easier.</p>
|
<p>My advice is this. Try to keep the installer as simple as possible. Windows Installer is a very complicated piece of software and when things don't work right it can be hard to figure out what's going on. I'm sure we have all experienced the endless loop of Windows Installer trying to repair a file that you no longer have the source .msi file for.</p>
<p>Most of the time using Windows Installer is like using a sledge hammer to crack a nut.</p>
<p>I use InnoSetup for my own stuff and InstallShield at work (against my will). Start with a simple script based installer and only use Windows Installer if you have a good reason to.</p>
<p>Note that support for installing assemblies to the GAC may be missing for some non Windows Installer setup tools (such as InnoSetup).</p>
| 4,366
|
<p>I am in need of a way to mute a specific application in Vista.</p>
<p>Example: Mute just Firefox, but not all of the other application. Much similar to muting a specific program from within the volume mixer in vista. </p>
<p>If there is a program that will do this, i would appreciate that. Otherwise if there is a way to do this, I will write a small app(Preferrably something .net).</p>
<p>EDIT: I want to automate this procedure, possibly key-map it.</p>
|
<p>I suggest using the built in Mixer in Vista...</p>
<p>Why do you want to use an 3rd party program?</p>
|
<p>Using AutoHotkey, this works even better than expected! Just a fast window flash and BOOM, done.
Src: <a href="http://feebdack.com/knob/how_to_mute_a_single_application" rel="nofollow">http://feebdack.com/knob/how_to_mute_a_single_application</a></p>
<pre><code>#NoEnv ;// Recommended for new scripts
#Persistent ;// Recommended for new scripts
SendMode Input ;// Recommended for new scripts
SetTitleMatchMode 2
;// Set VolumeMute to only silence Media Center
$f3::
MuteMediaCenter()
return
MuteMediaCenter()
{
;// Open mixer
Run sndvol
WinWait Volume Mixer
;// Mute Standard Media Center Process
appName = Chrome
MuteApp(appName)
;// Mute Netflix Media Center Process
appName = Firefox
MuteApp(appName)
WinClose Volume Mixer
}
;// Volume Mixer must exist
MuteApp(appName)
{
;// Find X position & width of textblock with text matching our appName
ControlGetPos, refX, , refW, , % appName, Volume Mixer
;// Find button with left side within the width of the textblock
x = -1
while ( x != "")
{
;// A_Index is current loop iteration→used to find id
tbIDX := (A_Index * 2)
ControlGetPos, x, , , , ToolbarWindow32%tbIDX%, Volume Mixer
diff := x - refX
if (diff > 0 && diff < refW)
{
;// msgbox diff: %diff% refX: %refX% tbIDX: %tbIDX% x: %x% A_Index: %A_Index%
ControlClick, ToolbarWindow32%tbIDX%, Volume Mixer
break
}
}
}
</code></pre>
| 6,297
|
<p>Is this possible? I had troubles with SVN clients not being able to access the repository with the following error message:</p>
<blockquote>
<p>Repository moved permanently to '<a href="http://svn.example.com/test/" rel="noreferrer">http://svn.example.com/test/</a>'; please relocate</p>
</blockquote>
<p>If I added the '/' to the end of the path I was trying to access, it just strips it off again, and shows the same error message. My configuration file looks like:</p>
<pre><code><VirtualHost *>
ServerName svn.example.com
# Normal VirtualHost stuff here
<Location /svn>
# Uncomment this to enable the repository
DAV svn
SVNParentPath /some/path/to/repositories
# Setup mod_authz_svn, etc, etc here
</Location>
</VirtualHost>
</code></pre>
<p>Note: This works. But if I change the Location to just <code>/</code> it stops working again with the error above. Is it possible to use the root directory, or am I missing something here? Firefox displays the repository listing fine when serving the repositories out of the root.</p>
<p>As someone else pointed out, this only seems to be an issue inside named virtual hosts... Anyone have any smart ideas why?</p>
|
<p>The problem is that you are using the document root also as the repository root (I'm not blaming you, this should just work, but it doesn't).</p>
<p>Try pointing the <code>DocumentRoot</code> and <code>SVNParentPath</code> directives to different physical locations, so the resulting config file should look like this (abbreviated):</p>
<pre><code><VirtualHost *:80>
DocumentRoot /home/svn.example.com/docroot
<Location />
SVNParentPath /home/svn.example.com/svnroot
SVNListParentPath on
</Location>
</VirtualHost>
</code></pre>
<p>Also, as @Nigel Jewell says, remove that Rewrite block, for sanity.</p>
|
<pre><code>This is working for me:
<Location />
DAV svn
SVNPath /repository
AuthType Basic
AuthName "Repository authentication"
AuthUserFile /repository/.svn-auth
AuthzSVNAccessFile /repository/.svn-access
Satisfy All
Require valid-user
</Location>
</code></pre>
<p>Pointing the browser to <a href="http://127.0.0.1" rel="nofollow noreferrer">http://127.0.0.1</a> shows me the repository content.</p>
| 33,158
|
<p>I want to set a breakpoint on the <code>__DoPostBack</code> method, but it's a pain to find the correct file to set the breakpoint in.</p>
<p>The method <code>__DoPostBack</code> is contained in an auto-generated js file called something like: </p>
<pre><code>ScriptResource.axd?d=P_lo2...
</code></pre>
<p>After a few post-backs visual studio gets littered with many of these files, and it's a bit of a bear to check which one the current page is referencing. Any thoughts?</p>
|
<p>How about this one <a href="http://sourceforge.net/projects/sqlitebrowser/" rel="nofollow noreferrer">http://sourceforge.net/projects/sqlitebrowser/</a>:</p>
<blockquote>
<p>SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface.</p>
</blockquote>
|
<p>Sourceforge has a help wanted page: <a href="http://sourceforge.net/people/" rel="nofollow noreferrer">http://sourceforge.net/people/</a></p>
<p>browse the postings to see if a project is in your expertise or find one that sound interesting...</p>
<p>And let me be the first to say thank you for being willing to contribute your time and knowlede to the open source movement.</p>
| 10,265
|
<p>I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:</p>
<p>Message<br>
-- TextMessage<br>
-------- InvitationTextMessage<br>
-- EmailMessage<br>
-------- InvitationEmailMessage </p>
<p>The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. </p>
<p>What's the most light-weight approach to solve the issue? </p>
<p>Thanks!</p>
|
<p>Alex, most of the times you need multiple inheritance is a signal your object structure is somewhat incorrect. In situation you outlined I see you have class responsibility simply too broad. If Message is part of application business model, it should not take care about rendering output. Instead, you could split responsibility and use MessageDispatcher that sends the Message passed using text or html backend. I don't know your code, but let me simulate it this way:</p>
<pre><code>$m = new Message();
$m->type = 'text/html';
$m->from = 'John Doe <jdoe@yahoo.com>';
$m->to = 'Random Hacker <rh@gmail.com>';
$m->subject = 'Invitation email';
$m->importBody('invitation.html');
$d = new MessageDispatcher();
$d->dispatch($m);
</code></pre>
<p>This way you can add some specialisation to Message class:</p>
<pre><code>$htmlIM = new InvitationHTMLMessage(); // html type, subject and body configuration in constructor
$textIM = new InvitationTextMessage(); // text type, subject and body configuration in constructor
$d = new MessageDispatcher();
$d->dispatch($htmlIM);
$d->dispatch($textIM);
</code></pre>
<p>Note that MessageDispatcher would make a decision whether to send as HTML or plain text depending on <code>type</code> property in Message object passed.</p>
<pre><code>// in MessageDispatcher class
public function dispatch(Message $m) {
if ($m->type == 'text/plain') {
$this->sendAsText($m);
} elseif ($m->type == 'text/html') {
$this->sendAsHTML($m);
} else {
throw new Exception("MIME type {$m->type} not supported");
}
}
</code></pre>
<p>To sum it up, responsibility is split between two classes. Message configuration is done in InvitationHTMLMessage/InvitationTextMessage class, and sending algorithm is delegated to dispatcher. This is called Strategy Pattern, you can read more on it <a href="https://web.archive.org/web/20190613203216/https://www.dofactory.com/net/strategy-design-pattern" rel="nofollow noreferrer">here</a>.</p>
|
<p>How about an Invitation class right below the Message class?</p>
<p>so the hierarchy goes:</p>
<p>Message<br>
--- Invitation<br>
------ TextMessage<br>
------ EmailMessage </p>
<p>And in Invitation class, add the functionality that was in InvitationTextMessage and InvitationEmailMessage. </p>
<p>I know that Invitation isn't really a type of Message, it's more a functionality of Message. So I'm not sure if this is good OO design or not.</p>
| 11,631
|
<p>It's been suggested that this might be a reasonable approach, in order to minimize changes to an existing server configurations, but is it actually valid/supported? I've not been able to find anything specific either way.</p>
<p>In practice, with a JBoss Portal V2.4.2 server, there appears to be some class-loading issues, so things such as the downloadable Stripes example or a standard Wicket quickstart app don't run, but I'm not sure if the problem there is a server-specific one or a generic one - Anyone?</p>
<p>Note: This isn't about displaying/moving an existing web-app into a portal, simply if a Portal Server should also be a valid AppServer?</p>
|
<p><a href="http://jcp.org/en/jsr/detail?id=286" rel="nofollow noreferrer">JSR 286 (Portlet 2.0) spec</a>:</p>
<blockquote>
<p>PLT.2.7</p>
<p>Relationship with Java 2
Platform, Standard and Enterprise
Edition</p>
<p>The Portlet API v2.0 is based on the
Java Platform, Standard Edition 5.0
and Enterprise Edition v1.4. Portlet
containers should at least meet the
requirements, described in v 1.4 of
the J2EE Specification, for executing
in a J2EE environment.</p>
</blockquote>
<p>It is therefore not unreasonable to expect standard app-server applications to work under a portal.</p>
<p>However, by definition, a portal is going to include more libraries in the global class space. Adding libraries to the container always introduces the risk of incompatibility and the need to manage what classes/resources are exposed to your application and how (application-first class-loading, etcetera). I've had problems in the past with third part libraries whose dependencies conflicted with a version that shipped with the portal. I wouldn't expect dependency management to get any easier.</p>
<p>Write once, test everywhere, as they say.</p>
|
<p>I assume that the question has to do whether a standard web application can be rendered as a portlet from a Portlet container. This is not possible. The portlets need to be based on the GenericPortlet class and have special deployment descriptors. There is the JSR-168 standard, which specifies the requirements for the portal. The JSR-286 specification is on the way.</p>
<p>The only thing you could do is to create a portlet that will serve your existing application through an iframe, but this is of course ugly.</p>
<p>There is a free book for portlets called "<a href="http://www.manning.com/hepper/" rel="nofollow noreferrer">Portlets and Apache Portals</a>", which could be useful. Consult also the specification. This <a href="http://portlets.blogspot.com/" rel="nofollow noreferrer">blog spot</a> is interesting.</p>
| 47,327
|
<p>Has anyone used <a href="http://www.oracle.com/technetwork/middleware/coherence/overview/index.html" rel="nofollow noreferrer">Oracle Coherence</a>? It looks very promising at the roadshows.</p>
<p>My concern is whether it's a stable and robust enough to implement mission-critical financial solutions.</p>
<p>I'd be grateful for any feedback on its performance, robustness and ease of maintenance.</p>
|
<p>I've had first hand experience with Oracle Coherence at two big investment banks and can say it's definitely stable. However, as with any complex piece of software it's not without it's quirks.</p>
<p><b>EDIT:</b> Doh, just realised the question is over a year old. Oh well...</p>
|
<p>Oracle Coherence is a mature product, but you need to make sure that you have the latest patches from Oracle. The point releases that are downloadable from the Oracle website have many bugs that are fixed in the patch releases.</p>
<p>As for development and maintenance, the learning curve is a little steeper than the documentation would suggest. I recommend the Oracle training course (or Alek Seovic's book).</p>
| 15,379
|
<p>Here's my code (note that this was given by a friend):</p>
<pre><code>Private Sub Browse_Click()
Dim textfile As String
textfile = Space(255)
GetFileNameFromBrowseW Me.hWnd, StrPtr(sSave), 255, StrPtr("c:\"),
StrPtr("txt"), StrPtr("Apps (*.txt)" + Chr$(0) + "*.txt" + Chr$(0) +
"All files (*.*)" + Chr$(0) + "*.*" + Chr$(0)), StrPtr("Select File")
Text1 = Left$(textfile, lstrlen(textfile))
End Sub
</code></pre>
<p>Basically later on I edit the text file selected so later I call it just by using textfile in my function. However I get a path not found so I feel like I'm doing something wrong.
Thanks in advance.</p>
<p>Edit: All I want to do is select a text file, then later be able to call it and use it.</p>
|
<p>As shahkalpesh mentioned, you can access this functionality simply using a standard COM library.</p>
<p>In VB6, add the component:</p>
<ul>
<li>Project > Components</li>
<li>On the Controls tab, choose Microsoft Common Dialog Control 6.0 (SP6)</li>
</ul>
<p>Now on your form, add the new Common Dialog control from the toolbox</p>
<p>In code, you need:</p>
<pre><code>CommonDialog.Filter = "Apps (*.txt)|*.txt|All files (*.*)|*.*"
CommonDialog.DefaultExt = "txt"
CommonDialog.DialogTitle = "Select File"
CommonDialog.ShowOpen
'The FileName property gives you the variable you need to use
MsgBox CommonDialog.FileName
</code></pre>
|
<p>Maybe sSave contains a pathname, but textfile contains 255 spaces.</p>
| 36,832
|
<p>I'm currently using the module <code>URI::URL</code> to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?</p>
|
<p>The following code should work.</p>
<pre><code>$uri = URI->new_abs( $str, $base_uri )
</code></pre>
<p>You should also take a look at <a href="http://search.cpan.org/dist/URI/URI.pm" rel="nofollow noreferrer">the URI page on search.cpan.org</a>.</p>
|
<p>Perhaps I got the wrong end of the stick but wouldn't,</p>
<pre><code>$full_url = $base_url . $relative_url</code></pre>
<p>work? IIRC Perl text processing is pretty quick.</p>
<p><i>@lennysan</i> Ah sure yes of course. Sorry I can't help, my Perl is pretty rusty.</p>
| 4,649
|
<p>I need to store phone numbers in a table. Please suggest which datatype should I use?
<strong>Wait. Please read on before you hit reply..</strong></p>
<p>This field needs to be indexed heavily as Sales Reps can use this field for searching (including wild character search).</p>
<p>As of now, we are expecting phone numbers to come in a number of formats (from an XML file). Do I have to write a parser to convert to a uniform format? There could be millions of data (with duplicates) and I dont want to tie up the server resources (in activities like preprocessing too much) every time some source data comes through..</p>
<p>Any suggestions are welcome..</p>
<p>Update: <strong>I have no control over source data. Just that the structure of xml file is standard. Would like to keep the xml parsing to a minimum.
Once it is in database, retrieval should be quick. One crazy suggestion going on around here is that it should even work with Ajax AutoComplete feature (so Sales Reps can see the matching ones immediately). OMG!!</strong></p>
|
<p>Does this include:</p>
<ul>
<li>International numbers?</li>
<li>Extensions?</li>
<li>Other information besides the actual number (like "ask for bobby")?</li>
</ul>
<p>If all of these are no, I would use a 10 char field and strip out all non-numeric data. If the first is a yes and the other two are no, I'd use two varchar(50) fields, one for the original input and one with all non-numeric data striped and used for indexing. If 2 or 3 are yes, I think I'd do two fields and some kind of crazy parser to determine what is extension or other data and deal with it appropriately. Of course you could avoid the 2nd column by doing something with the index where it strips out the extra characters when creating the index, but I'd just make a second column and probably do the stripping of characters with a trigger.</p>
<p>Update: to address the AJAX issue, it may not be as bad as you think. If this is realistically the main way anything is done to the table, store only the digits in a secondary column as I said, and then make the index for that column the clustered one.</p>
|
<p>Use data type long instead.. dont use int because it only allows whole numbers between -32,768 and 32,767 but if you use long data type you can insert numbers between -2,147,483,648 and 2,147,483,647.</p>
| 10,069
|
<p>I am working on an ASP.NET (3/5) web application. In the application, we assemble lists of classes from a variety of data sources. I would like to create a report in SQL Server SSRS that renders a report from the contents of one of those lists, without pushing the list to the database (in fact, it would be a violation of a bunch of rules if we did that). Right now we are using SQL Server 2005 but we are considering a move to 2008. Is what I want to do possible and, if so, how do I do it?</p>
|
<p>Reporting services offer something called as DataSet extensions. You may use that to render the report from your custom data source. You do not need to load them back into database. However, certain editions of SQL like SQL Express reporting services does not support dataset extension.</p>
|
<p>You might want to use the ReportViewer control which ship with Visual Studio 2005 and Visual Studio 2008.</p>
<p>It can run in a "local mode", which doesn't require a Report Server backend. You simply drop it from the VS toolbox onto an ASPX form, then wire it up in code with any IEnumerable collection as its datasource, and then provide it with a report definition file for local mode (RDLC).</p>
<p>The RDLC file is basically the same as the original RDL (report definition language), but it omits a few things like the datasource, which is provided by your application. The ReportViewer control contains a smaller version of the report processing engine, so that at runtime, it "couples" the RDLC you provide with a data set or bindable collection, and it does the rest.</p>
<p>For more details on this control, check out the following site: <a href="http://www.gotreportviewer.com" rel="nofollow noreferrer">www.gotreportviewer.com</a></p>
<p>HTH</p>
| 36,724
|
<p>Is there any way that I can find the container pointed to by an iterator? Specifically, I want to be able to find the <code>std::vector</code> pointed to by a particular <code>std::vector::iterator</code> so that I can check the range, without having to actually pass references to that vector around.</p>
<p>If (as I suspect) the answer is no, why not? </p>
<p>edit: thanks for a number of quick and (largely) accurate answers. <a href="https://stackoverflow.com/questions/375598/finding-the-owner-of-an-stl-iterator#375608">Evan Teran</a> nails it. I wasn't thinking about optimization at all, but it's obvious now. </p>
<p>A couple of people asked what I want to do this for. It's nothing terribly important. I have an object which is initialized with a vector and an iterator pointing into the vector. It would be cute and convenient if I could initialize the object just with an iterator because then I could convert <code>vector::iterator</code>s directly to this object (this sounds strange but does make sense in the particular case). But it's not crucial at all.</p>
|
<p>I don't believe so. If iterators had to keep a reference/pointer to their owning container, then it would be impossible for them to be optimized down to a lightweight pointer (which can be done with containers guaranteeing contiguous storage like vectors and such).</p>
|
<p>I don't believe there's an exposed method to do that. The reason being, that's not the purpose of the iterator. There is, of course, no technical reason that an iterator could not hold a pointer to its parent container. Even if it is implemented in such a way that does not require that pointer, it could still hold it.</p>
<p>Iterators are intended to iterate over the collection, and as such, they provide the interface necessary to do that and only that. This is good object-oriented programming principles.</p>
<p>May I ask what your use-case is, that you need to know the "range" of the container with an iterator?</p>
| 49,159
|
<p>For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something...</p>
<p>The way I understand it, outgoing mail has to make three trips:</p>
<ol>
<li>Client (gmail user using Thunderbird) to a server (Gmail)</li>
<li>First server (Gmail) to second server (Hotmail)</li>
<li>Second server (Hotmail) to second client (hotmail user using OS X Mail)</li>
</ol>
<p>As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server.</p>
<p>However, I don't understand how gmail server transfers the message to the hotmail server.</p>
<p>For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again).</p>
<p>So, the big question is: <strong>when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?</strong></p>
<p>Thank you so much!</p>
<p>~Jason</p>
<hr>
<p>Thanks, that's been helpful so far.</p>
<p>As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually).</p>
<p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p>
<p>Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right?</p>
<p>Thanks again (especially to dr-jan),</p>
<p>Jason</p>
|
<p>The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient.</p>
<p>It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages.</p>
<p>Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP).</p>
<p>Jason - to answer your follow up...</p>
<blockquote>
<p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p>
</blockquote>
<p>That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com).</p>
<p>You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window):</p>
<pre><code>nslookup
> set type=mx
> stackoverflow.com
Server: 158.155.25.16
Address: 158.155.25.16#53
Non-authoritative answer:
stackoverflow.com mail exchanger = 10 aspmx.l.google.com.
stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com.
stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com.
stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com.
stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.
Authoritative answers can be found from:
aspmx.l.google.com internet address = 64.233.183.114
aspmx.l.google.com internet address = 64.233.183.27
>
</code></pre>
<p>This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above.</p>
<p>The Wikipedia article mentioned (<a href="http://en.wikipedia.org/wiki/Mx_record" rel="noreferrer">http://en.wikipedia.org/wiki/Mx_record</a>) discusses the priority numbers shown above (10, 20, ..., 50).</p>
|
<p>Step 2 to 3 (i.e. Gmail to Hotmail) would normally happen through SMTP (or ESMTP - extended SMTP).</p>
<p>Hotmail doesn't send anything to a client via POP3. It's important to understand some of the nuances here. The client contacts Hotmail via POP3 and requests its mail. (i.e. the client initiates the discussion).</p>
| 5,274
|
<p>How to allow <code>TextBlock</code>'s text to be selectable?</p>
<p>I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?</p>
|
<p>Use a <code>TextBox</code> with these settings instead to make it read only and to look like a <code>TextBlock</code> control.</p>
<pre><code><TextBox Background="Transparent"
BorderThickness="0"
Text="{Binding Text, Mode=OneWay}"
IsReadOnly="True"
TextWrapping="Wrap" />
</code></pre>
|
<p>I've implemented <a href="http://blog.angeloflogic.com/2014/07/selectabletextblock-in-junglecontrols.html" rel="nofollow">SelectableTextBlock</a> in my opensource controls library. You can use it like this:</p>
<pre class="lang-xml prettyprint-override"><code><jc:SelectableTextBlock Text="Some text" />
</code></pre>
| 16,509
|
<p>I have the following JavaScript code:
<a href="http://www.nomorepasting.com/getpaste.php?pasteid=22561" rel="nofollow noreferrer">Link</a></p>
<p>In which the function makewindows does not seem to be working.</p>
<p>It does actual create a window, however the html either contains what is quotes, or if I change it to</p>
<pre><code>child1.document.write(json_encode($row2["ARTICLE_DESC"]));
</code></pre>
<p>to create a blank html page.</p>
<p>I moved this function to my main JavaScript file to include because I was getting errors before, but now no HTML is presented in the popupwindow. Is this because I am not retrieving article_Desc in thest3.php?</p>
<p>The other 2 files used are here:
<a href="http://www.nomorepasting.com/getpaste.php?pasteid=22562" rel="nofollow noreferrer">link</a>
and <a href="http://www.nomorepasting.com/getpaste.php?pasteid=22563" rel="nofollow noreferrer">test3.php</a></p>
|
<blockquote>
<p>$row2["ARTICLE_DESC"] is PHP variable.</p>
</blockquote>
<p>It is indeed a php variable, but <strong>it is not being rendered as php because it is not enclosed in <code><?php ?></code> tags</strong></p>
<p>So, the correct way to do it is: </p>
<pre><code>child1.document.write(<?php echo json_encode($row2["ARTICLE_DESC"]); ?>);
</code></pre>
<p>That way, the php, being a server side language, will render the value in $row2 before the page is rendered, so when the page finally gets rendered, that value will be in the javascript <code>write</code> function...as it's supposed to be.</p>
|
<p>I suspect that it is including the javascript after it has been parsed by the PHP interpreter. Try adding a parameter to makewindows and pass the value you intend to use in via the parameter when you construct the HTML.</p>
<pre><code> ...
<p><a href='#' onclick='makewindows('"
. json_encode($row2["ARTICLE_DESC"])
. "'); return false;'>...
function makewindows(html){
child1 = window.open ("about:blank");
child1.document.write(html);
child1.document.close();
}
</code></pre>
| 45,456
|
<p>I'm creating some big files (DB exports) with Java and I need to put them somewhere on our SharePoint server. Right now, I'm doing this with IE but I'd like to automate this step, too.</p>
<p>I searched the web and I found some hints to use SOAP but I don't really see to the ground of all this, yet. Can someone provide me with some sample code or a recipe what I need to do?</p>
<p>Please note: the SharePoint server asks for NT domain authentication. I can't even login with Firefox :(</p>
<p><strong>EDIT</strong></p>
<ul>
<li>How do I convert the scary URL in IE into a WebDAV path?</li>
<li>Is there a WebDAV "explorer" which I can use before I ruin the production system with my code? I tried "DAV Explorer 0.91" from <a href="http://www.davexplorer.org/" rel="noreferrer">http://www.davexplorer.org/</a> but that can't connect (probably because of NT domain auth).</li>
</ul>
|
<p>Okay ... after several hours of work and biting myself through the "documentation" MicroSoft provides and all the hints randomly spread over the 'net, I've managed to write some sample code to browse the content of a SharePoint server: <a href="http://blog.pdark.de/2008/11/navigating-sharepoint-folders-with.html" rel="noreferrer">Navigating SharePoint Folders With Axis2</a>.</p>
<p>Next stop: Uploading something.</p>
|
<p>I can think of different options:</p>
<ul>
<li>Mapping the Document library to a file drive and just save the file like any other file in the file system.</li>
<li>Using HTTP WebDAV protocol.</li>
</ul>
<p>...and for the NTLM authentication part:</p>
<p><a href="http://www.luigidragone.com/networking/ntlm.html" rel="nofollow noreferrer">http://www.luigidragone.com/networking/ntlm.html</a></p>
| 40,537
|
<pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
<p>I often find myself wanting to do things like this (<code>EmployeeNumber</code> is a <code>Nullable<int></code> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values). Unfortunately, the compiler feels that</p>
<blockquote>
<p>There is no implicit conversion between 'null' and 'int'</p>
</blockquote>
<p>even though both types would be valid in an assignment operation to a nullable int on their own.</p>
<p>Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the <code>.Text</code> string if it's not null.</p>
<p>As far as I know the only way to do this is to use an if statement and/or assign it in two steps. In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...</p>
<p>Does anyone know a more elegant solution?</p>
|
<p>The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values. In this case, you have a <code>null</code> and an <code>Int32</code>, and the type can not be determined (there are real reasons it can't just assume <code>Nullable<Int32></code>).</p>
<p>If you really want to use it in this way, you must cast one of the values to <code>Nullable<Int32></code> yourself, so C# can resolve the type:</p>
<pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? (int?)null
: Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
<p>or</p>
<pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
|
<p>As of <a href="https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#target-typed--and-" rel="nofollow noreferrer">C# 9.0</a>, this will finally be possible:</p>
<blockquote>
<h3>Target typed ?? and ?:</h3>
<p>Sometimes conditional ?? and ?: expressions don’t have an obvious shared type between the branches. Such cases fail today, but C# 9.0 will allow them if there’s a target type that both branches convert to:</p>
<pre><code>Person person = student ?? customer; // Shared base type
int? result = b ? 0 : null; // nullable value type
</code></pre>
</blockquote>
<p>That means the code block in the question will also compile without errors.</p>
<pre><code>EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
</code></pre>
| 10,138
|
<p>Which one should I use?</p>
<pre><code>catch (_com_error e)
</code></pre>
<p>or </p>
<pre><code>catch (_com_error& e)
</code></pre>
|
<p>The second. Here is my attempt at quoting Sutter</p>
<p>"Throw by value, catch by reference"</p>
<blockquote>
<p>Learn to <code>catch</code> properly: Throw exceptions by value (not pointer) and
catch them by reference (usually to <code>const</code>). This is the combination
that meshes best with exception semantics. When rethrowing the same
exception, prefer just <code>throw;</code> to <code>throw e;</code>.</p>
</blockquote>
<p>Here's the full <a href="http://www.informit.com/content/images/0321113586/items/sutter_item73.pdf" rel="nofollow noreferrer">Item 73. Throw by value, catch by reference.</a></p>
<hr>
<p>The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost. </p>
<pre><code>try { throw MyException ("error") }
catch (Exception e) {
/* Implies: Exception e (MyException ("error")) */
/* e is an instance of Exception, but not MyException */
}
</code></pre>
<p>Catching by reference avoids this issue by not copying the exception.</p>
<pre><code>try { throw MyException ("error") }
catch (Exception& e) {
/* Implies: Exception &e = MyException ("error"); */
/* e is an instance of MyException */
}
</code></pre>
|
<p>Definitely the second. If you had the following:</p>
<pre><code>class my_exception : public exception
{
int my_exception_data;
};
void foo()
{
throw my_exception;
}
void bar()
{
try
{
foo();
}
catch (exception e)
{
// e is "sliced off" - you lose the "my_exception-ness" of the exception object
}
}
</code></pre>
| 18,219
|
<p>I have written a CGI script that creates an image dynamically using GET data. To include this image in my webpage, I am using the following code:</p>
<pre><code><img src="image.py?text=xxxxxxxxxxxxxx">
</code></pre>
<p>The problem is that I expect in the future the "text" field will get very long and the URL will become too large. From Googling around there doesn't seem to be a fixed limit on URL length (ie. depends on the browser, server, proxy, etc.) Is there a better way to do this? </p>
<p>If it matters, I am working with Django and Python and I cannot use any client-side scripting (ie. JavaScript).</p>
<p>Cheers,
Ben</p>
|
<p>Store the text somewhere (e.g. a database) and then pass through the primary key.</p>
|
<p>img's use GET. You'll have to come up with another mechanism. How about calling the same functionality in image.py and saving the file as a temp file which you ref in the img tag? Or how about saving the value of text in a db row during the rendering of this img tag and using the row_id as what you pass into the image.py script?</p>
| 30,152
|
<p>I have some questions about basic CSS that I was unable to understand or find an answer for.</p>
<p>First, I tried placing 3 div tags within another div tag. The first main div tag containing the 3 other tags had nothing set for it except a size, which was <code>400px</code> by <code>400px</code>. Of the other 3 divs inside, all were <code>20px</code> by <code>20px</code>, and 1 was assigned <code>float:left</code>, and the other two were assigned a style that was float right. All attributes were defined within a style, and the two divs that were <code>float:right</code> were assigned the same style. My problem is that out of the 2 divs, the one that came last in the code, would appear first in a browser, and I did not understand the reasoning for this.</p>
<p>Here is the code:</p>
<pre><code><html>
<head>
<style>
#main{
border: red 4px dashed;
width: 25%
height: 25%,
}
#left{
float: left;
width: 20px;
height: 20px,
}
#right{
float: right;
width: 20px;
height: 20px,
}
</style>
</head>
<body>
<div id="main">
<div id="left">1</div>
<div id="right">2</div>
<div id="right">3</div>
</div>
</body>
</head>
</html>
</code></pre>
|
<blockquote>
<p>My problem is that out of the 2 divs,
the one that came last in the code,
would appear first in a browser, and I
did not understand the reasoning for
this.</p>
</blockquote>
<p>I think that You misunderstood a "appear first". You set Your divs to be floating right. So a "2" div, which is FIRST in Your code, is FIRST to be floated right, so it goes first to the right side. A "3" div is then floated, so i goes to the left side of the "2" div - because "2" was first, it took first place at the right side of the browser window, and div "3" took second place at the right side of the window. </p>
<p>In this case "second place at the right side of the window" means "first, looking from the left" ;-)</p>
|
<pre><code><html>
<head>
<style>
#main {
border: 4px dashed red;
display: block;
overflow: hidden;
}
#left {
float: left;
width: 20px;
height: 20px,
}
#right {
float: right;
width: 20px;
height: 20px,
}
</style>
</head>
<body>
<div id="main">
<div id="left">1</div>
<div id="right">3</div>
<div id="right">2</div>
</div>
</body>
</head>
</html>
</code></pre>
| 37,783
|
<p>The file upload control in asp.net does not allow me to select a folder and enables me to select only the files. Is there any way in which I can select a folder (obviously without using the file upload control).</p>
<p>Why I want to select the folder is basically to store its entire path in a database table. </p>
|
<p>The HTML <code><input type=file></code> element only supports single file uploads. If you to have multiple file upload, you would have to use a 3rd party component - usually written in Flash.</p>
<p>Here an example: <a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/aspnet/FlashUpload.aspx</a></p>
|
<p>No, browsing for files are the client-side feature, and the only information about file path is their name. It's cause security.</p>
| 16,064
|
<pre><code> public sealed class UserLoginSingleton
{
UserLoginCollection _userLoginCol = new UserLoginCollection();
UserLoginSingleton()
{
}
public static UserLoginSingleton Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if (!items.Contains("TheInstance"))
{
items["TheInstance"] = new UserLoginSingleton();
}
return items["TheInstance"] as UserLoginSingleton;
}
}
public void CreateUserObj(string xmlData)
{
_userLoginCol = (UserLoginCollection)_xmlUtil.Deserialize(xmlData, typeof(UserLoginCollection));
}
public UserLoginCollection getUserObj()
{
return _userLoginCol;
}
}
</code></pre>
<p>Usage:</p>
<p>Page 1.aspx</p>
<pre><code>UserLoginSingleton.Instance.CreateUserObj(xml);
</code></pre>
<p>Pase2.aspx:</p>
<blockquote>
<p>UserLoginCollection
userLoginCollection =
UserLoginSingleton.Instance.getUserObj();</p>
</blockquote>
<p>Followed the article here:
<a href="https://stackoverflow.com/questions/194999/are-static-class-instances-unique-to-a-request-or-a-server-in-aspnet">link text</a></p>
<p>I set my collection object in page 1 and then do a response.redirect or click on link to get me to page 2.aspx. However, my singleton instance has no collection object i set. How do i persist my collection object across diff pages per each session?</p>
<p>I know static's wont work as every instance will see the object and i want that to specific per each user.</p>
|
<p>The <code>HttpContext.Items</code> collection is per-request. So in your case when the user gets redirected to page2.aspx, the instance you created on page 1 is gone. For the same instance to be available across requests, you need to be using <code>HttpContext.Session</code> to store your instance.</p>
|
<p>static fields are shared between requests. Watch out for the standard multi-threaded issues!</p>
<p>HttpContext instances are not shared between requests.</p>
| 47,483
|
<p>In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.</p>
<p><strong>Is there any way to add files to the sub-tree or group for a Windows Form class?</strong></p>
|
<p>Open .csproj in edit mode, look for the file you want to be under another one, and add the DependentUpon element, like this:</p>
<pre><code><Compile Include="AlertDialog.xaml.cs">
<DependentUpon>AlertDialog.xaml</DependentUpon>
</Compile>
</code></pre>
|
<p>You need to edit the csproj directly. There is a DependentUpon tag that you have to add as a child tag of the file you want to place under MyForm.cs.</p>
<p>Example:</p>
<pre><code><Compile Include="MyForm.MyCoolSubFile.cs">
<DependentUpon>MyForm.cs</DependentUpon>
</Compile>
</code></pre>
| 27,556
|
<p>I've recently updated an application to the 3.5 framework (from 2.0). The app links to Reporting Services (2005) remotely via an URL. This all works fine locally but when deployed to the dev server (win 2003) I'm getting a 403 error when attempting to call the report server.</p>
<p>"You are not authorized to view this page
...</p>
<p>HTTP Error 403 - Forbidden "</p>
<p>This just started happening after the 3.5 framework was installed, I've tried various security settings but can't get this to work again.</p>
<p>Does anyone know what security needs to be set or what I need to change?</p>
<p>Thanks.</p>
|
<p>Not sure if I should answer myself or just comment but anyway.</p>
<p>Found the (or at least a) solution from another post. Apparently the reporting services root directory can get corrupted - how is not clear - but I deleted the ReportServer virtual directory and recreated it with the Reporting Services Configuration tool.</p>
<p>It's working again, thanks for the responses.</p>
|
<p>When you say call the report server, what do you mean specifically? Access the Report Manager using this url: www.myserver.com/reports ?</p>
<p>The main reason is, that locally you are authenticated implicitly as the user you're logged on to the server. Accessing the server remotely in the browser, does not necessarily authenticate you. Do you have anonymous authentication enabled in IIS on the server? If so, you are authenticated as a public anonymous/guest user and have not access to the report server. By disabling anonymous authentication, you will be prompted for username/password to authenticate.</p>
| 42,991
|
<p>I'm wanting to use jQuery to wrap a mailto: anchor around an email address, but it's also grabbing the whitepace that the CMS is generating.</p>
<p>Here's the HTML I have to work with, the script as I have it and a copy of the output.</p>
<p>HTML</p>
<pre><code><div class="field field-type-text field-field-email">
<div class="field-item">
name@example.com </div>
</div>
</code></pre>
<p>jQuery JavaScript</p>
<pre><code>$(document).ready(function(){
$('div.field-field-email .field-item').each(function(){
var emailAdd = $(this).text();
$(this).wrapInner('<a href="mailto:' + emailAdd + '"></a>');
});
});
</code></pre>
<p>Generated HTML</p>
<pre><code><div class="field field-type-text field-field-email">
<div class="field-items"><a href="mailto:%0A%20%20%20%20name@example.com%20%20%20%20">
name@example.com </a></div>
</div>
</code></pre>
<p>Though I suspect that others reading this question might want to just strip the leading and tailing whitespace, I'm quite happy to lose all the whitespace considering it's an email address I'm wrapping.</p>
|
<p>Use the <code>replace</code> function in js:</p>
<pre><code>var emailAdd = $(this).text().replace(/ /g,'');
</code></pre>
<p>That will remove all the spaces</p>
<p>If you want to remove the leading and trailing whitespace <strong>only</strong>, use the jQuery $.trim method :</p>
<pre><code>var emailAdd = $.trim($(this).text());
</code></pre>
|
<p><code>str=str.replace(/^\s+|\s+$/g,'');</code></p>
| 47,051
|
<p>I am using java language,I have a method that is supposed to return an object if it is found.</p>
<p>If it is not found, should I:</p>
<ol>
<li>return null</li>
<li>throw an exception</li>
<li>other</li>
</ol>
<p>Which is the best practise or idiom?</p>
|
<p>If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.</p>
<p>If the value can be missing or present and both are valid for the application logic then return a null.</p>
<p>More important: What do you do other places in the code? Consistency is important.</p>
|
<p>That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:</p>
<ul>
<li>Object found; return object</li>
<li>Object not-found; throw exception</li>
</ul>
<p>Otherwise, return null.</p>
| 21,155
|
<p>When a script is saved as a bundle, it can use the <code>localized string</code> command to find the appropriate string, e.g. in <code>Contents/Resources/English.lproj/Localizable.strings</code>. If this is a format string, what is the best way to fill in the placeholders? In other words, what is the AppleScript equivalent of <code>+[NSString stringWithFormat:]</code>?</p>
<p>One idea I had was to use <code>do shell script</code> with <code>printf(1)</code>. Is there a better way?</p>
|
<p><a href="https://developer.apple.com/library/content/releasenotes/AppleScript/RN-AppleScript/RN-10_10/RN-10_10.html" rel="nofollow noreferrer">Since OS X 10.10</a>, it’s been possible for any AppleScript script to use Objective-C. There are a few ways to call Objective-C methods from within AppleScript, as detailed in <a href="https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/MacAutomationScriptingGuide/AppendixA-AppleScriptObjCQuickTranslationGuide.html" rel="nofollow noreferrer">this translation guide</a>. An Objective-C developer like me would gravitate toward this syntax, which interpolates the method's parameters with their values:</p>
<pre><code>use framework "Foundation"
tell the current application's NSWorkspace's sharedWorkspace to openFile:"/Users/me/Desktop/filter.png" withApplication:"Preview"
</code></pre>
<p>Result:</p>
<pre><code>true
</code></pre>
<p><code>+[NSString stringWithFormat:]</code> is a tricky case. It takes a vararg list as its first parameter, so you need some way to force both the format string and its arguments into the same method parameter. The following results in an error, because AppleScript ends up passing a single NSArray into the parameter that expects, conceptually, a C array of NSStrings:</p>
<pre><code>use framework "Foundation"
the current application's NSString's stringWithFormat:{"%lu documents", 8}
</code></pre>
<p>Result:</p>
<pre><code>error "-[__NSArrayM length]: unrecognized selector sent to instance 0x7fd8d59f3bf0" number -10000
</code></pre>
<p>Instead, you have to use an alternative syntax that looks more like an AppleScript handler call than an Objective-C message. You also need to coerce the return value (an NSString object) into a <code>text</code>:</p>
<pre><code>use framework "Foundation"
the current application's NSString's stringWithFormat_("%lu documents", 8) as text
</code></pre>
<p>Result:</p>
<pre><code>"2087 documents"
</code></pre>
<p>The “with parameters” syntax that @nlanza mentions points to the fact that AppleScript is using something akin to <a href="https://developer.apple.com/reference/foundation/nsinvocation" rel="nofollow noreferrer">NSInvocation</a> under the hood. In Objective-C, NSInvocation allows you to send a message to an object, along with an array of parameter values, without necessarily matching each value to a particular parameter. (See <a href="http://theocacao.com/document.page/264" rel="nofollow noreferrer">this article</a> for some examples of using NSInvocation directly.)</p>
|
<p>As ugly as it is, calling out to <code>printf(1)</code> is the common solution.</p>
<p>A cleaner, though somewhat more complex, solution is to use AppleScript Studio, which allows you to call into Objective-C objects/classes from your AppleScript code with the <code>call method</code> syntax documented <a href="http://developer.apple.com/documentation/AppleScript/Conceptual/StudioBuildingApps/chapter04/chapter_4_section_2.html#//apple_ref/doc/uid/20001251-TPXREF175" rel="nofollow noreferrer">here</a>.</p>
<p>With that, you'd be able to use something like this:</p>
<pre><code>call method "stringWithFormat:" of class "NSString" with parameters {formatString, arguments}
</code></pre>
<p>The downside of this, of course, is that you need to write an AppleScript Studio app instead of just writing a simple script. You do get a good bit more flexibility in general with Studio apps, though, so it's not all together a terrible route to go.</p>
| 8,963
|
<p>How do I make my application always use English when displaying win32/.net exceptions messages?</p>
<p>I got this message, it looks like someone used babelfish to translate it (it's Swedish):
"System.ComponentModel.Win32Exception: Programmet kunde inte starta eftersom programmets sida-vid-sidakonfiguration är felaktig."</p>
<p>Extremely unhelpful, and Google had a whopping 4 hits for it, none of them helpful.
So I have to guess what the original message was and google that. (It's was: "The application has failed to start because its side-by-side configuration is incorrect.")</p>
<p>This time it was fairly simple to find out what the original error message was, having the message in English from the start would of course save me time.</p>
<p>So how do I do that?</p>
|
<p>You can try setting <code>Thread.CurrentThread.CurrentUICulture</code> and/or <code>.CurrentCulture</code> to <code>CultureInfo("en-US")</code>.</p>
|
<blockquote>
<p>How do I make my application always
use English when displaying win32/.net
exceptions messages?</p>
</blockquote>
<p>First of all, <em>don't show win32/.net exception messages to users</em>. You should handle exceptions rather than showing them to user.</p>
<p>By default exception messages will be shown in current's UI language (if appropriate language pack is installed, otherwise they fallback to English). You can change exception messages changing <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture.aspx" rel="nofollow noreferrer">Thread.CurrentThread.CurrentUICulture</a> property, however it will affect the whole GUI of your app.</p>
| 23,971
|
<p>I have a products table...</p>
<p><a href="http://img357.imageshack.us/img357/6393/productscx5.gif" rel="nofollow noreferrer">alt text http://img357.imageshack.us/img357/6393/productscx5.gif</a></p>
<p>and a revisions table, which is supposed to track changes to product info</p>
<p><a href="http://img124.imageshack.us/img124/1139/revisionslz5.gif" rel="nofollow noreferrer">alt text http://img124.imageshack.us/img124/1139/revisionslz5.gif</a></p>
<p>I try to query the database for all products, with their most recent revision...</p>
<pre><code>select
*
from `products` as `p`
left join `revisions` as `r` on `r`.`product_id` = `p`.`product_id`
group by `p`.`product_id`
order by `r`.`modified` desc
</code></pre>
<p>but I always just get the first revision. I need to do this in <strong>one</strong> select (ie no sub queries). I can manage it in mssql, is this even possible in mysql?</p>
|
<p>Here's how I'd do it:</p>
<pre><code>SELECT p.*, r.*
FROM products AS p
JOIN revisions AS r USING (product_id)
LEFT OUTER JOIN revisions AS r2
ON (r.product_id = r2.product_id AND r.modified < r2.modified)
WHERE r2.revision_id IS NULL;
</code></pre>
<p>In other words: find the revision for which no other revision exists with the same product_id and a greater modified value.</p>
|
<p>That same query is parsable in MySQL.</p>
<p>Why are you using a Left JOIN instead of an INNER join or a RIGHT join? </p>
<p>Also if you want to go about this in a different way, you have the MAX function at your disposal.</p>
| 19,046
|
<p>Other than <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall" rel="nofollow noreferrer">-Wall</a>, what other warnings have people found useful?</p>
<p><em><a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Warning-Options.html" rel="nofollow noreferrer">Options to Request or Suppress Warnings</a></em></p>
|
<p>I routinely use:</p>
<pre class="lang-none prettyprint-override"><code>gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \
-Wstrict-prototypes -Wmissing-prototypes
</code></pre>
<p>This set catches a lot for people unused to it (people whose code I get to compile with those flags for the first time); it seldom gives me a problem (though <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wcast-qual" rel="nofollow noreferrer">-Wcast-qual</a> is occasionally a nuisance).</p>
|
<p>I use this option:</p>
<p><a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wfatal-errors" rel="nofollow noreferrer">-Wfatal-errors</a></p>
| 18,694
|
<p>I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented.</p>
<p>A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than that they exist in the <a href="http://en.wikipedia.org/wiki/InnoDB" rel="noreferrer">InnoDB</a> storage schema that MySQL has.</p>
<p>What is a simple example of foreign keys implemented in MySQL?</p>
<p>Here's part of a schema I wrote that doesn't seem to be working if you would rather point out my flaw than show me a working example.</p>
<pre><code>CREATE TABLE `posts` (
`pID` bigint(20) NOT NULL auto_increment,
`content` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uID` bigint(20) NOT NULL,
`wikiptr` bigint(20) default NULL,
`cID` bigint(20) NOT NULL,
PRIMARY KEY (`pID`),
Foreign Key(`cID`) references categories,
Foreign Key(`uID`) references users
) ENGINE=InnoDB;
</code></pre>
|
<p>Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work:</p>
<pre><code>CREATE TABLE `posts` (
`pID` bigint(20) NOT NULL auto_increment,
`content` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uID` bigint(20) NOT NULL,
`wikiptr` bigint(20) default NULL,
`cID` bigint(20) NOT NULL,
PRIMARY KEY (`pID`),
Foreign Key(`cID`) references categories(`cID`),
Foreign Key(`uID`) references users(`uID`)
) ENGINE=InnoDB;
</code></pre>
<p>The column name is required in the <code>references</code> clause.</p>
|
<p>I agree with Robert. You are missing the name of the column in the references clause (and you should be getting the error 150). I'll add that you can check how the tables got created in reality with:</p>
<pre><code>SHOW CREATE TABLE posts;
</code></pre>
| 29,287
|
<p>I'm looking for suggestions on possible IPC mechanisms that are:</p>
<ul>
<li><strong>Cross platform</strong> (Win32 and Linux at least)</li>
<li>Simple to implement in <strong>C++</strong> as well as the <strong>most common scripting languages</strong> (perl, ruby, python, etc).</li>
<li>Finally, <strong>simple to use</strong> from a programming point of view!</li>
</ul>
<p>What my options are? I'm programming under Linux, but I'd like what I write to be portable to other OSes in the future. I've thought about using sockets, named pipes, or something like DBus.</p>
|
<p>In terms of speed, the best cross-platform IPC mechanism will be pipes. That assumes, however, that you want cross-platform IPC on the same machine. If you want to be able to talk to processes on remote machines, you'll want to look at using sockets instead. Luckily, if you're talking about TCP at least, sockets and pipes behave pretty much the same behavior. While the APIs for setting them up and connecting them are different, they both just act like streams of data.</p>
<p>The difficult part, however, is not the communication channel, but the messages you pass over it. You really want to look at something that will perform verification and parsing for you. I recommend looking at Google's <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html" rel="noreferrer">Protocol Buffers</a>. You basically create a spec file that describes the object you want to pass between processes, and there is a compiler that generates code in a number of different languages for reading and writing objects that match the spec. It's much easier (and less bug prone) than trying to come up with a messaging protocol and parser yourself.</p>
|
<p>Python has a pretty good IPC library: see <a href="https://docs.python.org/2/library/ipc.html" rel="nofollow noreferrer"><a href="https://docs.python.org/2/library/ipc.html" rel="nofollow noreferrer">https://docs.python.org/2/library/ipc.html</a></a></p>
| 8,558
|
<p>I have a IBAction such as:</p>
<pre><code>- (IBAction)showPicker:(id)sender;
</code></pre>
<p>How can I get the name of the control from the sender variable?</p>
<p>I am typically a c# coder so have tried the following to no avail</p>
<pre><code>senderName = ((UIButton *)sender).name;
</code></pre>
<p>I need something more descriptive than the control id (not the button title either). I have 5 buttons all calling the same method. I need to determine which was clicked in order to perform the methods actions on the appropriate control. I.E I have an address picker method but want to populate 5 text fields with different details with each of 5 buttons. Just trying to keep the code tidy</p>
<p>N.B Originally I was planning on using the Interface Builders name field, but I've been advised (below) that this isn't available at runtime.</p>
|
<p>You might want to look at using the <em>tag</em> property. It's an integer rather than a name, but can be used to differentiate between two controls. It's inherited from UIView so any control that's sending an event should have it.</p>
<p>It's editable in Interface Builder under View attributes.</p>
<p>It's a property so it can be accessed programatically with the dot notation:</p>
<pre><code>control.tag
</code></pre>
<p>Or you can convert to a string as follows:</p>
<pre><code>[stringWithFormat:@"%d", control.tag]
</code></pre>
|
<p>If the control has a name attribute, then:</p>
<pre><code>NSString *senderName = [sender name];
</code></pre>
<p>This isn't something most controls have. You might want:</p>
<pre><code>NSString *senderName = [sender title];
</code></pre>
<p>If it was an NSButton, for instance. Or as Marc says, for a UIButton, use currentTitle.</p>
| 46,862
|
<p>I'm trying to set up a basic test of HMAC-SHA-256 hashing but I'm having problems with the engine setup. Ideally I would like to set up only the HMAC-SHA-algorithm but so far I haven't even gotten the general case where load all the algorithms to work. Currently I'm getting segfaults on the row where I try to set the default digests.</p>
<p>Also, I'm regularly a Java guy, so don't hesitate to point out any mistakes in the code.</p>
<pre><code>#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
unsigned char* data = (unsigned char*) "4869205468657265";
unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
unsigned char* result;
HMAC_CTX* ctx;
ENGINE* e;
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
ENGINE_set_default_digests(e);
HMAC_CTX_init(ctx);
HMAC_Init_ex(ctx, key, 40, EVP_sha256(), e);
result = HMAC(NULL, NULL, 40, data, 16, NULL, NULL);
HMAC_CTX_cleanup(ctx);
ENGINE_finish(e);
ENGINE_free(e);
if (strcmp((char*) result, (char*) expected) == 0) {
printf("Test ok\n");
} else {
printf("Got %s instead of %s\n", result, expected);
}
}
</code></pre>
<p>EDIT: The program has now evolved to the following, but I'm still segfaulting at <code>HMAC_Init_ex</code>:</p>
<pre><code>unsigned char* key = (unsigned char*) "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
unsigned char* data = (unsigned char*) "4869205468657265";
unsigned char* expected = (unsigned char*) "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
unsigned char* result;
unsigned int result_len = 64;
HMAC_CTX ctx;
ENGINE* e;
result = (unsigned char*) malloc(sizeof(char) * result_len);
e = (ENGINE*) ENGINE_new();
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
ENGINE_set_default_digests(e);
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), e);
HMAC_Update(&ctx, data, 40);
HMAC_Final(&ctx, result, &result_len);
HMAC_CTX_cleanup(&ctx);
ENGINE_finish(e);
ENGINE_free(e);
</code></pre>
|
<p>The problem with your original suggestion is, as Martin said, that you need to initialise the ENGINE. The problem with your edited code was that you were doing ENGINE_new, which is getting you a completely new ENGINE of your own, which you then need to provide with cipher methods, digest methods, etc. In fact, for what you want (and what almost everybody wants), just completely ignoring all of the ENGINE stuff is the right choice. </p>
<p>Some subsidiary problems: </p>
<ul>
<li>your strings were hex, but you needed a \x per character to actually get that hex byte at that position in the string, which I suspect was what you wanted.</li>
<li>you were trying to hash 40 bytes from "data", which wasn't that long (actual effect: you'd end up partly hashing your result string)</li>
<li>your expected result was (as far as I can tell) incorrect</li>
<li>you would print out random characters to the terminal, since the HMAC function will produce 32 bytes of random binary data, not printable stuff.</li>
</ul>
<p>The following code compiles, works and passes the test. It's a bit different to the example code you found (since it still uses the individual HMAC_* functions - useful if you want to do your hashing bit by bit using HMAC_Update):</p>
<pre><code>#include <openssl/engine.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
unsigned char* key = (unsigned char*) "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b";
unsigned char* data = (unsigned char*) "\x48\x69\x20\x54\x68\x65\x72\x65";
unsigned char* expected = (unsigned char*) "\x49\x2c\xe0\x20\xfe\x25\x34\xa5\x78\x9d\xc3\x84\x88\x06\xc7\x8f\x4f\x67\x11\x39\x7f\x08\xe7\xe7\xa1\x2c\xa5\xa4\x48\x3c\x8a\xa6";
unsigned char* result;
unsigned int result_len = 32;
int i;
HMAC_CTX ctx;
result = (unsigned char*) malloc(sizeof(char) * result_len);
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, 16, EVP_sha256(), NULL);
HMAC_Update(&ctx, data, 8);
HMAC_Final(&ctx, result, &result_len);
HMAC_CTX_cleanup(&ctx);
for (i=0; i!=result_len; i++)
{
if (expected[i]!=result[i])
{
printf("Got %02X instead of %02X at byte %d!\n", result[i], expected[i], i);
break;
}
}
if (i==result_len)
{
printf("Test ok!\n");
}
return 0;
}
</code></pre>
<p>Of course, it doesn't answer your original question about how to initialise ENGINEs, but there's really no right answer to that without having more context, which context turns out not to be relevant in your situation...</p>
|
<p>It looks as though nothing is allocating an engine, so the first use of <code>e</code> is segfaulting. I think you need to call <code>ENGINE *ENGINE_new(void)</code> first.</p>
<p>(Note that I've used OpenSSL, but I haven't used the <code>ENGINE</code> functions before.)</p>
<p><strong>Update</strong>: I'm not really happy with my own answer (I had to dash off to tea, before). So my further notes are:</p>
<ol>
<li><p>I've had a bit of a look at the (long) <a href="http://www.manpagez.com/man/3/engine/" rel="nofollow noreferrer">man page</a> for the <code>ENGINE</code> functions, and I'm not quite sure that calling <code>ENGINE_new</code> is sufficient.</p></li>
<li><p>I didn't notice that the calls to the <code>HMAC_CTX_*</code> functions were taking an uninitialized pointer, rather than a pointer to an allocated structure. <code>HMAC_CTX_init</code> will try to write to the memory pointed to by its <code>ctx</code> parameter, which will segfault. You need to declare and use <code>ctx</code> like this:</p>
<pre><code>HMAC_CTX ctx;
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, key, 40, EVP_sha256(), e);
...
</code></pre>
<p>That way you're allocating the structure on the stack, and then passing a pointer to it.</p></li>
<li><p>The <code>HMAC</code> function doesn't take a pointer to a <code>CTX</code> at all, so apart from global or thread-local storage, I'm not sure what it's connection to the <code>CTX</code> is. I think you can bypass that by calling <code>HMAC_Update</code> one-or-more times, followed by <code>HMAC_Final</code> to get the result. You'd need to allocate space for that result, so something like the following would work for that:</p>
<pre><code>unsigned int len;
HMAC_Final(&ctx, result, &len);
</code></pre></li>
</ol>
| 30,049
|
<p>I have been working on a childish little program: there are a bunch of little circles on the screen, of different colors and sizes. When a larger circle encounters a smaller circle it eats the smaller circle, and when a circle has eaten enough other circles it reproduces. It's kind of neat!</p>
<p>However, the way I have it implemented, the process of detecting nearby circles and checking them for edibility is done with a for loop that cycles through the entire living population of circles... which takes longer and longer as the population tends to spike into the 3000 before it starts to drop. The process doesn't slow my computer down, I can go off and play Dawn of War or whatever and there isn't any slow down: it's just the process of checking every circle to see if it has collided with every other circle...</p>
<p>So what occurred to me, is that I could try to separate the application window into four quadrants, and have the circles in the quadrants do their checks simultaneously, since they would have almost no chance of interfering with each other: or something to that effect!</p>
<p>My question, then, is: how does one make for loops that run side by side? In Java, say.</p>
|
<p>Computers are usually single tasked, this means they can usually execute one instruction at a time per CPU or core.</p>
<p>However, as you have noticed, your operation system (and other programs) appear to run many tasks at the same time.</p>
<p>This is accomplished by splitting the work into processes, and each process can further implement concurrency by spawning threads. The operation system then switches between each process and thread very quickly to give the illusion of multitasking.</p>
<p>In your situation,your java program is a single process, and you would need to create 4 threads each running their own loop. It can get tricky, because threads need to synchronize their access to local variables, to prevent one thread editing a variable while another thread is trying to access it.</p>
<p>Because threading is a complex subject it would take far more explaining than I can do here.</p>
<p>However, you can read Suns excellent tutorial on Concurrency, which covers everything you need to know:</p>
<p><a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/essential/concurrency/</a></p>
|
<p>IF your computer has multiple processors or multiple cores, then you could easily run multiple threads and run smaller parts of the loops in each thread. Many PCs these days do have multiple cores -- so have it so that each thread gets 1/nth of the loop count and then create n threads.</p>
| 34,574
|
<p>I want to delete <strong>all</strong> the previously created indices. I am using <code>Lucene.net</code>.</p>
<p>I tried the following:</p>
<pre><code>Term term = new Term(); //empty because I want to delete all the indices
IndexReader rdr = IndexReader.Open(_directory);
rdr.DeleteDocuments(term);
rdr.Close();
</code></pre>
<p>But I get error. Any idea how to go about it?</p>
|
<p>The best way to delete an index is to wipe the filesystem directory. However, if you wan't to regenerate the index, the easiest way is to open a new indexwriter with the create parameter as true. It will start a new index deleting the contents of the existing one. </p>
|
<p>As Jokin said, the easiest was is to delete all of the files within the directory. i.e.;</p>
<pre><code>DirectoryInfo directoryInfo = new DirectoryInfo(@"IndexLocation");
Parallel.ForEach(directoryInfo.GetFiles(), file => {
file.Delete();
});
</code></pre>
| 23,873
|
<p>I'm moving DB from MySQL (used ODBC) to MS SQL and I want to "translate" SQL queries to LINQ. Can someone help me with this (it should SUM Charge column for every location and group result by months):</p>
<pre><code>SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC
</code></pre>
<p>?</p>
<p>Output should look like this:</p>
<pre><code>Location1 | Location2 | Location3 | date
</code></pre>
<p>EDIT:</p>
<p>I tryed to use LINQ sample from here:</p>
<p><a href="https://stackoverflow.com/questions/167304/is-it-possible-to-pivot-data-using-linq">Is it possible to Pivot data using LINQ?</a></p>
<pre><code>var query = context.log_sales
.GroupBy(c => c.OrderTime)
.Select(g => new
{
Date = g.Key,
Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
}).ToList();
</code></pre>
<p>and it is almost what I need. There should be grouping by year too and I don't know how to do this.</p>
|
<p>This might help.</p>
<pre><code>context.log_sales
.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})
.Select
( g => new {
Date = new DateTime(g.Key.Year, g.Key.Month, 1),
Location1 = g.Where(s => s.Location == "Location1").Sum(s => s.Charge),
Location2 = g.Where(s => s.Location == "Location2").Sum(s => s.Charge),
Location3 = g.Where(s => s.Location == "Location3").Sum(s => s.Charge),
}
)
.OrderBy(x => x.Date);
</code></pre>
|
<p>.. do You know maybe how to make adding Locations to Select dynamically? For example from List/Array.</p>
<p>EDIT: .. or maybe making Locations to load dynamically and setting which Locations should be loaded in Where statement before Select. Is this possible?</p>
| 22,199
|
<p>I have this simple regex,</p>
<pre><code>[\d]{1,5}
</code></pre>
<p>that matches any integer between 0 and 99999.</p>
<p>How would I modify it so that it didn't match 0, but matches 01 and 10, etc?</p>
<p>I know there is a way to do an OR like so...</p>
<pre><code>[\d]{1,5}|[^0]{1}
</code></pre>
<p>(doesn't make much sense)</p>
<p>There a way to do an AND?</p>
|
<p>probably better off with something like:</p>
<p>0*[1-9]+[\d]{0,4}</p>
<p>If I'm right that translates to "zero or more zeros followed by at least one of the characters included in '1-9' and then up to 4 trailing decimal characters"</p>
<p>Mike</p>
|
<pre><code>^([1-9][0-9]{0,4}|[0-9]{,1}[1-9][0-9]{,3}|[0-9]{,2}[1-9][0-9]{,2}|[0-9]{,3}[1-9][0-9]|[0-9]{,4}[1-9])$
</code></pre>
<p>Not pretty, but it should work. This is more of a brute force approach. There's a better way to do it via grouping as well, but I'm drawing a blank on the actual implementation at the moment.</p>
| 27,469
|
<p>Does anyone have recommendations/experience of how to find people willing to do usability testing of web based apps? I suspect I may need people who might actually be potential users, because mine is a commercial/vertical app which contains some processes and terminology which may not mean much to the average joe/jane.</p>
<p>I have a fairly robust prototype of a web app which is designed for people in Sales Management and before I go too much further with it I want to try a couple of key pieces out on some live users. I have a few friendly faces I can turn to (and have already), but I really want strangers who will not feel they need to be nice to me about it.</p>
<p>I'm fine designing the usability tests themselves, it is finding the guinea-pigs that is proving difficult.</p>
|
<p>I've used this service a couple times and have been impressed with the quality of the feedback they provide.</p>
<p><a href="http://www.usertesting.com/" rel="noreferrer">usertesting.com</a></p>
|
<p>I read this a few days ago and it might help: </p>
<p><a href="http://www.joelonsoftware.com/uibook/fog0000000249.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/uibook/fog0000000249.html</a></p>
| 36,978
|
<p>I work at a small company and our production system uses a hand-rolled RESTful API, implemented in Java with JAXB. We now find that we're taking on customers who use Ruby on Rails, and I have to come up with a reference implementation to show customers how to use our API in Ruby. I'd love to be able to just tell them to use ActiveResource, but the XML required by our API uses (and absolutely requires) namespaces. Unfortunately, we've already got a number of other customers who've already integrated this API, so removing the usage of namespaces is out of the question. What's the best way to generate XML with namespaces in Ruby ?</p>
|
<p>"Best" obviously depends on your needs.</p>
<p>The <em>fastest</em> way to generate any XML in ruby is to use <a href="http://libxml.rubyforge.org/" rel="nofollow noreferrer">libxml-ruby</a> - <a href="http://libxml.rubyforge.org/rdoc/" rel="nofollow noreferrer">link to rdoc</a>.
If your server gets any kind of load at all, this will be the way to go.</p>
<p>The <em>easiest</em> way to generate any XML in ruby is to use <a href="http://www.germane-software.com/software/rexml/doc/" rel="nofollow noreferrer">REXML</a> as it's part of the standard library and therefore it "just works". If your XML generation is something that hardly ever gets used, it's probably easier to just go with rexml.</p>
<p>Both support XML namespaces - check the rdocs to find out how to set and get namespaces</p>
|
<p>I find myself in almost an identical situation as yours (RESTful API done with JAXB w/ namespaces). </p>
<p>I think the most promising project for working with XML in Ruby is HappyMapper. It is a kind of XML binding library (along the lines of an early JAXB-type implementation). It has been gaining a lot of traction recently, and a few of us have been working on providing good namespace support.</p>
<p>The project resides here:
<a href="http://happymapper.rubyforge.org/" rel="nofollow noreferrer">http://happymapper.rubyforge.org/</a></p>
<p>with the source here:
<a href="http://github.com/jnunemaker/happymapper/tree/master" rel="nofollow noreferrer">http://github.com/jnunemaker/happymapper/tree/master</a></p>
<p>The project currently doesn't support creation of XML from Ruby Objects, and the original author has expressed no desire to provide that support, but I'll be committing some functionality for that in my fork:
<a href="http://github.com/jimmyz/happymapper/tree/master" rel="nofollow noreferrer">http://github.com/jimmyz/happymapper/tree/master</a></p>
<p>Hope this helps.</p>
<p>--
Jimmy Zimmerman</p>
| 30,843
|
<p>I am designing a class that stores (caches) a set of data. I want to lookup a value, if the class contains the value then use it and modify a property of the class. I am concerned about the design of the public interface.<br>
Here is how the class is going to be used:</p>
<pre>
ClassItem *pClassItem = myClass.Lookup(value);
if (pClassItem)
{ // item is found in class so modify and use it
pClassItem->SetAttribute(something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>However I don't want to have to expose ClassItem to this client (ClassItem is an implementation detail of MyClass).
To get round that the following could be considered:</p>
<pre>
bool found = myClass.Lookup(value);
if (found)
{ // item is found in class so modify and use it
myClass.ModifyAttribute(value, something);
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>However this is inefficient as Modify will have to do the lookup again. This would suggest a lookupAndModify type of method:</p>
<pre>
bool found = myClass.LookupAndModify(value, something);
if (found)
{ // item is found in class
... // use myClass
}
else
{ // value doesn't exist in the class so add it
myClass.Add(value, something);
}
</pre>
<p>But rolling LookupAndModify into one method seems like very poor design. It also only modifies if value is found and so the name is not only cumbersome but misleading as well.</p>
<p>Is there another better design that gets round this issue? Any design patterns for this (I couldn't find anything through google)?</p>
|
<p>Two things.</p>
<p>The first solution is close.</p>
<p>Don't however, return <code>ClassItem *</code>. Return an "opaque object". An integer index or other hash code that's opaque (meaningless) to the client, but usable by the myClass instance.</p>
<p>Then lookup returns an index, which modify can subsequently use.</p>
<pre><code>void *index = myClass.lookup( value );
if( index ) {
myClass.modify( index, value );
}
else {
myClass.add( value );
}
</code></pre>
<p>After writing the "primitive" Lookup, Modify and Add, then write your own composite operations built around these primitives.</p>
<p>Write a LookupAndModify, TryModify, AddIfNotExists and other methods built from your lower-level pieces.</p>
|
<p>This assumes that you're setting value to the same "something" in both the Modify and Add cases:</p>
<pre><code>if (!myClass.AddIfNotExists(value, something)) {
// use myClass
}
</code></pre>
<p>Otherwise:</p>
<pre><code>if (myClass.TryModify(value, something)) {
// use myClass
} else {
myClass.Add(value, otherSomething);
}
</code></pre>
| 15,436
|
<p>I work on Linux all the time and I'm clueless about Windows, not even having a Windows box. Is Git nowadays working on Windows? Or am I making problems for my Windows pals by using it?</p>
|
<p>As far as I can tell <a href="http://code.google.com/p/msysgit/" rel="nofollow noreferrer">msysgit</a> works perfectly well under Windows Vista.</p>
<p>This after a whole 2-month experience checking out plugins and applications for Ruby on Rails :-)</p>
<p>Anyway, it was a breeze to install, no problem.</p>
|
<p>It works, but not well. If you Google around a bit, you'll find <a href="http://code.google.com/p/msysgit" rel="nofollow noreferrer">the port which uses MinGW</a>. The main problems are instability and some very Linux-like tools (gittk). If you really need it though, you should be able to get by.</p>
| 15,110
|
<p>I'm implementing a <strong>email newsletter sender service</strong> using .NET and Windows Server technologies. Are there comprehensive guidelines which could help <strong>avoiding emails being trapped by spam filters</strong> and other mechanisms?</p>
<p>They should cover all aspects of (legal) bulk mail sending: SMTP configuration, DNS, HTML content, images, links within content etc. A simple example: is it better to embed images or load them from a server?</p>
<p>It would be great if you could provide some empirical data to show the efficiency of some measures taken.</p>
|
<p>Although I don't have a definitive answer, I think this is a very important question.
Here are few tidbits I know about it</p>
<ol>
<li>Choose a clean hosting/smtp server. IP addresses of spamming SMTP servers are often black-listed by other ISPs.</li>
<li>Send a simple introductory email to every subscriber, asking them to add your sender address to their safe list.</li>
<li>Be very prudent in sending to only those people who are actually expecting it. You wouldn't want pattern recognizers of spam filters learning the smell of your content.</li>
<li>If you don't know your smtp servers in advance, its a good practice to provide configuration options in your application for controlling batch sizes and delay between batches. Some servers don't like large batches or continuous activity.</li>
</ol>
|
<p>Unless you have a very specific reason to host the newsletter yourself, I think you'd be much better off using a third party service. There are lots out there, and some are very cheaply priced.</p>
<ol>
<li><p>It'll save you on development work
(no point in re-inventing the
wheel).</p></li>
<li><p>Their system will handle all
the unsubscribe link stuff that you
need to include in email newsletters
to comply with CAN SPAM laws or
whatever.</p></li>
<li><p>They handle the spam
reports that you will inevitably get
if you have a list of any non-trivial size.
They keep records of who signed up,
how they signed up, and their IP
address, and can present those on
receipt of a spam report to prove
that their service wasn't sending
out spam.</p></li>
<li><p>You can use double-opt in
(or confirmed opt in), for extra
evidence to prove that the people
you're sending emails to actually
signed up to receive them.</p></li>
</ol>
<p>If you really do need to host it yourself I'd suggest you search the web for "email deliverability". Things that are known to help include properly set up SPF records, DomainKeys/DKIM, correct DNS settings (reverse DNS especially - best to just use an online service to check your DNS settings). You can test a lot of these things by sending an email to check-auth@verifier.port25.com.</p>
<p>It's best to avoid using spammy words in your email - always a bit of guesswork this but you some words can trip filters.</p>
<p>But I'd guess that by far the most important thing is to be sending your email from a trusted server that maintains good relationships with ISPs (i.e. ensuring that ISPs don't think that the server is sending out spam). This is a big reason why it's much much easier to get a third party to handle everything for you.</p>
| 14,610
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.