id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
33,323,049
Angular 2's equivalent to window.location.href?
<p>How can one navigate to a different URL within Angular 2? I know that we can use JavaScript's</p> <blockquote> <p>window.location.href = '...';</p> </blockquote> <p>But that seems wrong and would cause a page refresh. I am pretty sure that there should be functionality in Angular 2 that will allow you to move between URLs without refreshing the page. I just can't seem to find it in the documentation. </p> <p>Thanks in advance! </p>
33,323,173
1
0
null
2015-10-24 20:34:26.9 UTC
1
2017-10-31 09:46:24.053 UTC
2017-01-25 18:37:45.36 UTC
null
1,205,871
null
4,375,197
null
1
16
angular|angular-new-router
41,080
<p>According to the documentation, you can use <strong>Router</strong> and its <strong>navigate</strong> function to change current state, and also pass the parameters, if neccessary:</p> <pre><code>import {Component, ...} from 'angular2/angular2'; import {Router, ...} from 'angular2/router'; import {HomeCmp} from '../home/home'; @Component({ selector: 'app', // params of your component here }) @RouteConfig([ { path: '/', component: HomeCmp, as: 'MyHome' }, // your other states here ]) export class AppCmp { router: Router; constructor(router: Router) { this.router = router; } navigateToHome() { // for example, that's how we can navigate to our home route this.router.navigate(['./MyHome', {param: 3}]); } } </code></pre> <p>Here is the link to the <a href="https://angular.io/guide/router" rel="nofollow noreferrer">official documentation</a>.</p> <p>And here is a <a href="https://github.com/mgechev/angular2-seed" rel="nofollow noreferrer">link</a> to seed project with a great example of using Router.</p>
21,641,522
How to remove specific special characters in R
<p>I have some sentences like this one.</p> <pre><code>c = "In Acid-base reaction (page[4]), why does it create water and not H+?" </code></pre> <p>I want to remove all special characters except for '?&amp;+-/</p> <p>I know that if I want to remove all special characters, I can simply use</p> <pre><code>gsub("[[:punct:]]", "", c) "In Acidbase reaction page4 why does it create water and not H" </code></pre> <p>However, some special characters such as + - ? are also removed, which I intend to keep. </p> <p>I tried to create a string of special characters that I can use in some code like this</p> <pre><code>gsub("[special_string]", "", c) </code></pre> <p>The best I can do is to come up with this </p> <pre><code>cat("!\"#$%()*,.:;&lt;=&gt;@[\\]^_`{|}~.") </code></pre> <p>However, the following code just won't work</p> <pre><code>gsub("[cat("!\"#$%()*,.:;&lt;=&gt;@[\\]^_`{|}~.")]", "", c) </code></pre> <p>What should I do to remove special characters, except for a few that I want to keep?</p> <p>Thanks</p>
21,641,569
3
0
null
2014-02-08 03:29:20.393 UTC
5
2018-03-14 08:59:19.843 UTC
2018-03-14 08:59:19.843 UTC
null
680,068
null
3,193,265
null
1
15
r|regex|character|gsub
70,477
<pre><code>gsub("[^[:alnum:][:blank:]+?&amp;/\\-]", "", c) # [1] "In Acid-base reaction page4 why does it create water and not H+?" </code></pre>
18,899,464
Possible to avoid ActiveRecord::ConnectionTimeoutError on Heroku?
<p>On Heroku I have a rails app running that with both a couple web dynos as well as one worker dyno. I'm running thousands of worker tasks throughout the day on Sidekiq however occasionally the ActiveRecord::ConnectionTimeoutError is raised (approximately 50 times a day). I've set up my unicorn server as follows</p> <pre><code>worker_processes 4 timeout 30 preload_app true before_fork do |server, worker| # As suggested here: https://devcenter.heroku.com/articles/rails-unicorn Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end if defined?(ActiveRecord::Base) ActiveRecord::Base.connection.disconnect! end end after_fork do |server,worker| if defined?(ActiveRecord::Base) config = Rails.application.config.database_configuration[Rails.env] config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 10 # seconds config['pool'] = ENV['DB_POOL'] || 10 ActiveRecord::Base.establish_connection(config) end Sidekiq.configure_client do |config| config.redis = { :size =&gt; 1 } end Sidekiq.configure_server do |config| config = Rails.application.config.database_configuration[Rails.env] config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 10 # seconds config['pool'] = ENV['DB_POOL'] || 10 ActiveRecord::Base.establish_connection(config) end end </code></pre> <p>On heroku I've set the DB_POOL config variable to 2 as <a href="https://devcenter.heroku.com/articles/concurrency-and-database-connections" rel="noreferrer">recommended by Heroku</a>. Should these errors be happening at all? Seems odd that it would be impossible to avoid such errors, no? What would you suggest?</p>
18,927,851
2
0
null
2013-09-19 15:53:06.4 UTC
8
2017-03-30 18:57:48.45 UTC
2013-10-25 19:05:08.973 UTC
null
149,503
null
812,939
null
1
9
ruby-on-rails|activerecord|heroku|unicorn|sidekiq
5,125
<p>A sidekiq server (the process running on your server that is actually performing the delayed tasks) will by default dial up to 25 threads to process work off its queue. Each of these threads could be requesting a connection to your primary database through ActiveRecord if your tasks require it. </p> <p>If you only have a connection pool of 5 connections, but you have 25 threads trying to connect, after 5 seconds the threads will just give up if they can't get an available connection from the pool and you'll get a connection time out error.</p> <p>Setting the pool size for your Sidekiq server to something closer to your concurrency level (set with the <code>-c</code> flag when you start the process) will help alleviate this issue at the cost of opening many more connections to your database. If you are on Heroku and are using Postgres for example, some of their plans are limited to 20, whereas others have a connection limit of 500 (<a href="https://devcenter.heroku.com/articles/heroku-postgres-plans" rel="nofollow noreferrer">source</a>).</p> <p>If you are running a multi-process server environment like Unicorn, you also need to monitor the number of connections each forked process makes as well. If you have 4 unicorn processes, and a default connection pool size of 5, your unicorn environment at any given time could have 20 live connections. You can read more about that on <a href="https://devcenter.heroku.com/articles/concurrency-and-database-connections#connection-pool" rel="nofollow noreferrer">Heroku's docs</a>. Note also that the DB pool size doesn’t mean that each dyno will now have that many open connections, but only that if a new connection is needed it will be created until a maximum of that many have been created.</p> <p>With that said, here is what I do.</p> <pre><code># config/initializers/unicorn.rb if ENV['RACK_ENV'] == 'development' worker_processes 1 listen "#{ENV['BOXEN_SOCKET_DIR']}/rails_app" timeout 120 else worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2) timeout 29 end # The timeout mechanism in Unicorn is an extreme solution that should be avoided whenever possible. # It will help catch bugs in your application where and when your application forgets to use timeouts, # but it is expensive as it kills and respawns a worker process. # see http://unicorn.bogomips.org/Application_Timeouts.html # Heroku recommends a timeout of 15 seconds. With a 15 second timeout, the master process will send a # SIGKILL to the worker process if processing a request takes longer than 15 seconds. This will # generate a H13 error code and you’ll see it in your logs. Note, this will not generate any stacktraces # to assist in debugging. Using Rack::Timeout, we can get a stacktrace in the logs that can be used for # future debugging, so we set that value to something less than this one preload_app true # for new relic before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end if defined?(ActiveRecord::Base) ActiveRecord::Base.connection.disconnect! end end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT' end Rails.logger.info("Done forking unicorn processes") #https://devcenter.heroku.com/articles/concurrency-and-database-connections if defined?(ActiveRecord::Base) db_pool_size = if ENV["DB_POOL"] ENV["DB_POOL"] else ENV["WEB_CONCURRENCY"] || 2 end config = Rails.application.config.database_configuration[Rails.env] config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 10 # seconds config['pool'] = ENV['DB_POOL'] || 2 ActiveRecord::Base.establish_connection(config) # Turning synchronous_commit off can be a useful alternative when performance is more important than exact certainty about the durability of a transaction ActiveRecord::Base.connection.execute "update pg_settings set setting='off' where name = 'synchronous_commit';" Rails.logger.info("Connection pool size for unicorn is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}") end end </code></pre> <p>And for sidekiq:</p> <pre><code># config/initializers/sidekiq.rb Sidekiq.configure_server do |config| sidekiq_pool = ENV['SIDEKIQ_DB_POOL'] || 20 if defined?(ActiveRecord::Base) Rails.logger.debug("Setting custom connection pool size of #{sidekiq_pool} for Sidekiq Server") db_config = Rails.application.config.database_configuration[Rails.env] db_config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 10 # seconds cb_config['pool'] = sidekiq_pool ActiveRecord::Base.establish_connection(db_config) Rails.logger.info("Connection pool size for Sidekiq Server is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}") end end </code></pre> <p>If all goes well, when you fire up your processes you'll see something like in your log:</p> <pre><code>Setting custom connection pool size of 10 for Sidekiq Server Connection pool size for Sidekiq Server is now: 20 Done forking unicorn processes (1.4ms) update pg_settings set setting='off' where name = 'synchronous_commit'; Connection pool size for unicorn is now: 2 </code></pre> <p>Sources: </p> <ul> <li><a href="https://devcenter.heroku.com/articles/concurrency-and-database-connections#connection-pool" rel="nofollow noreferrer">https://devcenter.heroku.com/articles/concurrency-and-database-connections#connection-pool</a></li> <li><a href="https://github.com/mperham/sidekiq/issues/503" rel="nofollow noreferrer">https://github.com/mperham/sidekiq/issues/503</a></li> <li><a href="https://github.com/mperham/sidekiq/wiki/Advanced-Options" rel="nofollow noreferrer">https://github.com/mperham/sidekiq/wiki/Advanced-Options</a></li> </ul>
18,917,768
Why composer install timeouts after 300 seconds?
<p>I have small project made in symfony2 when I try to build it on my server it's always fails when unzipping symfony. Build was OK and suddenly composer won't unzip symfony and I didn't change anything. I tried to build with Jenkins and also manually from bash with same result. It's not permissions problem and also internet connection on my server is OK.</p> <pre><code>Loading composer repositories with package information Installing dependencies (including require-dev) from lock file - Installing symfony/symfony (v2.3.4) Downloading: 100% [Symfony\Component\Process\Exception\ProcessTimedOutException] The process "unzip '/path/vendor/symfony/symfony/6116f6f3 d4125a757858954cb107e64b' -d 'vendor/composer/b2f33269' &amp;&amp; chmod -R u+w 'vendor/composer/b2f33269'" exceeded the timeout of 300 seconds. </code></pre>
18,917,919
10
0
null
2013-09-20 13:15:05.79 UTC
27
2021-05-01 10:44:52.527 UTC
2014-11-02 02:17:55.69 UTC
null
55,075
null
1,269,774
null
1
93
symfony|timeout|composer-php
99,387
<p>try <code>composer update/install -o -vvv</code> and check wether the package is being loaded from composer's cache.</p> <p>if yes try clearing composer's cache or try adding <code>-cache-dir=/dev/null</code>.</p> <p>To force downloading an archive instead of cloning sources, use the <code>--prefer-dist</code> option in combination with <code>--no-dev</code>.</p> <p>Otherwise you could try raising composer's process timeout value:</p> <pre><code>export COMPOSER_PROCESS_TIMEOUT=600 ( defaults to 300 ) </code></pre>
27,125,340
Material "close" button in Toolbar instead of Back
<p>I have seen in Google's Inbox App, composing a new email, in the toolbar instead of the back button (an arrow) it has a "close" button (see picture). </p> <p>How can I achieve this?</p> <p><img src="https://i.stack.imgur.com/nhMUX.png" alt="inbox compose close button"></p>
27,125,463
7
0
null
2014-11-25 11:24:22.347 UTC
15
2022-07-04 11:59:07.58 UTC
2016-08-27 00:26:15.4 UTC
null
1,788,806
null
755,240
null
1
83
android|android-actionbar|material-design
52,636
<p>Use  </p> <pre><code>this.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_close); </code></pre> <p> </p> <p>to achieve this.</p> <p>You can create your own close icon or get from <a href="https://github.com/google/material-design-icons" rel="noreferrer">material design icon set </a>on GitHub. Also, add this line before above line to make close function as the back arrow.</p> <pre><code>this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); </code></pre>
17,808,177
What is the difference between setContentView and LayoutInflater?
<p>I am creating a tabs list with several fragments. I have noticed that, in the main activity, I used <code>setContentView</code> to get the layout xml and use <code>findViewById</code> to get the corresponding UI element config.</p> <pre><code>setContentView(R.layout.fragment_tabs); mTabHost = (TabHost)findViewById(android.R.id.tabhost); mTabHost.setup(); mTabManager = new TabManager(this, mTabHost, android.R.id.tabcontent); </code></pre> <p>However, in the different fragment class, I have to use the inflater instead. </p> <pre><code>View v = inflater.inflate(R.layout.webview, container, false); WebView myBrowser=(WebView)v.findViewById(R.id.mybrowser); </code></pre> <p>And both function are used to get the layout xml to create an object, why is there a difference? Is the first one use during <code>onCreate</code>, and the second one during <code>onCreateView</code>? In what situation I should choose either of them?</p>
17,808,405
1
1
null
2013-07-23 10:54:53.097 UTC
15
2020-06-05 02:07:13.813 UTC
2018-12-18 01:24:20.26 UTC
null
3,924,118
null
782,104
null
1
27
android|layout|xml-parsing|android-lifecycle|layout-inflater
14,857
<p><code>setContentView</code> is an <code>Activity</code> method only. Each <code>Activity</code> is provided with a <code>FrameLayout</code> with id <code>"@+id/content"</code> (i.e. the content view). Whatever view you specify in <code>setContentView</code> will be the view for that <code>Activity</code>. Note that you can also pass an instance of a view to this method, e.g. <code>setContentView(new WebView(this));</code> The version of the method that you are using will inflate the view for you behind the scenes.</p> <p>Fragments, on the other hand, have a lifecycle method called <code>onCreateView</code> which returns a view (if it has one). The most common way to do this is to inflate a view in XML and return it in this method. In this case you need to inflate it yourself though. Fragments don't have a <code>setContentView</code> method</p> <p>Activities and views both have a method called <code>findViewById()</code>. The activity version will search for a view with the given id inside of it's content view (therefore, internally, it will call <code>contentView.findViewById())</code>. This means that the contentView needs to be set before it becomes usable. Like <code>setContentView</code>, fragments don't have a method for <code>findViewById</code> (which makes sense, because there is no content view). Simply use <code>getView().findViewById()</code> instead for the same behaviour.</p> <p><code>LayoutInflater.inflate</code> just inflates and returns a view (you can use this anywhere). You still need to set that view as the content view within an Activity</p>
30,702,490
How to fix WordPress HTTPS issues when behind an Amazon Load Balancer?
<p>I've had this issue before. When running WordPress (or other PHP scripts) behind Amazon's EC2 Load Balancer, the scripts do not realize they are being ran on the https:// protocol and results in issues such as endless redirect loops, and HTTPS warnings ("Some content on this page is being requested in a non-secure way...").</p> <p>I found a solution here, but requires modifying WordPress core, which is no good for updatability: <a href="https://wordpress.org/support/topic/when-behind-amazon-web-services-elastic-load-balancer-causes-endless-redirect" rel="noreferrer">https://wordpress.org/support/topic/when-behind-amazon-web-services-elastic-load-balancer-causes-endless-redirect</a></p> <p>Is there a way to fix this without modifying WordPress core? I am using Apache 2.2.</p>
30,702,491
6
0
null
2015-06-08 06:29:03.76 UTC
19
2022-04-06 05:54:37 UTC
2019-04-13 17:45:21.76 UTC
null
771,496
null
1,526,208
null
1
57
wordpress|amazon-web-services|amazon-ec2|https|amazon-elb
35,846
<p>Like the link, you gave suggested, for WordPress the issue lies in the <code>is_ssl()</code> function, which like most PHP software explicitly checks the <code>$_SERVER['HTTPS']</code> and <code>$_SERVER['SERVER_PORT']</code> to check if the current page is being accessed in the https:// context.</p> <p>When your page is accessed over HTTPS, but the Amazon Load Balancer is performing SSL offloading and actually requesting your content on the non-SSL port 80, the webserver, PHP, or anything else for that matter, does not understand or see that it's being accessed over https://.</p> <p>The fix for this is that Amazon's ELB sends the de-facto standard <code>X-Forwarded-Proto</code> HTTP header, which we can use to figure out which protocol the client is <em>actually</em> using on the other side of the Load Balancer.</p> <p>With Apache 2.2, you could use something along the lines of:</p> <pre><code>&lt;IfModule mod_setenvif.c&gt; SetEnvIf X-Forwarded-Proto &quot;^https$&quot; HTTPS &lt;/IfModule&gt; </code></pre> <p>This simply reads the <code>X-Forwarded-Proto</code> header. If this value equals <code>https</code> then the <code>HTTPS</code> environment variable is set to <code>1</code>. PHP will see this environment variable, and eventually, it will become <code>$_SERVER['HTTPS']</code> that equals <code>1</code> -- just like it would be for a &quot;real&quot; native SSL request.</p>
30,417,223
How to add menu button without action bar?
<p>I'd like to add a menu button to the right top corner of my app and without action bar, like it is in Google Fit app on the screenshot below. Can anyone help me?</p> <p><img src="https://i.stack.imgur.com/bK5BW.png" alt="menu button without action bar"></p>
30,417,316
4
0
null
2015-05-23 20:23:35.71 UTC
10
2020-10-06 07:08:44.7 UTC
null
null
null
null
3,185,707
null
1
45
android|android-menu
30,479
<p>You can simply use <code>PopupMenu</code>, for example add the following to a button when clicked:</p> <pre><code>public void showPopup(View v) {     PopupMenu popup = new PopupMenu(this, v);     MenuInflater inflater = popup.getMenuInflater();     inflater.inflate(R.menu.actions, popup.getMenu());     popup.show(); } </code></pre> <p>Kotlin</p> <pre class="lang-kotlin prettyprint-override"><code>fun showPopup(v : View){ val popup = PopupMenu(this, v) val inflater: MenuInflater = popup.menuInflater inflater.inflate(R.menu.actions, popup.menu) popup.setOnMenuItemClickListener { menuItem -&gt; when(menuItem.itemId){ R.id.action1-&gt; { } R.id.action2-&gt; { } } true } popup.show() } </code></pre> <p>For more info, read <code>Creating a Popup Menu</code> : <a href="http://developer.android.com/guide/topics/ui/menus.html" rel="noreferrer">http://developer.android.com/guide/topics/ui/menus.html</a></p>
36,232,137
How to Lazy Initialize with a parameter in Kotlin
<p>In Kotlin, I could perform Lazy Initialization without Parameter as below declaration.</p> <pre><code>val presenter by lazy { initializePresenter() } abstract fun initializePresenter(): T </code></pre> <p>However, if I have a parameter in my initializerPresenter i.e. <code>viewInterface</code>, how could I pass the parameter into the Lazy Initiallization?</p> <pre><code>val presenter by lazy { initializePresenter(/*Error here: what should I put here?*/) } abstract fun initializePresenter(viewInterface: V): T </code></pre>
36,233,649
1
0
null
2016-03-26 05:58:50.917 UTC
2
2016-03-26 13:58:24.707 UTC
2016-03-26 09:30:52.147 UTC
null
170,842
null
3,286,489
null
1
29
kotlin
16,024
<p>You can use any element within the accessible scope, that is constructor parameters, properties, and functions. You can even use other lazy properties, which can be quite useful sometimes. Here are all three variant in a single piece of code.</p> <pre><code>abstract class Class&lt;V&gt;(viewInterface: V) { private val anotherViewInterface: V by lazy { createViewInterface() } val presenter1 by lazy { initializePresenter(viewInterface) } val presenter2 by lazy { initializePresenter(anotherViewInterface) } val presenter3 by lazy { initializePresenter(createViewInterface()) } abstract fun initializePresenter(viewInterface: V): T private fun createViewInterface(): V { return /* something */ } } </code></pre> <p>And any top-level functions and properties can be used as well.</p>
44,103,711
Collection Where LIKE Laravel 5.4
<p>I know collection doesn't support where LIKE but how can I achieve this.</p> <p>My data is: <a href="https://i.stack.imgur.com/A7ldY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A7ldY.png" alt="enter image description here" /></a></p> <pre><code>collect($products)-&gt;where('name', 'LIKE', '%'. $productName . '%'); </code></pre> <p>Laravel doesn't support where like in the collection. I'm thinking to use</p> <pre><code>collect($products)-&gt;filter( function () use ($productName) { return preg_match(pattern, subject); }); </code></pre> <p>But I don't know how to do it. TY</p>
44,103,784
3
0
null
2017-05-22 02:17:10.2 UTC
8
2022-06-03 10:15:46.273 UTC
2021-12-04 16:14:50.467 UTC
null
14,807,111
null
3,345,484
null
1
28
laravel
30,213
<p>On a collection you can use the <code>filter($callback_function)</code> method to select items in the collection. Pass in a callback function that returns <code>true</code> for every item that should be returned.</p> <p>In your case you can use the <a href="http://php.net/manual/en/function.stristr.php" rel="noreferrer" title="stristr&#40;&#41;"><code>stristr()</code></a> function to emulate a <code>LIKE</code> operator, like this:</p> <pre><code>collect($products)-&gt;filter(function ($item) use ($productName) { // replace stristr with your choice of matching function return false !== stristr($item-&gt;name, $productName); }); </code></pre> <p>Just replace <code>stristr</code> with <code>preg_match</code> or what ever you need to match strings.</p> <p>This will return the collection in its original structure minus the non matching items.</p>
29,252,351
Page lifecycle events in xamarin.forms
<p>I just developed my first xamarin.forms app. I am excited about xamarin.forms, but I miss several events.</p> <p>Are there any page-lifecycle-events in a xamarin.forms ContentPage?</p> <p>I know of these two:</p> <pre><code>protected override void OnAppearing() { } protected override void OnDisappearing() { } </code></pre> <p>But the OnAppearing() event only fires once. On Android, when I push the start button and go back to my app, this event does not fire again.</p> <p>Is there a workaround for this (like OnNavigatedTo in WindowsPhone-pages)? </p> <p>Thanks.</p>
29,252,552
3
0
null
2015-03-25 09:52:17.763 UTC
3
2022-07-13 11:53:29.547 UTC
2017-06-29 12:16:57.437 UTC
null
96,944
null
2,653,134
null
1
35
c#|events|xamarin|xamarin.forms|page-lifecycle
61,336
<p>So the <code>OnAppearing</code> event is fired when your page is appearing. I.e. you have navigated to that page or back to that page from another in the Stack. There is currently no <code>Page Lifecycle</code> events as you can see from the <a href="http://iosapi.xamarin.com/?link=T%3AXamarin.Forms.Page%2F*">API documentation</a></p> <p>I think what you are talking about is if you put your application to sleep and navigate back into it the <code>OnAppearing</code> event is not fired, This is because your page hasn't appeared because it was already there, the application was just asleep.</p> <p>What you are looking for is the <a href="http://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/app-lifecycle/"><code>App Lifecycle</code></a> which includes methods such as:</p> <pre><code>protected override void OnStart() { Debug.WriteLine ("OnStart"); } protected override void OnSleep() { Debug.WriteLine ("OnSleep"); } protected override void OnResume() { Debug.WriteLine ("OnResume"); } </code></pre> <p>You can then use the <code>OnResume</code> event to do what you are looking for.</p> <p>That Xamarin Document includes the changes that must be made to old Xamarin projects to access these events. e.g. your <code>App</code> class in your shared library must inherit from <code>Xamarin.Forms.Application</code> and changes must also be made to the <code>AppDelegate</code> and <code>MainActivity</code>.</p>
29,747,583
Unit test and private vars
<p>I'm writing a BDD unit test for a <strong>public method</strong>. The method changes a private property (<code>private var</code>) so I'd like to write an expect() and ensure it's being set correctly. Since it's private, I can't work out how access it from the unit test target.</p> <p>For Objective-C, I'd just add an extension header. Are there any similar tricks in Swift? As a note, the property has a didSet() with some code as well.</p>
30,294,145
1
0
null
2015-04-20 12:12:51.48 UTC
1
2018-02-20 13:13:29.133 UTC
2018-02-20 13:13:29.133 UTC
null
2,227,743
null
4,486,058
null
1
36
unit-testing|swift|bdd
9,625
<p>(Note that Swift 2 adds the <code>@testable</code> attribute which can make internal methods and properties available for testing. See @JeremyP's comments below for some more information.)</p> <p>No. In Swift, private is private. The compiler can use this fact to optimize, so depending on how you use that property, it is legal for the compiler to have removed it, inlined it, or done any other thing that would give the correct behavior based on the code actually in that file. (Whether the optimizer is actually that smart today or not, it's allowed to be.)</p> <p>Now of course if you declare your class to be <code>@objc</code>, then you can break those optimizations, and you can go poking around with ObjC to read it. And there are bizarre workarounds that can let you use Swift to call arbitrary <code>@objc</code> exposed methods (like a zero-timeout <code>NSTimer</code>). But don't do that.</p> <p>This is a classic testing problem, and the classic testing answer is don't test this way. Don't test internal state. If it is literally impossible to tell from the outside that something has happened, then there is nothing to test. Redesign the object so that it is testable across its public interface. And usually that means composition and mocks.</p> <p>Probably the most common version of this problem is caching. It's very hard to test that something is actually cached, since the only difference may be that it is retrieved faster. But it's still testable. Move the caching functionality into another object, and let your object-under-test accept a custom caching object. Then you can pass a mock that records whether the right cache calls were made (or networking calls, or database calls, or whatever the internal state holds).</p> <p>Basically the answer is: redesign so that it's easier to test.</p> <p>OK, but you really, really, really need it... how to do it? OK, it is possible without breaking the world.</p> <p>Create a function inside the file to be tested that exposes the thing you want. Not a method. Just a free function. Then you can put that helper function in an <code>#if TEST</code>, and set <code>TEST</code> in your testing configuration. Ideally I'd make the function actually test the thing you care about rather than exposing the variable (and in that case, maybe you can let the function be internal or even public). But either way.</p>
29,699,372
promise resolve before inner promise resolved
<p>I have a promise and I want it to resolve only when inner promise has resolved. Right now it resolves before the "resolve" function has been reached in the "loadend" callback.</p> <p>What am I missing? I am confused about the way you are supposed to use resolve and about how you can use a promise within another promise.</p> <p>I couldn't find anything that helped on the web.</p> <p>In the following example I basically load a bunch of files, for each file I get a blob and I want to pass this blob in a file reader.</p> <p>Once all files have been passed to the file reader, I want to move to the next function in the promise chain.</p> <p>Right now it goes to the next function in the chain without waiting for resolve to be called.</p> <pre><code>var list = []; var urls = this.files; urls.forEach(function(url, i) { list.push( fetch(url).then(function(response) { response.blob().then(function(buffer) { var promise = new Promise( function(resolve) { var myReader = new FileReader(); myReader.addEventListener('loadend', function(e) { // some time consuming operations ... window.console.log('yo'); resolve('yo'); }); //start the reading process. myReader.readAsArrayBuffer(buffer); }); promise.then(function() { window.console.log('smooth'); return 'smooth'; }); }); }) ); }); ... // run the promise... Promise .all(list) .then(function(message){ window.console.log('so what...?'); }) .catch(function(error) { window.console.log(error); }); </code></pre>
29,699,544
1
0
null
2015-04-17 12:34:18.133 UTC
10
2015-04-17 12:47:50.073 UTC
null
null
null
null
2,568,650
null
1
9
javascript|promise|ecmascript-6|resolve|es6-promise
6,558
<p>When you don't <code>return</code> anything from <code>then</code> callbacks, it assumes synchronous operation and goes to resolve the result promise with the result (<code>undefined</code>) immediately.</p> <p>You need to <strong><code>return</code> a promise from every asynchronous function</strong>, including <code>then</code> callbacks that you want to get chained.</p> <p>Specifically, your code should become</p> <pre><code>var list = this.files.map(function(url, i) { // ^^^^ easier than [] + forEach + push return fetch(url).then(function(response) { return response.blob().then(function(buffer) { return new Promise(function(resolve) { var myReader = new FileReader(); myReader.addEventListener('loadend', function(e) { … resolve('yo'); }); myReader.readAsArrayBuffer(buffer); }).then(function() { window.console.log('smooth'); return 'smooth'; }); }) }); }); </code></pre> <p>or even better, <a href="https://stackoverflow.com/a/22000931/1048572">flattened</a>:</p> <pre><code>var list = this.files.map(function(url, i) { return fetch(url).then(function(response) { return response.blob(); }).then(function(buffer) { return new Promise(function(resolve) { var myReader = new FileReader(); myReader.addEventListener('loadend', function(e) { … resolve('yo'); }); myReader.readAsArrayBuffer(buffer); }); }).then(function() { window.console.log('smooth'); return 'smooth'; }); }); </code></pre>
22,087,881
How to save and edit a file using JavaScript?
<p>I want a user of my website to enter some text in a text area and when he submits the form, the text that he entered be stored in a .txt file that is present in same directory of the current web page? I don't have a slight idea how it's done or even if it could be done in JavaScript. <h3>How can it be done?</h3></p>
22,088,011
5
1
null
2014-02-28 06:30:03.243 UTC
4
2018-09-24 04:43:59.857 UTC
2014-02-28 06:33:01.71 UTC
null
1,931,841
null
3,279,988
null
1
11
javascript|html|file
49,945
<p>Yes you can, HTML5 File API has a <code>saveAs</code> API that can be used to save binary data using Javascript. You can generate a .txt file by first getting the data into a canvas and saving it as:</p> <pre><code>canvas.toBlob(function(blob) { saveAs(blob, filename); }); </code></pre> <p>See this demo, the text file is actually generated in browser without PHP. <a href="http://eligrey.com/demos/FileSaver.js/" rel="noreferrer">http://eligrey.com/demos/FileSaver.js/</a></p> <p>There is an excellent article written back in 2011 by Eli Grey on html5rocks: <a href="http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side" rel="noreferrer">http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side</a></p> <p>More reading at W3C: <a href="http://www.w3.org/TR/file-writer-api/#the-filesaver-interface" rel="noreferrer">Filesaver interface</a></p> <hr> <p><strong>Edit 2016 Update</strong></p> <p>My original answer showed an example using the BlobBuilder interface which has since been <a href="https://developer.mozilla.org/en-US/docs/Web/API/BlobBuilder" rel="noreferrer">deprecated and marked as obsolete</a>. It is now recommended to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob" rel="noreferrer">Blob Construct</a> to manipulate binary data.</p> <p>At the time of posting, Blob construct is <a href="http://caniuse.com/#search=blob" rel="noreferrer">supported on all major browsers</a>. IE 11, Edge 13, Firefox 43, Chrome 45, Safari 9, Opera 35, iOS Safari 8.4, Android Chrome 49.</p> <p>Demo:</p> <ul> <li>Koldev has posted jsfiddle how to use this new construct to save a json file.</li> <li>Link: <a href="https://jsfiddle.net/koldev/cW7W5/" rel="noreferrer">https://jsfiddle.net/koldev/cW7W5/</a></li> </ul> <p>More reading:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob" rel="noreferrer">MDN Blob Documentation</a></li> <li><a href="http://caniuse.com/#search=blob" rel="noreferrer">Caniuse Blob construction</a></li> </ul>
23,900,862
Allow A Header View for Only Certain Sections Using an iOS UICollectionView
<p>The code below displays my header view correctly, but for each of the sections in the UICollectionView:</p> <pre><code>-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SectionHeaderCollectionReusableView" forIndexPath:indexPath]; switch (indexPath.section) { case Section_One: return headerView; case Section_Two: return headerView; case Section_Three: return headerView; case Section_Four: return headerView; case Section_Five: return headerView; default: return headerView; } } </code></pre> <p>What I would like to do instead, is not display a header view for 'Section_One' or 'Section_Two', but returning 'nil' results in an 'NSInternalInconsistencyException':</p> <pre><code>-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SectionHeaderCollectionReusableView" forIndexPath:indexPath]; switch (indexPath.section) { case Section_One: return nil; case Section_Two: return nil; case Section_Three: return headerView; case Section_Four: return headerView; case Section_Five: return headerView; default: return nil; } } </code></pre> <p>What do I need to do to display a header view for only certain sections?</p>
23,915,346
5
2
null
2014-05-28 00:00:35.54 UTC
7
2022-06-10 07:39:34.787 UTC
null
null
null
null
3,670,931
null
1
34
ios|objective-c|uicollectionview|uicollectionreusableview
20,013
<p>Go ahead and return a header for each section and then set the size of the section header to have a size of zero in this UICollectionViewDelegate function.</p> <pre><code>- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { if (section == 0) { return CGSizeZero; }else { return CGSizeMake(self.collectionView.bounds.size.width, desiredHeight); } } </code></pre>
43,017,251
Solve almostIncreasingSequence (Codefights)
<p>Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.</p> <p>Example</p> <p>For sequence <code>[1, 3, 2, 1]</code>, the output should be:</p> <pre><code>almostIncreasingSequence(sequence) = false; </code></pre> <p>There is no one element in this array that can be removed in order to get a strictly increasing sequence.</p> <p>For sequence <code>[1, 3, 2]</code>, the output should be:</p> <pre><code>almostIncreasingSequence(sequence) = true. </code></pre> <p>You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].</p> <p>My code:</p> <pre><code>def almostIncreasingSequence(sequence): c= 0 for i in range(len(sequence)-1): if sequence[i]&gt;=sequence[i+1]: c +=1 return c&lt;1 </code></pre> <p>But it can't pass all tests.</p> <pre><code>input: [1, 3, 2] Output:false Expected Output:true Input: [10, 1, 2, 3, 4, 5] Output: false Expected Output: true Input: [0, -2, 5, 6] Output: false Expected Output: true input: [1, 1] Output: false Expected Output: true Input: [1, 2, 3, 4, 3, 6] Output: false Expected Output: true Input: [1, 2, 3, 4, 99, 5, 6] Output: false Expected Output: true </code></pre>
43,017,981
26
3
null
2017-03-25 13:57:21.647 UTC
13
2022-08-07 10:47:37.093 UTC
2017-03-25 14:19:55.97 UTC
null
7,741,140
null
7,741,140
null
1
40
python|arrays
54,181
<p>Your algorithm is much too simplistic. You have a right idea, checking consecutive pairs of elements that the earlier element is less than the later element, but more is required.</p> <p>Make a routine <code>first_bad_pair(sequence)</code> that checks the list that all pairs of elements are in order. If so, return the value <code>-1</code>. Otherwise, return the index of the earlier element: this will be a value from <code>0</code> to <code>n-2</code>. Then one algorithm that would work is to check the original list. If it works, fine, but if not try deleting the earlier or later offending elements. If either of those work, fine, otherwise not fine.</p> <p>I can think of other algorithms but this one seems the most straightforward. If you do not like the up-to-two temporary lists that are made by combining two slices of the original list, the equivalent could be done with comparisons in the original list using more <code>if</code> statements.</p> <p>Here is Python code that passes all the tests you show.</p> <pre><code>def first_bad_pair(sequence): """Return the first index of a pair of elements where the earlier element is not less than the later elements. If no such pair exists, return -1.""" for i in range(len(sequence)-1): if sequence[i] &gt;= sequence[i+1]: return i return -1 def almostIncreasingSequence(sequence): """Return whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.""" j = first_bad_pair(sequence) if j == -1: return True # List is increasing if first_bad_pair(sequence[j-1:j] + sequence[j+1:]) == -1: return True # Deleting earlier element makes increasing if first_bad_pair(sequence[j:j+1] + sequence[j+2:]) == -1: return True # Deleting later element makes increasing return False # Deleting either does not make increasing </code></pre> <p>If you do want to avoid those temporary lists, here is other code that has a more complicated pair-checking routine.</p> <pre><code>def first_bad_pair(sequence, k): """Return the first index of a pair of elements in sequence[] for indices k-1, k+1, k+2, k+3, ... where the earlier element is not less than the later element. If no such pair exists, return -1.""" if 0 &lt; k &lt; len(sequence) - 1: if sequence[k-1] &gt;= sequence[k+1]: return k-1 for i in range(k+1, len(sequence)-1): if sequence[i] &gt;= sequence[i+1]: return i return -1 def almostIncreasingSequence(sequence): """Return whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.""" j = first_bad_pair(sequence, -1) if j == -1: return True # List is increasing if first_bad_pair(sequence, j) == -1: return True # Deleting earlier element makes increasing if first_bad_pair(sequence, j+1) == -1: return True # Deleting later element makes increasing return False # Deleting either does not make increasing </code></pre> <p>And here are the tests I used.</p> <pre><code>print('\nThese should be True.') print(almostIncreasingSequence([])) print(almostIncreasingSequence([1])) print(almostIncreasingSequence([1, 2])) print(almostIncreasingSequence([1, 2, 3])) print(almostIncreasingSequence([1, 3, 2])) print(almostIncreasingSequence([10, 1, 2, 3, 4, 5])) print(almostIncreasingSequence([0, -2, 5, 6])) print(almostIncreasingSequence([1, 1])) print(almostIncreasingSequence([1, 2, 3, 4, 3, 6])) print(almostIncreasingSequence([1, 2, 3, 4, 99, 5, 6])) print(almostIncreasingSequence([1, 2, 2, 3])) print('\nThese should be False.') print(almostIncreasingSequence([1, 3, 2, 1])) print(almostIncreasingSequence([3, 2, 1])) print(almostIncreasingSequence([1, 1, 1])) </code></pre>
30,460,649
Spring MVC - Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml];
<p>I have been struggling with the following exception occurring in my Spring-MVC project for a few days already. There are some similar issues on the web but neither of them helped me really. I am using Eclipse as my IDE. My folder structure.</p> <p><img src="https://i.stack.imgur.com/GDWPo.png" alt="This is my folder Structure"></p> <p>pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.infofaces&lt;/groupId&gt; &lt;artifactId&gt;MavenInfofaces&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;MavenInfofaces Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- JSTL --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring framework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring&lt;/artifactId&gt; &lt;version&gt;2.5.6&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring MVC framework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;2.5.6&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Commons Upload --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt; &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt; &lt;version&gt;1.2.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Commons Upload --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-io&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- MySql Connector --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.35&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Core Hibernate ORM Functionality --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;4.3.8.Final&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;MavenInfofaces&lt;/finalName&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>web.xml</p> <pre><code>&lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt;Archetype Created Web Application&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;*.html&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>mvc-dispatcher-servlet.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;context:component-scan base-package="com.infofaces.myself.controller" /&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" &gt; &lt;property name="prefix"&gt; &lt;value&gt;/WEB-INF/pages/&lt;/value&gt; &lt;/property&gt; &lt;property name="suffix"&gt; &lt;value&gt;.jsp&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>Exception while starting Tomcat Server 8.0.</p> <pre><code>INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] May 26, 2015 7:23:27 PM org.springframework.util.xml.SimpleSaxErrorHandler warning WARNING: Ignored XML validation warning org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-beans-3.0.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not &lt;xsd:schema&gt;. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaWarning(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument1(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4909) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.net.UnknownHostException: www.springframework.org at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.&lt;init&gt;(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaDOMParser.parse(Unknown Source) ... 47 more May 26, 2015 7:23:27 PM org.springframework.web.servlet.FrameworkServlet initServletBean SEVERE: Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 12 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; cvc-elt.1: Cannot find the declaration of element 'beans'. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4909) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; cvc-elt.1: Cannot find the declaration of element 'beans'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) ... 27 more May 26, 2015 7:23:27 PM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 12 in XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; cvc-elt.1: Cannot find the declaration of element 'beans'. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:404) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4909) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; cvc-elt.1: Cannot find the declaration of element 'beans'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) ... 27 more May 26, 2015 7:23:27 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet [mvc-dispatcher] in web application [/MavenInfofaces] threw load() exception org.xml.sax.SAXParseException; lineNumber: 12; columnNumber: 80; cvc-elt.1: Cannot find the declaration of element 'beans'. at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:342) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:310) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:92) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:123) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:422) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:402) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:316) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:282) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:126) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4909) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5196) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) </code></pre> <p>I am newbie to Spring MVC and Maven projects. Please help me to get rid of this issue.</p>
30,461,302
3
2
null
2015-05-26 13:56:11.86 UTC
null
2017-06-23 07:06:09.21 UTC
null
null
null
null
3,449,149
null
1
4
java|spring|maven|spring-mvc
39,192
<p>A simple careless mistake. As Deinum said in comment.. There is Spring 3.0 schema files in web.xml but using Spring 2.5. I changed my pom.xml to get Spring 3.0 jars and it worked fine. </p> <p>pom.xml</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.infofaces&lt;/groupId&gt; &lt;artifactId&gt;MavenInfofaces&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;MavenInfofaces Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- JSTL --&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;jstl&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring framework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;3.0.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring MVC framework --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;3.0.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Commons Upload --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-fileupload&lt;/groupId&gt; &lt;artifactId&gt;commons-fileupload&lt;/artifactId&gt; &lt;version&gt;1.2.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Apache Commons Upload --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-io&lt;/groupId&gt; &lt;artifactId&gt;commons-io&lt;/artifactId&gt; &lt;version&gt;1.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- MySql Connector --&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.35&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Core Hibernate ORM Functionality --&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;version&gt;4.3.8.Final&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;MavenInfofaces&lt;/finalName&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Thanks M.Deinum.</p>
53,785,791
Difference in the end of lifetime rules?
<p><a href="https://en.cppreference.com/w/cpp/language/lifetime" rel="noreferrer">https://en.cppreference.com/w/cpp/language/lifetime</a> in <strong>Notes</strong> section has this code, reproduced here:</p> <pre><code>struct A { int* p; ~A() { std::cout &lt;&lt; *p; } // if n outlives a, prints 123 }; void f() { A a; int n = 123; // if n does not outlive a, this is optimized out (dead store) a.p = &amp;n; } </code></pre> <p>What is it trying to say in this <strong>Notes</strong> section? </p> <p>From what I understand, the code is UB (or is it) as it's clear that <code>n</code> does not outlive <code>a</code>.</p> <p>What does it mean by:</p> <blockquote> <p>difference in the end of lifetime rules between non-class objects (end of storage duration) and class objects (reverse order of construction) matters</p> </blockquote> <p>But it does not say matter <strong>how</strong>.</p> <p>I am very confused by this entire section.</p>
53,785,998
2
4
null
2018-12-14 19:26:02.113 UTC
5
2018-12-15 03:28:58.417 UTC
null
null
null
null
2,288,628
null
1
33
c++|language-lawyer|undefined-behavior
1,080
<p>This is an odd aspect of C++'s lifetime rules. <a href="https://timsong-cpp.github.io/cppwp/basic.life#1" rel="noreferrer">[basic.life]/1 tells us</a> that an object's lifetime ends:</p> <blockquote> <ul> <li>if <code>T</code> <strong>is a class type with a non-trivial destructor</strong> ([class.dtor]), the destructor call starts, or</li> <li>the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).</li> </ul> </blockquote> <p>Emphasis added. <code>int</code> is not a "class type with a non-trivial destructor", so its lifetime <em>only ends</em> when the storage it occupies is released. By contrast, <code>A</code> is a class type with a non-trivial destructor", so its lifetime ends when the destructor gets called.</p> <p>The storage for a scope is released when the scope exits, pursuant to <a href="https://timsong-cpp.github.io/cppwp/n4659/basic.stc.auto" rel="noreferrer">[basic.stc.auto]/1</a>:</p> <blockquote> <p>The storage for [variables with automatic storage duration] lasts until the block in which they are created exits.</p> </blockquote> <p>But automatic variables are destroyed in accord with <a href="https://timsong-cpp.github.io/cppwp/n4659/stmt.jump#2" rel="noreferrer">[stmt.jump]/2</a>:</p> <blockquote> <p>On exit from a scope (however accomplished), objects with automatic storage duration that have been constructed in that scope are destroyed in the reverse order of their construction.</p> </blockquote> <p>Notice that the order of destruction is specified, but the order of automatic storage release is <em>not</em> specified. This means that the implementation could release the storage right after each variable is destroyed, or release it all at once later, or in some arbitrary other order.</p> <p>Now, the fact that it uses the singular for storage ("the storage for ... lasts") rather than talking about each variable individually may suggest that the intent is for the storage as a whole to be released at once for that scope. But there is no explicit statement of this in the standard. So as long as a variable is destroyed before its storage is released, any ordering of destruction vs. release appears to be legal.</p> <p>This means it is entirely possible for the code to work, for <code>n</code> to outlive <code>a</code>. But it is unspecified whether it <em>does</em> work.</p>
32,195,745
update the database from package manager console in code first environment
<h1>Code First Environment</h1> <p>I'm trying to update the database from package Manager console.If my Domain class change, I have to drop and create the database,Instead of dropping the Database how can i update the database.</p> <p>I have already try by reading some blogs in google.</p> <h2>commands</h2> <pre><code>PM&gt; Install-Package EntityFramework </code></pre> <ol> <li><p>By using this command i install the Entity Framework successfully.</p> <pre><code> PM&gt; Enable-Migrations </code></pre> </li> <li><p>By using this command it created the Migration file in my project.</p> <pre><code> PM&gt; Update-Database </code></pre> </li> <li><p>By using this command , i may update the table but i have a <strong>Problem here</strong>.</p> </li> </ol> <h1>Error</h1> <blockquote> <p>Specify the '-Verbose' flag to view the SQL statements being applied to the target database. System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.</p> </blockquote> <h1>Doubt is here</h1> <p>Sometimes It may update if only one field changes in <strong>POCO</strong> Class. For example I have Updated the <strong>more number of Domain class</strong> ,How can i Update the Database from Package manager Console. Any Idea ?</p>
32,195,857
5
2
null
2015-08-25 04:50:42.503 UTC
12
2018-07-11 14:34:29.52 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,234,662
null
1
31
c#|sql-server|visual-studio-2012|entity-framework-6|entity-framework-migrations
102,653
<p>You can specify connection string via <code>ConnectionString</code> parameter:</p> <pre><code>Update-Database -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose </code></pre> <p>Also you need to use this parameter with the same value for <code>Add-Migration</code> command:</p> <pre><code>Add-Migration Version_Name -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose </code></pre>
34,774,807
Get URL of a newly created asset, iOS 9 style
<p><code>ALAssetsLibrary</code> is deprecated these days but practically all examples on SO are still making use of it. For my objective, I need to know the URL of the video that was added to the Photo Library so I could share a video to the Instagram app (that's the only way in which Instagram accepts videos). The URL should probably start with "assets-library://..."</p> <p>This is simple with <code>ALAssetsLibrary</code>:</p> <pre><code>ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) { // ... </code></pre> <p>Above, the URL is passed as an argument to the completion block. But what about iOS 9 compatible way with <code>PHPhotoLibrary</code> class and <code>performChanges</code> method?</p> <pre><code>var videoAssetPlaceholder:PHObjectPlaceholder! // property // ... let videoURL = NSBundle.mainBundle().URLForResource("Video_.mp4", withExtension: nil)! let photoLibrary = PHPhotoLibrary.sharedPhotoLibrary() photoLibrary.performChanges({ let request = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) self.videoAssetPlaceholder = request?.placeholderForCreatedAsset }, completionHandler: { success, error in if success { // The URL of the video asset? } }) </code></pre>
34,788,748
2
2
null
2016-01-13 18:53:27.073 UTC
8
2017-08-03 16:16:50.257 UTC
2016-01-13 21:53:03.007 UTC
null
944,687
null
944,687
null
1
15
ios|swift|alassetslibrary|photokit
9,721
<p>Here's what I've ended up with:</p> <pre><code>let videoURL = NSBundle.mainBundle().URLForResource("Video_.mp4", withExtension: nil)! let photoLibrary = PHPhotoLibrary.sharedPhotoLibrary() var videoAssetPlaceholder:PHObjectPlaceholder! photoLibrary.performChanges({ let request = PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(videoURL) videoAssetPlaceholder = request!.placeholderForCreatedAsset }, completionHandler: { success, error in if success { let localID = videoAssetPlaceholder.localIdentifier let assetID = localID.stringByReplacingOccurrencesOfString( "/.*", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil) let ext = "mp4" let assetURLStr = "assets-library://asset/asset.\(ext)?id=\(assetID)&amp;ext=\(ext)" // Do something with assetURLStr } }) </code></pre>
67,448,034
"Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.16"
<p>I am a beginner in Kotlin App Development. The following error occurs when I tried to build the app -</p> <pre><code>e: C:/Users/Lenovo/.gradle/caches/transforms-2/files-2.1/32f0bb3e96b47cf79ece6482359b6ad2/jetified-kotlin-stdlib-jdk7-1.5.0.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.16 </code></pre> <p><a href="https://i.stack.imgur.com/yG6Kj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yG6Kj.jpg" alt="enter image description here" /></a></p> <p>Is it about updating the module? Then how to update it?</p>
67,816,693
27
4
null
2021-05-08 13:21:36.257 UTC
9
2022-09-12 08:24:36.867 UTC
2022-09-12 08:24:36.867 UTC
null
5,746,918
null
14,099,703
null
1
168
android|android-studio|kotlin
174,517
<p>For someone who is still looking for answer to this, here is the working solution for this problem. In your project level open <code>build.gradle</code> file, increase the <code>ext.kotlin_version</code> from whatever current version that you have like <code>1.5.0</code>, to the latest stable version <code>1.6.0</code> (Whatever is latest at that time). Thanks</p> <p>You can get latest version from here:</p> <p><a href="https://kotlinlang.org/docs/releases.html#release-details" rel="noreferrer">https://kotlinlang.org/docs/releases.html#release-details</a></p>
19,921,972
Parsing HTML into NSAttributedText - how to set font?
<p>I am trying to get a snippet of text that is formatted in html to display nicely on an iPhone in a UITableViewCell.</p> <p>So far I have this:</p> <pre><code>NSError* error; NSString* source = @"&lt;strong&gt;Nice&lt;/strong&gt; try, Phil"; NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:[source dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:&amp;error]; </code></pre> <p>This kind of works. I get some text that has 'Nice' in bold! But... it also sets the font to be Times Roman! This is not the font face I want. I am thinking I need to set something in the documentAttributes, but, I can't find any examples anywhere.</p>
19,953,767
17
2
null
2013-11-12 05:56:33.277 UTC
56
2022-05-08 05:52:23.047 UTC
2013-11-12 05:59:55.557 UTC
null
1,226,963
null
447,303
null
1
153
html|ios|nsattributedstring
89,634
<p>Figured it out. Bit of a bear, and maybe not the best answer.</p> <p>This code will go through all the font changes. I know that it is using "Times New Roman" and "Times New Roman BoldMT" for the fonts. But regardless, this will find the bold fonts and let me reset them. I can also reset the size while I'm at it.</p> <p>I honestly hope/think there is a way to set this up at parse time, but I can't find it if there is.</p> <pre><code> NSRange range = (NSRange){0,[str length]}; [str enumerateAttribute:NSFontAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) { UIFont* currentFont = value; UIFont *replacementFont = nil; if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch].location != NSNotFound) { replacementFont = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:25.0f]; } else { replacementFont = [UIFont fontWithName:@"HelveticaNeue-Thin" size:25.0f]; } [str addAttribute:NSFontAttributeName value:replacementFont range:range]; }]; </code></pre>
7,654,386
How do I properly escape data for a Makefile?
<p>I'm dynamically generating <code>config.mk</code> with a bash script which will be used by a Makefile. The file is constructed with:</p> <pre><code>cat &gt; config.mk &lt;&lt;CFG SOMEVAR := $value_from_bash1 ANOTHER := $value_from_bash2 CFG </code></pre> <p>How do I ensure that the generated file really contains the contents of <code>$value_from_bash*</code>, and not something expanded / interpreted? I probably need to escape <code>$</code> to <code>$$</code> and <code>\</code> to <code>\\</code>, but are there other characters that needs to be escaped? Perhaps there is a special literal assignment I've not heard of?</p> <p>Spaces seems to be troublesome too:</p> <pre><code>$ ls -1 a b a $ cat Makefile f := a b default_target: echo "$(firstword $(wildcard ${f}))" $ make a </code></pre> <p>If I use <code>f := a\ b</code> it works (using quotes like <code>f := 'a b'</code> did not work either, makefile just treats it as a regular character)</p>
7,860,705
3
3
null
2011-10-04 21:41:37.043 UTC
10
2018-04-19 05:53:54.467 UTC
2011-10-18 20:29:25.74 UTC
null
202,229
null
427,545
null
1
53
bash|makefile|escaping
65,381
<p>Okay, it turned out that Makefiles need little escaping for itself, but the commands which are executed by the shell interpreter <em>need</em> to be escaped.</p> <p>Characters which have a special meaning in Makefile and that need to be escaped are:</p> <ul> <li>sharp (<code>#</code>, comment) becomes <code>\#</code></li> <li>dollar (<code>$</code>, begin of variable) becomes <code>$$</code></li> </ul> <p>Newlines cannot be inserted in a variable, but to avoid breaking the rest of the Makefile, prepend it with a backslash so the line break will be ignored.</p> <p>Too bad a backslash itself cannot be escaped (<code>\\</code> will still be <code>\\</code> and not <code>\</code> as you might expect). This makes it not possible to put a literal slash on the end of a string as it will either eat the newline or the hash of a following comment. A space can be put on the end of the line, but that'll also be put in the variable itself.</p> <p>The recipe itself is interpreted as a shell command, without any fancy escaping, so you've to escape data yourself, just imagine that you're writing a shellscript and inserting the variables from other files. The strategy here would be putting the variables between single quotes and escape only <code>'</code> with <code>'\''</code> (close the string, insert a literal <code>'</code> and start a new string). Example: <code>mornin' all</code> becomes <code>'morning'\'' all'</code> which is equivalent to <code>"morning' all"</code>.</p> <p>The firstword+wildcard issue is caused by the fact that filenames with spaces in them are treated as separate filenames by <code>firstword</code>. Furthermore, <code>wildcard</code> expands escapes using <code>\</code> so <code>x\ y</code> is matches as one word, <code>x y</code> and not two words.</p>
7,340,452
Process output from apache-commons exec
<p>I am at my wits end here. I'm sure this is something simple and I most likely have huge holes in my understanding of java and streams. I think there are so many classes that I'm a bit overwhelmed with trying to poke through the API to figure out when and how I want to use the multitude of input/output streams.</p> <p>I just learned about the existence of the apache commons library (self teaching java fail), and am currently trying to convert some of my Runtime.getRuntime().exec to use the commons - exec. Already it's fixed some of the once every 6 months this problem crops up then goes away style problems with exec.</p> <p>The code executes a perl script, and displays the stdout from the script in the GUI as it is running. </p> <p>The calling code is inside of a swingworker.</p> <p>I'm getting lost how to use the pumpStreamHandler... anyway here is the old code:</p> <pre><code>String pl_cmd = "perl script.pl" Process p_pl = Runtime.getRuntime().exec( pl_cmd ); BufferedReader br_pl = new BufferedReader( new InputStreamReader( p_pl.getInputStream() ) ); stdout = br_pl.readLine(); while ( stdout != null ) { output.displayln( stdout ); stdout = br_pl.readLine(); } </code></pre> <p>I guess this is what I get for copy pasting code I don't fully understand a long time ago. The above I assume is executing the process, then grabs the outputstream (via "getInputStream"?), places it into a buffered reader, then will just loop there until the buffer is empty. </p> <p>What I don't get is why there is no need for a 'waitfor' style command here? Isn't it possible that there will be some time in which the buffer will be empty, exit the loop, and continue on while the process is still going? When I run it, this doesn't seem to be the case.</p> <p>In any event, I'm trying to get the same behavior using commons exec, basically again going from google found code:</p> <pre><code>DefaultExecuteResultHandler rh = new DefaultExecuteResultHandler(); ExecuteWatchdog wd = new ExecuteWatchdog( ExecuteWatchdog.INFINITE_TIMEOUT ); Executor exec = new DefaultExecutor(); ByteArrayOutputStream out = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler( out ); exec.setStreamHandler( psh ); exec.setWatchdog( wd ); exec.execute(cmd, rh ); rh.waitFor(); </code></pre> <p>I'm trying to figure out what pumpstreamhandler is doing. I assume that this will take the output from the exec object, and fill the OutputStream I provide it with the bytes from the perl script's stdout/err?</p> <p>If so how would you get the above behavior to have it stream the output line by line? In examples people show you call the out.toString() at the end, and I assume this would just give me a dump of all the output from the script once it is done running? How would you do it such that it would show the output as it is running line by line?</p> <p>------------Future Edit ---------------------</p> <p>Found this via google and works nice as well:</p> <pre><code>public static void main(String a[]) throws Exception { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); CommandLine cl = CommandLine.parse("ls -al"); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(psh); exec.execute(cl); System.out.println(stdout.toString()); } </code></pre>
12,301,247
4
2
null
2011-09-07 20:57:33.747 UTC
2
2019-05-16 09:56:04.697 UTC
2013-05-29 19:52:32.597 UTC
null
680,907
null
680,907
null
1
29
java|apache-commons|apache-commons-exec
24,705
<p>Don't pass a <code>ByteArrayOutputStream</code> to the <code>PumpStreamHandler</code>, use an implementation of the abstract class <code>org.apache.commons.exec.LogOutputStream</code>. From <a href="http://commons.apache.org/proper/commons-exec/apidocs/index.html?org/apache/commons/exec/PumpStreamHandler.html" rel="nofollow noreferrer">the javadoc</a>: </p> <blockquote> <p>The implementation parses the incoming data to construct a line and passes the complete line to an user-defined implementation.</p> </blockquote> <p>Thus the LogOutputStram is preprocessing the output to give you the control of handling individual lines instead of the raw bytes. Something like this:</p> <pre class="lang-java prettyprint-override"><code>import java.util.LinkedList; import java.util.List; import org.apache.commons.exec.LogOutputStream; public class CollectingLogOutputStream extends LogOutputStream { private final List&lt;String&gt; lines = new LinkedList&lt;String&gt;(); @Override protected void processLine(String line, int level) { lines.add(line); } public List&lt;String&gt; getLines() { return lines; } } </code></pre> <p>Then after the blocking call to <code>exec.execute</code> your <code>getLines()</code> will have the standard out and standard error you are looking for. The <code>ExecutionResultHandler</code> is optional from the perspective of just executing the process, and collecting all the stdOut/stdErr into a list of lines.</p>
8,061,166
Syntax to include separate Sass file?
<p>I can't confirm that this syntax is best practice. I would like to reference an external Sass file and have it prepend it to my final CSS file, this way my Sass sheet looks more clean, and I'm only still only making one HTTP request.</p> <p>For example, take the "normalize" code and put it into a .sass file, then in my sass sheets simply refer to it:</p> <pre><code>@import src/normalize @import src/droidSans rest of code here..... </code></pre> <p>It works fine so far, but I can't find anything concrete if I'm headed in the right direction. Also I am just making static templates for the time being... not using Rails at the moment.</p> <p>I have been playing around with Sass for a few hours and I love it!!!</p>
8,061,239
1
2
null
2011-11-09 06:24:55.407 UTC
6
2016-05-03 16:49:59.5 UTC
2014-09-14 14:26:48.17 UTC
null
1,696,030
null
775,600
null
1
45
css|sass
51,039
<p>In order to prevent your partial from being converted into its own css file, prefix the filename with an underscore, <code>_normalize.scss</code>. Then you can import it the way you've indicated you're doing already:</p> <pre><code>@import "normalize"; </code></pre> <p>Or import many files at once:</p> <pre><code>@import "normalize", "droidSans"; </code></pre> <p>Or import from a relative directory:</p> <pre><code>@import "folder/file" </code></pre> <p>Note the use of double-quotes and semi-colon; I'm using the SCSS syntax which is a later development to the SASS word. While both styles are valid, you may find yourself preferring one over the other depending on what other languages you dabble in.</p> <p>Further reading can be found under <em>Directives/Partials</em> in <a href="http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#directives" rel="noreferrer">the documentation</a>.</p>
21,568,072
Should I always call vector clear() at the end of the function?
<p>I have some simple function that uses vector like this (pseudo code):</p> <pre><code>void someFunc(void) { std::vector&lt;std::string&gt; contentVector; // here are some operations on the vector // should I call the clear() here or this could be ommited ? contentVector.clear(); } </code></pre> <p>Should I call the clear() or this could be ommited ?</p>
21,568,133
5
3
null
2014-02-05 03:27:23.793 UTC
8
2014-02-06 18:52:32.197 UTC
null
null
null
null
1,449,403
null
1
30
c++|vector|stl|stdvector
12,495
<p>If we look at the <a href="http://en.cppreference.com/w/" rel="noreferrer">cppreference.com</a> entry for <a href="http://en.cppreference.com/w/cpp/container/vector/~vector" rel="noreferrer">std::vector::~vector</a> it says:</p> <blockquote> <p>Destructs the container. The destructors of the elements are called and the used storage is deallocated. Note, that if the elements are pointers, the pointed-to objects are not destroyed. </p> </blockquote> <p>so no you don't have to call <a href="http://en.cppreference.com/w/cpp/container/vector/clear" rel="noreferrer">clear</a>.</p> <p>If we want to go to the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3485.pdf" rel="noreferrer">draft standard</a>, we have to look at section <code>23.2.1</code> <em>General container requirements</em> paragraph <em>4</em> which says:</p> <blockquote> <p>In Tables 96 and 97, X denotes a container class containing objects of type T, a and b denote values of type X,[...]</p> </blockquote> <p>and then look at <code>Table 96 — Container requirements</code> which has the following expression entry:</p> <pre><code>(&amp;a)-&gt;~X() </code></pre> <p>and the following note:</p> <blockquote> <p>note: the destructor is applied to every element of a; all the memory is deallocated.</p> </blockquote> <p><B>Update</B></p> <p>This is <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> in action and as <em>Bjarne Stroustrup</em> says in <a href="http://www.stroustrup.com/bs_faq2.html#finally" rel="noreferrer">Why doesn't C++ provide a "finally" construct?</a>:</p> <blockquote> <p>Because C++ supports an alternative that is almost always better: The "resource acquisition is initialization" technique (TC++PL3 section 14.4). The basic idea is to represent a resource by a local object, so that the local object's destructor will release the resource. That way, the programmer cannot forget to release the resource.</p> </blockquote>
1,955,810
div floating over table
<p>I am trying to get a div to float over a table so it will be on top of all the text?</p>
1,955,818
4
0
null
2009-12-23 23:00:17.067 UTC
1
2017-07-21 11:51:32.92 UTC
2012-06-15 17:11:59.427 UTC
null
791,629
null
119,973
null
1
7
html
48,509
<p>Check out <a href="http://www.w3.org/TR/CSS2/visuren.html#propdef-position" rel="noreferrer">absolute positioning</a>, and possibly <a href="http://www.w3.org/TR/CSS2/visuren.html#propdef-z-index" rel="noreferrer">z-index</a> as well (although if this is your only absolutely-positioned content, you won't need it). Although there are other ways to get things to overlap, that's probably the most relevant for you.</p> <p>Very simple example:</p> <p>CSS:</p> <pre><code>#target { position: absolute; left: 50px; top: 100px; border: 2px solid black; background-color: #ddd; } </code></pre> <p>HTML:</p> <pre><code>&lt;p&gt;Something before the table&lt;/p&gt; &lt;div id="target"&gt;I'm on top of the table&lt;/div&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;td&gt;Text in the table&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><a href="http://jsbin.com/ojovag" rel="noreferrer">Live copy</a> | <a href="http://jsbin.com/ojovag/edit" rel="noreferrer">source</a></p>
1,519,141
Difference between addSubview and insertSubview in UIView class
<p>What is the difference between <code>addSubview</code> and <code>insertSubView</code> methods when a view is added programmatically?</p>
1,519,483
4
0
null
2009-10-05 09:54:37.797 UTC
17
2020-12-09 05:14:36.65 UTC
2018-07-26 06:25:41.123 UTC
null
1,113,632
null
120,322
null
1
87
iphone|uiview|uikit|subview|addsubview
63,211
<p>The only difference is in where the view is added: whether it is the frontmost view (<code>addSubview:</code>), or it is before the 5th subview, (<code>insertSubview:atIndex:</code>) or if it is immediately behind another subview (<code>insertSubview:aboveSubview:</code>).</p>
28,744,167
Android Deep linking: Use the same link for the app and the play store
<p>I have a website which enables the user to make a search query. The query might take some time to complete (minutes to days), and I would like to enable the user to download an Android app and receive the answer there, by sending an email with a link to the user.</p> <p>I would like this mechanism to work whether the user has the app installed or not; in other words:</p> <ul> <li>If the user has the app it should be opened with <a href="https://developer.android.com/training/app-indexing/deep-linking.html" rel="noreferrer">deep link</a> that contains an identifier argument.</li> <li>If the user does not have it it should open the play store on the app's page (e.g. <code>https://play.google.com/store/apps/details?id=com.bar.foo&amp;referrer=BlahBlah</code>), let the user install it, and open the app with the identifier argument.</li> </ul> <p><img src="https://i.stack.imgur.com/yc0yS.png" alt="enter image description here"></p> <p><strong>Is there a way to form a link that opens an Android application with an argument, that would work regardless if the app is installed or not?</strong></p>
28,792,160
4
3
null
2015-02-26 13:48:35.677 UTC
43
2019-04-16 20:06:07.853 UTC
null
null
null
null
51,197
null
1
75
android|deep-linking
70,802
<p>This workaround might work:</p> <ol> <li><p>At the server side, create a redirect rule to google play. For example, <code>https://www.foo.com/bar/BlahBlah</code> will redirect to <code>https://play.google.com/store/apps/details?id=com.bar.foo&amp;referrer=BlahBlah</code>. </p></li> <li><p>At the app, <a href="https://developer.android.com/training/app-indexing/deep-linking.html">register the server side link as a deep link</a>:</p></li> </ol> <pre class="lang-xml prettyprint-override"><code>&lt;data android:scheme="https" android:host="www.foo.com" android:pathPrefix="/bar" /&gt; </code></pre> <p>Now, if the app is installed, the URL will be caught and the path can be parsed to extract the <code>BlahBlah</code> part. If the app isn't installed pressing the link will redirect the user to the Play store with the referring URL.</p> <p><img src="https://i.stack.imgur.com/F8tj1.png" alt="enter image description here"></p> <p>Notes:</p> <ul> <li><code>/bar/BlahBlah</code> was converted to <code>&amp;referrer=BlahBlah</code>, because the play store receives a URL argument and the deep link mechanism works with URL paths (as far a I can tell)</li> </ul>
7,033,167
How to extract substring by start-index and end-index?
<pre><code>$str = 'HelloWorld'; $sub = substr($str, 3, 5); echo $sub; // prints "loWor" </code></pre> <p>I know that substr() takes the first parameter, 2nd parameter is start index, while 3rd parameter is substring length to extract. What I need is to extract substring by <strong>startIndex</strong> and <strong>endIndex</strong>. What I need is something like this:</p> <pre><code>$str = 'HelloWorld'; $sub = my_substr_function($str, 3, 5); echo $sub; // prints "lo" </code></pre> <p>Is there a function that does that in php? Or can you help me with a workaround solution, please?</p>
7,033,178
5
2
null
2011-08-11 21:35:11.543 UTC
7
2017-02-06 18:47:23.553 UTC
2013-02-06 13:40:37.077 UTC
null
421,223
null
134,824
null
1
49
php
64,265
<p>It's just math</p> <pre><code>$sub = substr($str, 3, 5 - 3); </code></pre> <p>The length is the end minus the start.</p>
7,227,162
Way to play video files in Tkinter?
<p>Is there a way to play video files like <a href="http://en.wikipedia.org/wiki/Audio_Video_Interleave" rel="noreferrer">AVI</a>, <a href="http://en.wikipedia.org/wiki/MPEG-4_Part_14" rel="noreferrer">MP4</a>, etc.? </p> <p>I tried using <a href="http://pymedia.org/" rel="noreferrer">PyMedia</a>, but apparently it only works with <a href="http://en.wikipedia.org/wiki/Pygame" rel="noreferrer">Pygame</a>.</p> <p>What is the solution to my problem?</p>
7,321,768
6
0
null
2011-08-29 07:13:01.067 UTC
13
2022-05-07 05:44:41.223 UTC
2015-08-22 12:46:01.457 UTC
null
3,924,118
null
724,408
null
1
23
python|video|tkinter
59,962
<p>You could use <code>python-gstreamer</code> for playing videos (this works for me on Linux, but it should also work on Windows). This requires <a href="http://gstreamer.freedesktop.org/modules/gst-python.html" rel="noreferrer"><code>python-gstreamer</code></a> and <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.24/" rel="noreferrer"><code>python-gobject</code></a>, I would recommend you to use this all-in-one installer.</p> <p>Here is the code:</p> <pre><code>import os import sys import Tkinter as tkinter import gobject import gst def on_sync_message(bus, message, window_id): if not message.structure is None: if message.structure.get_name() == 'prepare-xwindow-id': image_sink = message.src image_sink.set_property('force-aspect-ratio', True) image_sink.set_xwindow_id(window_id) gobject.threads_init() window = tkinter.Tk() window.geometry('500x400') video = tkinter.Frame(window, bg='#000000') video.pack(side=tkinter.BOTTOM,anchor=tkinter.S,expand=tkinter.YES,fill=tkinter.BOTH) window_id = video.winfo_id() player = gst.element_factory_make('playbin2', 'player') player.set_property('video-sink', None) player.set_property('uri', 'file://%s' % (os.path.abspath(sys.argv[1]))) player.set_state(gst.STATE_PLAYING) bus = player.get_bus() bus.add_signal_watch() bus.enable_sync_message_emission() bus.connect('sync-message::element', on_sync_message, window_id) window.mainloop() </code></pre>
7,223,166
onCreate() and onCreateView() invokes a lot more than required (Fragments)
<p>Can somebody explain why the <code>onCreate()</code> and <code>onCreateView()</code> are being invoked so many times which increments with each orientation change?</p> <p>Here is very simple app which consists of one <code>Activity</code> composed of two <code>Fragments</code>. The second <code>Fragment</code> loads <strong>dynamically</strong>. If you define these two <code>Fragments</code> in <code>main.xml</code> there would not be such a behavior.</p> <p>Here is <code>main.xml</code>: </p> <pre><code> &lt;fragment class="ets.saeref.Left" android:id="@+id/left_frag" android:layout_weight="70" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;FrameLayout android:id="@+id/right_frag" android:layout_weight="30" android:layout_width="match_parent" android:layout_height="match_parent"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>Here is left frag:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000"&gt; &lt;Button android:text="Landscape" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; </code></pre> <p>Here is right frag:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"&gt; &lt;Button android:text="Landscape" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; </code></pre> <p>Left.class:</p> <pre><code>public class Left extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("Left", "onCreate()"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("Left", "onCreateView()"); return inflater.inflate(R.layout.left, container, false); } } </code></pre> <p>Right.class:</p> <pre><code>public class Right extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("Right", "onCreate()"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i("Right", "onCreateView()"); return inflater.inflate(R.layout.right, container, false); } } </code></pre> <p>Main class:</p> <pre><code>public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Fragment fg = new Right(); getFragmentManager().beginTransaction().add(R.id.right_frag, fg) .commit(); Log.i("Main", "onCreate()"); } } </code></pre> <p>Log after several orientation changes:</p> <pre><code>08-28 21:47:38.220: INFO/Main(1099): onCreate() 08-28 21:47:38.220: INFO/Right(1099): onCreateView() 08-28 21:47:38.220: INFO/Right(1099): onCreateView() 08-28 21:47:38.220: INFO/Right(1099): onCreateView() 08-28 21:47:38.220: INFO/Right(1099): onCreate() 08-28 21:47:38.220: INFO/Right(1099): onCreateView() 08-28 21:47:41.110: INFO/ActivityManager(142): Config changed: {1.0 0mcc0mnc en_US sw800dp w1280dp h752dp xlrg land finger -keyb/v/h -nav/h s.162} 08-28 21:47:41.140: INFO/Right(1099): onCreate() 08-28 21:47:41.140: INFO/Right(1099): onCreate() 08-28 21:47:41.140: INFO/Right(1099): onCreate() 08-28 21:47:41.140: INFO/Right(1099): onCreate() 08-28 21:47:41.170: INFO/Left(1099): onCreate() 08-28 21:47:41.170: INFO/Left(1099): onCreateView() 08-28 21:47:41.170: INFO/Main(1099): onCreate() 08-28 21:47:41.170: INFO/Right(1099): onCreateView() 08-28 21:47:41.170: INFO/Right(1099): onCreateView() 08-28 21:47:41.170: INFO/Right(1099): onCreateView() 08-28 21:47:41.170: INFO/Right(1099): onCreateView() 08-28 21:47:41.190: INFO/Right(1099): onCreate() 08-28 21:47:41.190: INFO/Right(1099): onCreateView() 08-28 21:47:45.070: INFO/ActivityManager(142): Config changed: {1.0 0mcc0mnc en_US sw800dp w800dp h1232dp xlrg port finger -keyb/v/h -nav/h s.163} 08-28 21:47:45.120: INFO/Right(1099): onCreate() 08-28 21:47:45.120: INFO/Right(1099): onCreate() 08-28 21:47:45.120: INFO/Right(1099): onCreate() 08-28 21:47:45.120: INFO/Right(1099): onCreate() 08-28 21:47:45.120: INFO/Right(1099): onCreate() 08-28 21:47:45.130: INFO/Left(1099): onCreate() 08-28 21:47:45.130: INFO/Left(1099): onCreateView() 08-28 21:47:45.130: INFO/Main(1099): onCreate() 08-28 21:47:45.130: INFO/Right(1099): onCreateView() 08-28 21:47:45.130: INFO/Right(1099): onCreateView() 08-28 21:47:45.130: INFO/Right(1099): onCreateView() 08-28 21:47:45.140: INFO/Right(1099): onCreateView() 08-28 21:47:45.140: INFO/Right(1099): onCreateView() 08-28 21:47:45.140: INFO/Right(1099): onCreate() 08-28 21:47:45.140: INFO/Right(1099): onCreateView() </code></pre>
7,234,209
6
0
null
2011-08-28 18:57:56.643 UTC
16
2015-02-20 11:52:24.77 UTC
null
null
null
null
397,991
null
1
46
android
70,166
<p>I can't point to the documentation which explains this, but the solution is to only create and add the fragment when the activity first loads, like this:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (savedInstanceState == null) { Fragment fg = new Right(); getFragmentManager().beginTransaction().add(R.id.right_frag, fg) .commit(); } Log.i("Main", "onCreate()"); } </code></pre>
7,516,666
Home automation in C#?
<p>I want to develop a small C# application to control various components of a central heating.</p> <p>First, I would like to be able to retrieve values ​​from a temperature sensor. I must not be the first C# developer looking to get this kind of stuff. I would then try to control thermostatic valves.</p> <p>Microsoft or others vendors delivers GUI libraries, Mathematics libraries, database access libraries, ... I'm just looking for a Home Automation Library or something similar. Could you redirect me to the hardware components compatible or information sites on the subject.</p> <p>Thank you,</p>
7,516,714
7
6
null
2011-09-22 14:40:35.977 UTC
14
2014-10-18 06:50:49.15 UTC
2011-09-23 08:58:53.56 UTC
null
196,526
null
196,526
null
1
31
c#|automation|home-automation
12,319
<p>I'm playing around with a .NET development board with great fun for home automation. They come in all price ranges(some very simple and there are the ones with screens, wifi and so on) and support a compact .net framework and have a lot of sensors and relays to add on to it!</p> <p><a href="http://www.netduino.com/" rel="noreferrer">NetDuino</a></p> <p>My own project at home is that I just had a on/off switch for my warm water. I do control it with my netduino board by a fixed times but I can also switch it on from a web browser. Next version is for it to not switch on if there have been no movement in my apartment for a while so if I go off for holiday I don't have to switch it off. Also bought an servo to open my window if temp go over a certain degree :).. Next will be to have some kind recognition if a lady enters to start the soft music and the disco ball spinning!</p>
7,189,520
True-way solution in Java: parse 2 numbers from 2 strings and then return their sum
<p>Given the code:</p> <pre><code>public static int sum(String a, String b) /* throws? WHAT? */ { int x = Integer.parseInt(a); // throws NumberFormatException int y = Integer.parseInt(b); // throws NumberFormatException return x + y; } </code></pre> <p>Could you tell if it's good Java or not? What I'm talking about is, <code>NumberFormatException</code> is an unchecked exception. You <strong>don't have</strong> to specify it as part of <code>sum()</code> signature. Moreover, as far as I understand, the idea of unchecked exceptions is just to signal that program's implementation is incorrect, and even more, catching unchecked exceptions is a bad idea, since it's like <em>fixing bad program at runtime</em>.</p> <p>Would somebody please clarify whether:</p> <ol> <li>I should specify <code>NumberFormatException</code> as a part of method's signature.</li> <li>I should define my own checked exception (<code>BadDataException</code>), handle <code>NumberFormatException</code> inside the method and re-throw it as <code>BadDataException</code>.</li> <li>I should define my own checked exception (<code>BadDataException</code>), validate both strings some way like regular expressions and throw my <code>BadDataException</code> if it doesn't match.</li> <li>Your idea?</li> </ol> <p><strong>Update</strong>:</p> <p>Imagine, it's not an open-source framework, that you should use for some reason. You look at method's signature and think - &quot;OK, it never throws&quot;. Then, some day, you got an exception. Is it normal?</p> <p><strong>Update 2</strong>:</p> <p>There are some comments saying my <code>sum(String, String)</code> is a bad design. I do absolutely agree, but for those who believe that original problem would just never appear if we had good design, here's an extra question:</p> <p>The problem definition is like this: you have a data source where numbers are stored as <code>String</code>s. This source may be XML file, web page, desktop window with 2 edit boxes, whatever.</p> <p>Your goal is to implement the logic that takes these 2 <code>String</code>s, converts them to <code>int</code>s and displays message box saying &quot;the sum is xxx&quot;.</p> <p>No matter what's the approach you use to design/implement this, you'll <em>have these 2 points of inner functionality</em>:</p> <ol> <li>A place where you convert <code>String</code> to <code>int</code></li> <li>A place where you add 2 <code>int</code>s</li> </ol> <p>The primary question of my original post is:</p> <p><code>Integer.parseInt()</code> expects <em>correct</em> string to be passed. Whenever you pass a <em>bad string</em>, it means that <em>your program</em> is incorrect (not &quot;<em>your user</em> is an idiot&quot;). You need to implement the piece of code where on one hand you have Integer.parseInt() with <em>MUST semantics</em> and on the other hand you need to be OK with the cases when input is incorrect - <em>SHOULD semantics</em>.</p> <p>So, briefly: how do I implement <em>SHOULD semantics</em> if I only have <em>MUST libraries</em>.</p>
7,189,610
18
6
null
2011-08-25 11:23:34.087 UTC
19
2022-04-21 09:40:03.383 UTC
2022-04-21 09:40:03.383 UTC
null
5,446,749
null
852,604
null
1
84
java|parsing|exception
5,329
<p>This is a good question. I wish more people would think about such things.</p> <p>IMHO, throwing unchecked exceptions is acceptable if you've been passed rubbish parameters.</p> <p>Generally speaking, you shouldn't throw <code>BadDataException</code> because you shouldn't use Exceptions to control program flow. Exceptions are for the exceptional. Callers to your method can know <em>before</em> they call it if their strings are numbers or not, so passing rubbish in is avoidable and therefore can be considered a <em>programming error</em>, which means it's OK to throw unchecked exceptions.</p> <p>Regarding declaring <code>throws NumberFormatException</code> - this is not that useful, because few will notice due to NumberFormatException being unchecked. However, IDE's can make use of it and offer to wrap in <code>try/catch</code> correctly. A good option is to use javadoc as well, eg:</p> <pre><code>/** * Adds two string numbers * @param a * @param b * @return * @throws NumberFormatException if either of a or b is not an integer */ public static int sum(String a, String b) throws NumberFormatException { int x = Integer.parseInt(a); int y = Integer.parseInt(b); return x + y; } </code></pre> <p><strong>EDITED</strong>:<br> The commenters have made valid points. You need to consider how this will be used and the overall design of your app. </p> <p>If the method will be used all over the place, and it's important that all callers handle problems, the declare the method as throwing a checked exception (forcing callers to deal with problems), but cluttering the code with <code>try/catch</code> blocks.</p> <p>If on the other hand we are using this method with data we trust, then declare it as above, because it is not expected to ever explode and you avoid the code clutter of essentially unnecessary <code>try/catch</code> blocks.</p>
14,337,091
Video encode from sequence of images from java android
<p>I would like to encode video from sequence of images with java only in my current android project. I mean without any use of external tools such as NDK.<br> Also is there any availability of java libraries for encoding video from sequence of images ?</p>
16,516,152
1
0
null
2013-01-15 11:50:48.733 UTC
11
2013-05-14 16:42:46.34 UTC
null
null
null
null
1,183,691
null
1
8
java|android|image|video-encoding|android-image
14,188
<p>You can use a pure java library called JCodec ( <a href="http://jcodec.org">http://jcodec.org</a> ). It contains a primitive yet working H.264 ( AVC ) encoder and a fully functioning MP4 ( ISO BMF ) muxer.<br> Here's a <strong>CORRECTED</strong> code sample that uses low-level API: </p> <pre><code>public void imageToMP4(BufferedImage bi) { // A transform to convert RGB to YUV colorspace RgbToYuv420 transform = new RgbToYuv420(0, 0); // A JCodec native picture that would hold source image in YUV colorspace Picture toEncode = Picture.create(bi.getWidth(), bi.getHeight(), ColorSpace.YUV420); // Perform conversion transform.transform(AWTUtil.fromBufferedImage(bi), yuv); // Create MP4 muxer MP4Muxer muxer = new MP4Muxer(sink, Brand.MP4); // Add a video track CompressedTrack outTrack = muxer.addTrackForCompressed(TrackType.VIDEO, 25); // Create H.264 encoder H264Encoder encoder = new H264Encoder(rc); // Allocate a buffer that would hold an encoded frame ByteBuffer _out = ByteBuffer.allocate(ine.getWidth() * ine.getHeight() * 6); // Allocate storage for SPS/PPS, they need to be stored separately in a special place of MP4 file List&lt;ByteBuffer&gt; spsList = new ArrayList&lt;ByteBuffer&gt;(); List&lt;ByteBuffer&gt; ppsList = new ArrayList&lt;ByteBuffer&gt;(); // Encode image into H.264 frame, the result is stored in '_out' buffer ByteBuffer result = encoder.encodeFrame(_out, toEncode); // Based on the frame above form correct MP4 packet H264Utils.encodeMOVPacket(result, spsList, ppsList); // Add packet to video track outTrack.addFrame(new MP4Packet(result, 0, 25, 1, 0, true, null, 0, 0)); // Push saved SPS/PPS to a special storage in MP4 outTrack.addSampleEntry(H264Utils.createMOVSampleEntry(spsList, ppsList)); // Write MP4 header and finalize recording muxer.writeHeader(); } </code></pre> <p>You can download JCodec library from a project web site or via Maven, for this add the below snippet to your pom.xml:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.jcodec&lt;/groupId&gt; &lt;artifactId&gt;jcodec&lt;/artifactId&gt; &lt;version&gt;0.1.3&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p><strong>[UPDATE 1]</strong> Android users can use something like below to convert Android Bitmap object to JCodec native format: </p> <pre><code>public static Picture fromBitmap(Bitmap src) { Picture dst = Picture.create((int)src.getWidth(), (int)src.getHeight(), RGB); fromBitmap(src, dst); return dst; } public static void fromBitmap(Bitmap src, Picture dst) { int[] dstData = dst.getPlaneData(0); int[] packed = new int[src.getWidth() * src.getHeight()]; src.getPixels(packed, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight()); for (int i = 0, srcOff = 0, dstOff = 0; i &lt; src.getHeight(); i++) { for (int j = 0; j &lt; src.getWidth(); j++, srcOff++, dstOff += 3) { int rgb = packed[srcOff]; dstData[dstOff] = (rgb &gt;&gt; 16) &amp; 0xff; dstData[dstOff + 1] = (rgb &gt;&gt; 8) &amp; 0xff; dstData[dstOff + 2] = rgb &amp; 0xff; } } } </code></pre>
14,065,271
How to use EXECUTE FORMAT ... USING in postgres function
<pre><code>CREATE OR REPLACE FUNCTION dummytest_insert_trigger() RETURNS trigger AS $BODY$ DECLARE v_partition_name VARCHAR(32); BEGIN IF NEW.datetime IS NOT NULL THEN v_partition_name := 'dummyTest'; EXECUTE format('INSERT INTO %I VALUES ($1,$2)',v_partition_name)using NEW.id,NEW.datetime; END IF; RETURN NULL; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION dummytest_insert_trigger() OWNER TO postgres; </code></pre> <p>I'm trying to insert using insert into dummyTest values(1,'2013-01-01 00:00:00+05:30');</p> <p>But it's showing error as </p> <pre><code>ERROR: function format(unknown) does not exist SQL state: 42883 Hint: No function matches the given name and argument types. You might need to add explicit type casts. Context: PL/pgSQL function "dummytest_insert_trigger" line 8 at EXECUTE statement </code></pre> <p>I'm unable get the error.</p>
14,066,715
2
1
null
2012-12-28 06:00:26.323 UTC
null
2020-08-08 08:38:16.18 UTC
2012-12-28 06:40:45.997 UTC
null
1,933,743
null
1,933,743
null
1
8
postgresql|format|execute|using
58,569
<p>Your function could look like this in Postgres 9.0 or later:</p> <pre><code>CREATE OR REPLACE FUNCTION dummytest_insert_trigger() RETURNS trigger AS $func$ DECLARE v_partition_name text := quote_ident('dummyTest'); -- assign at declaration BEGIN IF NEW.datetime IS NOT NULL THEN EXECUTE 'INSERT INTO ' || v_partition_name || ' VALUES ($1,$2)' USING NEW.id, NEW.datetime; END IF; RETURN NULL; -- You sure about this? END $func$ LANGUAGE plpgsql; </code></pre> <p>About <code>RETURN NULL</code>:</p> <ul> <li><a href="https://stackoverflow.com/questions/31774157/to-ignore-result-in-before-trigger-of-postgresql/31892633#31892633">To ignore result in BEFORE TRIGGER of PostgreSQL?</a></li> </ul> <p>I would advice not to use mixed case identifiers. With <code>format( .. %I ..)</code> or <code>quote_ident()</code>, you'd get a table named <code>"dummyTest"</code>, which you'll have to double quote for the rest of its existence. Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/20878932/are-postgresql-column-names-case-sensitive/20880247#20880247">Are PostgreSQL column names case-sensitive?</a></li> </ul> <p>Use lower case instead:</p> <pre><code>quote_ident('dummytest') </code></pre> <p>There is really no point in using dynamic SQL with <code>EXECUTE</code> as long as you have a static table name. But that's probably just the simplified example?</p>
14,283,703
When is it a good idea to use std::promise over the other std::thread mechanisms?
<p>I am trying to establish some heuristics to help me decide the appropriate <code>std::thread</code> class to use.</p> <p>As I understand it, from highest level (simplest to use, but least flexible) to lowest level, we have:</p> <ol> <li>std::async with/std::future (std::shared_future) (when you want to execute on a one-time throw-away producer-thread async)</li> <li>std::packaged_task (when you want to assign a producer, but defer the call to the thread)</li> <li>std::promise (???)</li> </ol> <p>I think I have a decent grasp of <strong>when to use</strong> the first two, but am still unclear about <code>std::promise</code>.</p> <p><code>std::future</code> in conjunction with a <code>std::async</code> call, effectively transforms a producing callback/functor/lambda to an asynchronous call (which returns immediately, by definition). A singular consumer can call <code>std::future::get()</code>, a blocking call, to get its results back.</p> <p><code>std::shared_future</code> is just a version which allows for multiple consumers.</p> <p>If you want to bind a <code>std::future</code> value with a producer callback, <strong>but want to defer the actual invocation to a later time (when you associate the task to a spawning thread)</strong>, <code>std::packaged_task</code> is the right choice. But now, since the corresponding <code>std::future</code> to the <code>std::package_task</code> could, in the general case, be accessed by multiple-threads, we may have to take care to use a <code>std::mutex</code>. Note that with <code>std::async</code>, in the first case, we don't have to worry about locking.</p> <p>Having read <a href="https://stackoverflow.com/a/12335206/975129">some interesting links on promise</a>, I think I understand its mechanisms and how to set them up, but my question is, <strong>when would you choose to use a promise over the other three?</strong> </p> <p><em>I'm looking more for an application-level answer, like a rule-of-thumb (fill the ??? in 3. above), as opposed to the answer in the link (eg use std::promise to implement some library mechanism), so I can more easily explain how to choose the proper class to a beginning user of <code>std::thread</code>.</em></p> <p>In other words, it would be nice to have an useful example of what I can do with a <code>std::promise</code> that <strong>cannot</strong> be done with the other mechanisms.</p> <p><strong>ANSWER</strong></p> <p>A <code>std::future</code> is a strange beast: in general, you cannot modify its value directly.</p> <p>Three producers which can modify its value are:</p> <ol> <li><code>std::async</code> through an asynchronous callback, which will return a <code>std::future</code> instance.</li> <li><code>std::packaged_task</code>, which, when passed to a thread, will invoke its callback thereby updating the <code>std::future</code> instance associated with that <code>std::packaged_task</code>. This mechanism allows for early binding of a producer, but a later invocation.</li> <li><code>std::promise</code>, which allows one to modify its associated <code>std::future</code> through its <code>set_value()</code> call. With this direct control over mutating a <code>std::future</code>, we must ensure that that the design is thread-safe if there are multiple producers (use <code>std::mutex</code> as necessitated).</li> </ol> <p>I think <a href="https://stackoverflow.com/a/14283834/975129">SethCarnegie's answer</a>: </p> <blockquote> <p>An easy way to think of it is that you can either set a future by returning a value or by using a promise. future has no set method; that functionality is provided by promise.</p> </blockquote> <p>helps clarify when to use a promise. But we have to keep in mind that a <code>std::mutex</code> may be necessary, as the promise might be accessible from different threads, depending on usage.</p> <p>Also, <a href="https://stackoverflow.com/a/11004368/975129">David's Rodriguez's answer</a> is also excellent:</p> <blockquote> <p>The consumer end of the communication channel would use a std::future to consume the datum from the shared state, while the producer thread would use a std::promise to write to the shared state.</p> </blockquote> <p>But as an alternative, why not simply just use a <code>std::mutex</code> on a stl container of results, and one thread or a threadpool of producers to act on the container? What does using <code>std::promise</code>, instead, buy me, besides some extra readability vs a stl container of results? </p> <p>The control appears to be better in the <code>std::promise</code> version:</p> <ol> <li>wait() will block on a given future until the result is produced</li> <li>if there is only one producer thread, a mutex is not necessary</li> </ol> <p><em>The following google-test passes both helgrind and drd, confirming that with a single producer, and with the use of wait(), a mutex is not needed.</em></p> <p><strong>TEST</strong></p> <pre><code>static unsigned MapFunc( std::string const&amp; str ) { if ( str=="one" ) return 1u; if ( str=="two" ) return 2u; return 0u; } TEST( Test_future, Try_promise ) { typedef std::map&lt;std::string,std::promise&lt;unsigned&gt;&gt; MAP; MAP my_map; std::future&lt;unsigned&gt; f1 = my_map["one"].get_future(); std::future&lt;unsigned&gt; f2 = my_map["two"].get_future(); std::thread{ [ ]( MAP&amp; m ) { m["one"].set_value( MapFunc( "one" )); m["two"].set_value( MapFunc( "two" )); }, std::ref( my_map ) }.detach(); f1.wait(); f2.wait(); EXPECT_EQ( 1u, f1.get() ); EXPECT_EQ( 2u, f2.get() ); } </code></pre>
14,283,834
2
5
2013-01-11 22:33:51.567 UTC
2013-01-11 17:40:57.137 UTC
20
2013-01-11 22:48:49.227 UTC
2017-05-23 12:34:14.86 UTC
null
-1
null
975,129
null
1
24
c++|c++11|stdthread
19,872
<p>You don't choose to use a <code>promise</code> <em>instead</em> of the others, you use a <code>promise</code> to <em>fulfill</em> a <code>future</code> <em>in conjunction</em> with the others. The code sample at <a href="http://en.cppreference.com/w/cpp/thread/future" rel="noreferrer">cppreference.com</a> gives an example of using all four:</p> <pre><code>#include &lt;iostream&gt; #include &lt;future&gt; #include &lt;thread&gt; int main() { // future from a packaged_task std::packaged_task&lt;int()&gt; task([](){ return 7; }); // wrap the function std::future&lt;int&gt; f1 = task.get_future(); // get a future std::thread(std::move(task)).detach(); // launch on a thread // future from an async() std::future&lt;int&gt; f2 = std::async(std::launch::async, [](){ return 8; }); // future from a promise std::promise&lt;int&gt; p; std::future&lt;int&gt; f3 = p.get_future(); std::thread( [](std::promise&lt;int&gt;&amp; p){ p.set_value(9); }, std::ref(p) ).detach(); std::cout &lt;&lt; &quot;Waiting...&quot;; f1.wait(); f2.wait(); f3.wait(); std::cout &lt;&lt; &quot;Done!\nResults are: &quot; &lt;&lt; f1.get() &lt;&lt; ' ' &lt;&lt; f2.get() &lt;&lt; ' ' &lt;&lt; f3.get() &lt;&lt; '\n'; } </code></pre> <p>prints</p> <blockquote> <p>Waiting...Done!</p> <p>Results are: 7 8 9</p> </blockquote> <p>Futures are used with all three threads to get their results, and a <code>promise</code> is used with the third one to fulfill a <code>future</code> by means other than a return value. Also, a single thread can fulfill multiple <code>future</code>s with different values via <code>promise</code>s, which it can't do otherwise.</p> <p>An easy way to think of it is that you can either set a <code>future</code> by returning a value or by using a <code>promise</code>. <code>future</code> has no <code>set</code> method; that functionality is provided by <code>promise</code>. You choose what you need based on what the situation allows.</p>
13,851,940
Pure CSS Solution - Square Elements?
<p>If I have a <code>&lt;div&gt;</code> with a relative width (such as <em>width: 50%</em>), is there a simple way to make it have the same width as it does height without resorting to JavaScript?</p>
19,448,481
6
7
null
2012-12-13 02:23:05.407 UTC
7
2018-03-20 18:47:39.213 UTC
2014-10-21 12:01:26.97 UTC
null
371,530
null
433,380
null
1
25
css|layout|width|aspect-ratio
46,726
<p>It is actually possible to achieve it with this neat trick i found at <a href="https://pagecrafter.com/maintain-aspect-ratio-for-html-element-using-only-css-in-a-responsive-design/" rel="noreferrer">this blog</a> </p> <pre><code>#square { width: 100%; height: 0; padding-bottom: 100%; } </code></pre> <p>Hope that helps</p>
14,270,300
What is the difference between CLOCK_MONOTONIC & CLOCK_MONOTONIC_RAW?
<p>According to the Linux man page under Ubuntu</p> <pre><code>CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point. CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific) Similar to CLOCK_MONOTONIC, but provides access to a raw hard‐ ware-based time that is not subject to NTP adjustments. </code></pre> <p>According to the webster online dictionary Monotonic means:</p> <blockquote> <p>2: having the property either of never increasing or of never decreasing as the values of the independent variable or the subscripts of the terms increase.</p> </blockquote> <p>In other words, it won't jump backwards. I can see that this would be an important property if you were timing some code.</p> <p>However, the difference between the normal and raw version isn't clear. Can someone shed some light into how NTP can still affect CLOCK_MONOTONIC? </p>
14,270,415
2
0
null
2013-01-11 01:37:29.023 UTC
12
2017-04-24 23:07:30.363 UTC
null
null
null
null
134,702
null
1
50
linux|ubuntu|timing
37,203
<p><code>CLOCK_MONOTONIC</code> never experiences discontinuities due to NTP time adjustments, but it <em>does</em> change in frequency as NTP learns what error exists between the local oscillator and the upstream servers.</p> <p><code>CLOCK_MONOTONIC_RAW</code> is simply the local oscillator, not disciplined by NTP. This could be very useful if you want to implement some other time synchronization algorithm against a clock which is not fighting you due to NTP. While ntpd (the reference implementation of NTP protocol and the most widespread NTP daemon) is reputed to be "gentle" with time adjustments, it's more accurate to say it's gentle with the absolute time. It's willing to slew the clock by 500ppm which is pretty dramatic if you're in a position to measure your clock frequency against some other standard.</p> <p>The utility of <code>CLOCK_MONOTONIC_RAW</code> is going to be limited until facilities like <code>pthread_timedwait_monotonic</code> offer an option to use that timebase.</p>
14,178,889
What is the purpose of the reader monad?
<p>The reader monad is so complex and seems to be useless. In an imperative language like Java or C++, there is no equivalent concept for the reader monad, if I am not mistaken.</p> <p>Can you give me a simple example and clear this up a little bit?</p>
14,179,721
3
5
null
2013-01-06 03:06:11.48 UTC
67
2020-01-25 19:47:00.273 UTC
2018-12-23 22:49:42.487 UTC
null
775,954
null
1,832,951
null
1
145
haskell|monads|reader-monad
39,790
<p>Don't be scared! The reader monad is actually not so complicated, and has real easy-to-use utility.</p> <p>There are two ways of approaching a monad: we can ask</p> <ol> <li>What does the monad <strong><em>do</em></strong>? What operations is it equipped with? What is it good for?</li> <li>How is the monad implemented? From where does it arise?</li> </ol> <p>From the first approach, the reader monad is some abstract type</p> <pre><code>data Reader env a </code></pre> <p>such that</p> <pre><code>-- Reader is a monad instance Monad (Reader env) -- and we have a function to get its environment ask :: Reader env env -- finally, we can run a Reader runReader :: Reader env a -&gt; env -&gt; a </code></pre> <p>So how do we use this? Well, the reader monad is good for passing (implicit) configuration information through a computation.</p> <p>Any time you have a "constant" in a computation that you need at various points, but really you would like to be able to perform the same computation with different values, then you should use a reader monad.</p> <p>Reader monads are also used to do what the OO people call <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a>. For example, the <a href="https://en.wikipedia.org/wiki/Negamax" rel="noreferrer">negamax</a> algorithm is used frequently (in highly optimized forms) to compute the value of a position in a two player game. The algorithm itself though does not care what game you are playing, except that you need to be able to determine what the "next" positions are in the game, and you need to be able to tell if the current position is a victory position.</p> <pre><code> import Control.Monad.Reader data GameState = NotOver | FirstPlayerWin | SecondPlayerWin | Tie data Game position = Game { getNext :: position -&gt; [position], getState :: position -&gt; GameState } getNext' :: position -&gt; Reader (Game position) [position] getNext' position = do game &lt;- ask return $ getNext game position getState' :: position -&gt; Reader (Game position) GameState getState' position = do game &lt;- ask return $ getState game position negamax :: Double -&gt; position -&gt; Reader (Game position) Double negamax color position = do state &lt;- getState' position case state of FirstPlayerWin -&gt; return color SecondPlayerWin -&gt; return $ negate color Tie -&gt; return 0 NotOver -&gt; do possible &lt;- getNext' position values &lt;- mapM ((liftM negate) . negamax (negate color)) possible return $ maximum values </code></pre> <p>This will then work with any finite, deterministic, two player game.</p> <p>This pattern is useful even for things that are not really dependency injection. Suppose you work in finance, you might design some complicated logic for pricing an asset (a derivative say), which is all well and good and you can do without any stinking monads. But then, you modify your program to deal with multiple currencies. You need to be able to convert between currencies on the fly. Your first attempt is to define a top level function</p> <pre><code>type CurrencyDict = Map CurrencyName Dollars currencyDict :: CurrencyDict </code></pre> <p>to get spot prices. You can then call this dictionary in your code....but wait! That won't work! The currency dictionary is immutable and so has to be the same not only for the life of your program, but from the time it gets <strong>compiled</strong>! So what do you do? Well, one option would be to use the Reader monad:</p> <pre><code> computePrice :: Reader CurrencyDict Dollars computePrice = do currencyDict &lt;- ask --insert computation here </code></pre> <p>Perhaps the most classic use-case is in implementing interpreters. But, before we look at that, we need to introduce another function</p> <pre><code> local :: (env -&gt; env) -&gt; Reader env a -&gt; Reader env a </code></pre> <p>Okay, so Haskell and other functional languages are based on the <a href="https://en.wikipedia.org/wiki/Lambda_calculus" rel="noreferrer">lambda calculus</a>. Lambda calculus has a syntax that looks like</p> <pre><code> data Term = Apply Term Term | Lambda String Term | Var Term deriving (Show) </code></pre> <p>and we want to write an evaluator for this language. To do so, we will need to keep track of an environment, which is a list of bindings associated with terms (actually it will be closures because we want to do static scoping).</p> <pre><code> newtype Env = Env ([(String, Closure)]) type Closure = (Term, Env) </code></pre> <p>When we are done, we should get out a value (or an error):</p> <pre><code> data Value = Lam String Closure | Failure String </code></pre> <p>So, let's write the interpreter:</p> <pre><code>interp' :: Term -&gt; Reader Env Value --when we have a lambda term, we can just return it interp' (Lambda nv t) = do env &lt;- ask return $ Lam nv (t, env) --when we run into a value, we look it up in the environment interp' (Var v) = do (Env env) &lt;- ask case lookup (show v) env of -- if it is not in the environment we have a problem Nothing -&gt; return . Failure $ "unbound variable: " ++ (show v) -- if it is in the environment, then we should interpret it Just (term, env) -&gt; local (const env) $ interp' term --the complicated case is an application interp' (Apply t1 t2) = do v1 &lt;- interp' t1 case v1 of Failure s -&gt; return (Failure s) Lam nv clos -&gt; local (\(Env ls) -&gt; Env ((nv, clos) : ls)) $ interp' t2 --I guess not that complicated! </code></pre> <p>Finally, we can use it by passing a trivial environment:</p> <pre><code>interp :: Term -&gt; Value interp term = runReader (interp' term) (Env []) </code></pre> <p>And that is it. A fully functional interpreter for the lambda calculus.</p> <hr> <p>The other way to think about this is to ask: How is it implemented? The answer is that the reader monad is actually one of the simplest and most elegant of all monads.</p> <pre><code>newtype Reader env a = Reader {runReader :: env -&gt; a} </code></pre> <p>Reader is just a fancy name for functions! We have already defined <code>runReader</code> so what about the other parts of the API? Well, every <code>Monad</code> is also a <code>Functor</code>:</p> <pre><code>instance Functor (Reader env) where fmap f (Reader g) = Reader $ f . g </code></pre> <p>Now, to get a monad:</p> <pre><code>instance Monad (Reader env) where return x = Reader (\_ -&gt; x) (Reader f) &gt;&gt;= g = Reader $ \x -&gt; runReader (g (f x)) x </code></pre> <p>which is not so scary. <code>ask</code> is really simple:</p> <pre><code>ask = Reader $ \x -&gt; x </code></pre> <p>while <code>local</code> isn't so bad:</p> <pre><code>local f (Reader g) = Reader $ \x -&gt; runReader g (f x) </code></pre> <p>Okay, so the reader monad is just a function. Why have Reader at all? Good question. Actually, you don't need it!</p> <pre><code>instance Functor ((-&gt;) env) where fmap = (.) instance Monad ((-&gt;) env) where return = const f &gt;&gt;= g = \x -&gt; g (f x) x </code></pre> <p>These are even simpler. What's more, <code>ask</code> is just <code>id</code> and <code>local</code> is just function composition with the order of the functions switched!</p>
30,121,510
Java HttpsURLConnection and TLS 1.2
<p>I read in an article that <code>HttpsURLConnection</code> will transparently negotiate the SSL connection.</p> <p>The official document says:</p> <blockquote> <p>This class uses HostnameVerifier and SSLSocketFactory. There are default implementations defined for both classes. <sup>[<a href="http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/HttpsURLConnection.html" rel="noreferrer">1</a>]</sup></p> </blockquote> <p>Does that mean once you open a connection with</p> <pre><code>httpsCon = (HttpsURLConnection) url.openConnection(); </code></pre> <p>It is already SSL/TLS encrypted without any more hassle? </p> <p>How can I view and set the TLS version for the standard implementation? (Should be TLS 1.2 for Java 8 and TLS 1.0 for Java 7)</p> <h2>References</h2> <ol> <li>Oracle Corp. (2011). <a href="http://docs.oracle.com/javase/7/docs/api/javax/net/ssl/HttpsURLConnection.html" rel="noreferrer"><em>javax.net.ssl.HttpsURLConnection</em></a>. (JavaDoc)</li> </ol>
32,346,644
4
6
null
2015-05-08 10:24:45.84 UTC
11
2021-08-04 03:01:45.56 UTC
2016-12-17 05:18:21.247 UTC
null
452,210
null
2,551,007
null
1
31
java|ssl|httpsurlconnection
74,794
<p>You will have to create an <code>SSLContext</code> to set the Protocoll:<br><br> in <strong>Java 1.8</strong>:</p> <pre><code> SSLContext sc = SSLContext.getInstance("TLSv1.2"); // Init the SSLContext with a TrustManager[] and SecureRandom() sc.init(null, trustCerts, new java.security.SecureRandom()); </code></pre> <p>in <strong>Java 1.7</strong>:</p> <pre><code> SSLContext sc = SSLContext.getInstance("TLSv1"); // Init the SSLContext with a TrustManager[] and SecureRandom() sc.init(null, trustCerts, new java.security.SecureRandom()); </code></pre> <p>then you just have to set the <em>SSLContext</em> to the <strong>HttpsURLConnection</strong>:</p> <pre><code>httpsCon.setSSLSocketFactory(sc.getSocketFactory()); </code></pre> <p>That should do the Trick.</p>
43,348,463
What is the difference between Subject and BehaviorSubject?
<p>I'm not clear on the difference between a <code>Subject</code> and a <code>BehaviorSubject</code>. Is it just that a <code>BehaviorSubject</code> has the <code>getValue()</code> function?</p>
43,351,340
10
2
null
2017-04-11 14:12:01.043 UTC
88
2022-08-17 17:39:02.107 UTC
2022-02-07 11:45:28.737 UTC
null
7,494,218
null
4,854,046
null
1
398
angular|typescript|rxjs|behaviorsubject|subject
234,800
<p>A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.</p> <p>Subject example (with RxJS 5 API):</p> <pre><code>const subject = new Rx.Subject(); subject.next(1); subject.subscribe(x =&gt; console.log(x)); </code></pre> <p>Console output will be empty</p> <p>BehaviorSubject example:</p> <pre><code>const subject = new Rx.BehaviorSubject(0); subject.next(1); subject.subscribe(x =&gt; console.log(x)); </code></pre> <p>Console output: 1</p> <p>In addition:</p> <ul> <li><code>BehaviorSubject</code> should be created with an initial value: new <code>Rx.BehaviorSubject(1)</code></li> <li>Consider <code>ReplaySubject</code> if you want the subject to get previously publised values.</li> </ul>
9,207,379
simple file upload script
<p>I have written a simple file upload script but it gives me the error of undefined index file1.</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;form method="post"&gt; &lt;label for="file"&gt;Filename:&lt;/label&gt; &lt;input type="file" name="file1" id="file1" /&gt; &lt;br /&gt; &lt;input type="submit" name="submit" value="Submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php if(isset($_POST['submit'])) { if ($_FILES["file1"]["error"] &gt; 0) { echo "Error: " . $_FILES["file1"]["error"] . "&lt;br /&gt;"; } else { echo "Upload: " . $_FILES["file1"]["name"] . "&lt;br /&gt;"; echo "Type: " . $_FILES["file1"]["type"] . "&lt;br /&gt;"; echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb&lt;br /&gt;"; echo "Stored in: " . $_FILES["file1"]["tmp_name"]; } } ?&gt; </code></pre> <p>What is the problem in code?</p>
9,207,394
6
1
null
2012-02-09 08:15:37.943 UTC
1
2020-07-01 20:10:13.477 UTC
2012-02-09 08:18:51.793 UTC
null
396,476
null
563,466
null
1
8
php|file-upload
88,523
<p>You lack <code>enctype="multipart/form-data"</code> in your <code>&lt;form&gt;</code> element.</p>
9,193,445
weak property for delegate cannot be formed
<p>I have a property that looks like this:</p> <pre><code>@property (weak, nonatomic) id&lt;NavigationControllerDelegate&gt; delegate; </code></pre> <p>But when I run my app I get the following error:</p> <pre><code>objc[4251]: cannot form weak reference to instance (0x101e0d4b0) of class TabBarController </code></pre> <p>The only reason I can get from google for this error is that you get it when you try to form a weak reference to an object that overrides retain/release/dealloc, which I am not. My TabBarController is inheriting from NSViewController.</p> <p>Anyone knows what might cause this? It works if I use "assign", but obviously I'd prefer to use "weak".</p>
9,193,860
1
1
null
2012-02-08 12:38:24.763 UTC
10
2014-07-10 22:32:06.133 UTC
null
null
null
null
1,097,245
null
1
19
objective-c|ios|macos|cocoa|automatic-ref-counting
5,384
<p>According to Apple's <a href="https://developer.apple.com/library/mac/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226-CH1-SW17" rel="noreferrer">Transitioning to ARC Release Notes</a>,</p> <blockquote> <p>You cannot currently create weak references to instances of the following classes:</p> <p><code>NSATSTypesetter</code>, <code>NSColorSpace</code>, <code>NSFont</code>, <code>NSMenuView</code>, <code>NSParagraphStyle</code>, <code>NSSimpleHorizontalTypesetter</code>, and <code>NSTextView</code>.</p> <p>Note: In addition, in OS X v10.7, you cannot create weak references to instances of <code>NSFontManager</code>, <code>NSFontPanel</code>, <code>NSImage</code>, <code>NSTableCellView</code>, <strong><code>NSViewController</code></strong>, <code>NSWindow</code>, and <code>NSWindowController</code>. In addition, in OS X v10.7 no classes in the AV Foundation framework support weak references.</p> </blockquote> <p>(Note: one needs to be very careful with nonzeroing weak references...)</p>
44,625,680
Disable zoom on web-view react-native?
<p>How to disable zoom on <code>react-native</code> <code>web-view</code>,is there a property like <code>hasZoom={false}</code>(just an example) that can be included in the below <code>web-view</code> tag that can disable zooming. It has to be working on both android and ios.</p> <pre><code>&lt;WebView ref={WEBVIEW_REF} source={{uri:Environment.LOGIN_URL}} ignoreSslError={true} onNavigationStateChange={this._onNavigationStateChange.bind(this)} onLoad={this.onLoad.bind(this)} onError={this.onError.bind(this)} &gt;&lt;/WebView&gt; </code></pre>
48,252,727
7
3
null
2017-06-19 08:32:28.987 UTC
7
2020-11-04 17:54:21.443 UTC
2017-06-19 08:40:11.513 UTC
null
4,061,501
null
7,358,035
null
1
38
android|ios|webview|react-native|hybrid-mobile-app
37,554
<p>Thought this might help others, I solved this by adding the following in the html <code>&lt;head&gt;</code> section:</p> <p><code>&lt;meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"&gt;</code></p>
45,858,084
What is a fast pythonic way to deepcopy just data from a python dict or list ?
<p>When we need to copy full data from a dictionary containing primitive data types ( for simplicity, lets ignore presence of datatypes like datetime etc), the most obvious choice that we have is to use <code>deepcopy</code>, but deepcopy is slower than some other hackish methods of achieving the same i.e. using serialization-unserialization for example like json-dump-json-load or msgpack-pack-msgpack-unpack. The difference in efficiency can be seen here :</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; setup = ''' ... import msgpack ... import json ... from copy import deepcopy ... data = {'name':'John Doe','ranks':{'sports':13,'edu':34,'arts':45},'grade':5} ... ''' &gt;&gt;&gt; print(timeit.timeit('deepcopy(data)', setup=setup)) 12.0860249996 &gt;&gt;&gt; print(timeit.timeit('json.loads(json.dumps(data))', setup=setup)) 9.07182312012 &gt;&gt;&gt; print(timeit.timeit('msgpack.unpackb(msgpack.packb(data))', setup=setup)) 1.42743492126 </code></pre> <p>json and msgpack (or cPickle) methods are faster than a normal deepcopy, which is obvious as deepcopy would be doing much more in copying all the attributes of the object too. </p> <p>Question: Is there a more pythonic/inbuilt way to achieve just a data copy of a dictionary or list, without having all the overhead that deepcopy has ?</p>
45,858,907
5
4
null
2017-08-24 09:37:35.557 UTC
9
2022-08-11 16:45:12.877 UTC
null
null
null
null
533,399
null
1
25
python
11,147
<p>It really depends on your needs. <code>deepcopy</code> was built with the intention to do the (most) correct thing. It keeps shared references, it doesn't recurse into infinite recursive structures and so on... It can do that by keeping a <code>memo</code> dictionary in which all encountered "things" are inserted by reference. That's what makes it quite slow for pure-data copies. However I would <em>almost</em> always say that <code>deepcopy</code> is <strong>the most pythonic way to copy data</strong> even if other approaches could be faster.</p> <p>If you have pure-data and a limited amount of types inside it you could build your own <code>deepcopy</code> (build <em>roughly</em> after the implementation of <a href="https://github.com/python/cpython/blob/master/Lib/copy.py" rel="noreferrer"><code>deepcopy</code> in CPython</a>):</p> <pre><code>_dispatcher = {} def _copy_list(l, dispatch): ret = l.copy() for idx, item in enumerate(ret): cp = dispatch.get(type(item)) if cp is not None: ret[idx] = cp(item, dispatch) return ret def _copy_dict(d, dispatch): ret = d.copy() for key, value in ret.items(): cp = dispatch.get(type(value)) if cp is not None: ret[key] = cp(value, dispatch) return ret _dispatcher[list] = _copy_list _dispatcher[dict] = _copy_dict def deepcopy(sth): cp = _dispatcher.get(type(sth)) if cp is None: return sth else: return cp(sth, _dispatcher) </code></pre> <p>This only works correct for all immutable non-container types and <code>list</code> and <code>dict</code> instances. You could add more dispatchers if you need them.</p> <pre><code># Timings done on Python 3.5.3 - Windows - on a really slow laptop :-/ import copy import msgpack import json import string data = {'name':'John Doe','ranks':{'sports':13,'edu':34,'arts':45},'grade':5} %timeit deepcopy(data) # 11.9 µs ± 280 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit copy.deepcopy(data) # 64.3 µs ± 1.15 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit json.loads(json.dumps(data)) # 65.9 µs ± 2.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) %timeit msgpack.unpackb(msgpack.packb(data)) # 56.5 µs ± 2.53 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) </code></pre> <p>Let's also see how it performs when copying a big dictionary containing strings and integers:</p> <pre><code>data = {''.join([a,b,c]): 1 for a in string.ascii_letters for b in string.ascii_letters for c in string.ascii_letters} %timeit deepcopy(data) # 194 ms ± 5.37 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit copy.deepcopy(data) # 1.02 s ± 46.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit json.loads(json.dumps(data)) # 398 ms ± 20.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit msgpack.unpackb(msgpack.packb(data)) # 238 ms ± 8.81 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) </code></pre>
19,436,069
Adding Play JSON Library to sbt
<p>How can I add the Play JSON library (<code>play.api.libs.json</code>) to my sbt project?</p> <p>When I added the following to my <code>plugins.sbt</code> file:</p> <pre><code>addSbtPlugin("play" % "sbt-plugin" % "2.1.0") </code></pre> <p>I faced this error:</p> <pre><code>[warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: play#sbt-plugin;2.1.0: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: </code></pre> <p>I did not find a resolver for this library, otherwise I would've added it and ran <code>sbt update</code>. Note that my <code>resolvers</code> includes <a href="http://repo.typesafe.com/typesafe/releases/">http://repo.typesafe.com/typesafe/releases/</a>.</p>
19,438,083
5
3
null
2013-10-17 19:58:21.737 UTC
11
2017-05-25 13:17:54.577 UTC
2014-03-29 15:27:59.97 UTC
null
1,305,344
null
409,976
null
1
47
playframework|sbt|playframework-2.1
24,330
<p><strong>Play 2.3 JSON with SBT >= 0.13.5</strong></p> <p>put into build.sbt:</p> <pre><code>libraryDependencies += "com.typesafe.play" %% "play-json" % "2.3.4" </code></pre> <p><strong>Play 2.1</strong></p> <p>build.sbt:</p> <pre><code>resolvers += "Typesafe Repo" at "http://repo.typesafe.com/typesafe/releases/" scalaVersion := "2.10.2" libraryDependencies += "play" % "play_2.10" % "2.1.0" </code></pre> <p>Play JSON is in Play 2.1 not an independent artifact.</p>
693,070
How can you find unused functions in Python code?
<p>So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?</p> <p>I've seen these two references: <a href="https://stackoverflow.com/questions/245963">Find unused code</a> and <a href="https://stackoverflow.com/questions/11532">Tool to find unused functions in php project</a>, but they seem specific to C# and PHP, respectively.</p> <p>Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?</p>
9,824,998
5
0
null
2009-03-28 16:42:42.107 UTC
19
2021-10-04 00:39:12.39 UTC
2017-05-23 11:54:22.647 UTC
null
-1
Brian M. Hunt
19,212
null
1
80
python|refactoring|dead-code
29,137
<p>In Python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are <a href="https://coverage.readthedocs.io/en/6.0/" rel="noreferrer"><code>coverage</code></a> and <a href="https://ctb.github.io/figleaf/doc/" rel="noreferrer"><code>figleaf</code></a>. They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable results.</p> <p>Alternatively, you can use static code analyzers that just look at your code, but don't actually run it. They run much faster, but due to Python's dynamic nature the results may contain false positives. Two tools in this category are <a href="https://pypi.org/project/pyflakes/" rel="noreferrer"><code>pyflakes</code></a> and <a href="https://pypi.org/project/vulture/" rel="noreferrer"><code>vulture</code></a>. Pyflakes finds unused imports and unused local variables. Vulture finds all kinds of unused and unreachable code. (Full disclosure: I'm the maintainer of Vulture.)</p> <p>The tools are available in the Python Package Index <a href="https://pypi.org/" rel="noreferrer">https://pypi.org/</a>.</p>
931,827
std::string comparison (check whether string begins with another string)
<p>I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().</p>
931,873
5
0
null
2009-05-31 10:44:14.503 UTC
14
2018-07-04 15:11:24.833 UTC
2016-07-12 05:35:54.793 UTC
null
212,378
null
48,461
null
1
90
c++|string|stl|compare
67,935
<p>I would use compare method:</p> <pre><code>std::string s("xyzblahblah"); std::string t("xyz") if (s.compare(0, t.length(), t) == 0) { // ok } </code></pre>
564,980
Javascript - form select element open url in new window and submit form
<p><strong>UPDATED</strong> - please read further details below original question</p> <p>I have a select form element with various urls, that I want to open in a new window when selected - to do this I have the following code in the element's onchange event:</p> <pre><code>window.open(this.options[this.selectedIndex].value,'_blank'); </code></pre> <p>This works fine. But I also want to submit the form when changing this select element value - I've tried various things, but I can't seem to get it to work.</p> <p>I have jquery, so if it's easier to achieve via that then that's fine.</p> <p><em>Update - I've just realised there is another issue with the above, because some of the urls are actually used to generate and output pdfs, and these do not work - they open and then immediately close (at least in IE7).</em></p> <p><strong>UPDATE 07/05/09</strong> - I've now opened a bounty for this question as I really need to come up with a working solution. I did originally get around the issue by displaying links instead of a form select element, but this is no longer feasible.</p> <p>The reason I need the above is that I have a large number of files that might need to be viewed / printed, too many to reasonably display as a list of links. I need to submit the form to record the fact a particular file has been viewed / printed, then display a log of the file history on the form - I'm comfortable with achieving this side of things, so don't require assistance there, but I thought it would help to place the context. </p> <p>So, to clarify my requirements - I need a form select element and 'View' button that when clicked will not only launch a file download in a new window (note the above issue I faced when these files were PDFs), but also submit the form that contains the select element.</p>
834,241
6
2
null
2009-02-19 12:00:47.193 UTC
1
2010-12-01 11:44:16.57 UTC
2009-05-07 11:47:22.25 UTC
BrynJ
29,538
BrynJ
29,538
null
1
2
javascript|jquery|forms|select|form-submit
44,648
<p>Here ya go</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $("#selectElement").change(function() { if ($(this).val()) { window.open($(this).val(), '_blank'); $("#formElement").submit(); } }); // just to be sure that it is submitting, remove this code $("#formElement").submit(function() { alert('submitting ... '); }); }); &lt;/script&gt; &lt;form id="formElement" method="get" action="#"&gt; &lt;select id="selectElement"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="http://www.deviantnation.com/"&gt;View Site 1&lt;/option&gt; &lt;option value="http://stackoverflow.com/"&gt;View Site 2&lt;/option&gt; &lt;option value="http://serverfault.com/"&gt;View Site 3&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre>
1,089,285
Maven Run Project
<p>Is there a Maven "phase" or "goal" to simply execute the main method of a Java class? I have a project that I'd like to test manually by simply doing something like "mvn run".</p>
1,089,338
6
0
null
2009-07-06 21:24:47.963 UTC
72
2021-09-08 07:00:27.87 UTC
2014-01-13 09:38:50.453 UTC
null
112,671
null
84,399
null
1
265
java|maven
223,098
<p>See the <a href="http://www.mojohaus.org/exec-maven-plugin/" rel="noreferrer">exec maven plugin</a>. You can run Java classes using:</p> <pre><code>mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ... </code></pre> <p>The invocation can be as simple as <code>mvn exec:java</code> if the plugin configuration is in your pom.xml. The plugin site on Mojohaus has a <a href="http://www.mojohaus.org/exec-maven-plugin/examples/example-exec-using-plugin-dependencies.html" rel="noreferrer">more detailed example</a>.</p> <pre><code>&lt;project&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.2.1&lt;/version&gt; &lt;configuration&gt; &lt;mainClass&gt;com.example.Main&lt;/mainClass&gt; &lt;arguments&gt; &lt;argument&gt;argument1&lt;/argument&gt; &lt;/arguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>
576,176
.net collection for fast insert/delete
<p>I need to maintain a roster of connected clients that are very shortlived and frequently go up and down. Due to the potential number of clients I need a collection that supports fast insert/delete. Suggestions?</p>
576,296
6
0
null
2009-02-23 00:33:53.49 UTC
16
2009-03-03 20:33:04.37 UTC
null
null
null
spender
14,357
null
1
15
c#|.net|collections
11,083
<h2>C5 Generic Collection Library</h2> <p>The best implementations I have found in C# and C++ are these -- for C#/CLI:</p> <ul> <li><a href="http://www.itu.dk/research/c5/Release1.1/ITU-TR-2006-76.pdf" rel="noreferrer">http://www.itu.dk/research/c5/Release1.1/ITU-TR-2006-76.pdf</a></li> <li><a href="http://www.itu.dk/research/c5/" rel="noreferrer">http://www.itu.dk/research/c5/</a></li> </ul> <p>It's well researched, has extensible unit tests, and since February they also have implemented the common interfaces in .Net which makes it a lot easier to work with the collections. They were featured on <a href="http://channel9.msdn.com/shows/Going+Deep/Peter-Sestoft-C5-Generic-Collection-Library-for-C-and-CLI/" rel="noreferrer">Channel9</a> and they've done extensive performance testing on the collections.</p> <p>If you are using data-structures anyway these researchers have a <a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="noreferrer">red-black-tree</a> implementation in their library, similar to what you find if you fire up Lütz reflector and have a look in System.Data's internal structures :p. Insert-complexity: O(log(n)).</p> <h2>Lock-free C++ collections</h2> <p>Then, if you can <a href="http://blog.rednael.com/2008/08/29/MarshallingUsingNativeDLLsInNET.aspx" rel="noreferrer">allow for some C++ interop</a> and you absolutely need the speed and want as little overhead as possible, then these lock-free ADTs from Dmitriy V'jukov are probably the best you can get in this world, outperforming Intel's concurrent library of ADTs. </p> <ul> <li><a href="http://groups.google.com/group/lock-free" rel="noreferrer">http://groups.google.com/group/lock-free</a></li> </ul> <p>I've read some of the code and it's really the makings of someone well versed in how these things are put together. VC++ can do native C++ interop without annoying boundaries. <a href="http://groups.google.com/group/lock-free" rel="noreferrer">http://www.swig.org/</a> can otherwise help you wrap C++ interfaces for consumption in .Net, or you can do it yourself through P/Invoke.</p> <h2>Microsoft's Take</h2> <p>They have written tutorials, <a href="http://msdn.microsoft.com/en-us/library/ms379573.aspx" rel="noreferrer">this one implementing a rather unpolished skip-list in C#</a>, and discussing other types of data-structures. (There's a better <a href="http://www.codeproject.com/KB/recipes/skiplist1.aspx" rel="noreferrer">SkipList at CodeProject</a>, which is very polished and implement the interfaces in a well-behaved manner.) They also have a few data-structures bundled with .Net, namely the <a href="http://msdn.microsoft.com/en-us/library/4yh14awz.aspx" rel="noreferrer">HashTable/Dictionary&lt;,></a> and <a href="http://msdn.microsoft.com/en-us/library/bb397727.aspx" rel="noreferrer">HashSet</a>. Of course there's the "ResizeArray"/List type as well together with a stack and queue, but they are all "linear" on search.</p> <h2>Google's perf-tools</h2> <p>If you wish to speed up the time it takes for memory-allocation you can use google's perf-tools. They are available at google code and they contain a <a href="http://goog-perftools.sourceforge.net/doc/tcmalloc.html" rel="noreferrer">very interesting multi-threaded malloc-implementation (TCMalloc)</a> which shows much more consistent timing than the normal malloc does. You could use this together with the lock-free structures above to really go crazy with performance.</p> <h2>Improving response times with memoization</h2> <p>You can also use memoization on functions to improve performance through caching, something interesting if you're using e.g. <a href="https://rads.stackoverflow.com/amzn/click/com/1590598504" rel="noreferrer" rel="nofollow noreferrer">F#</a>. F# also allows C++ interop, so you're OK there.</p> <h2>O(k)</h2> <p>There's also the possibility of doing something on your own using the research which has been done on <a href="http://en.wikipedia.org/wiki/Bloom_filter" rel="noreferrer">bloom-filters</a>, which allow O(k) lookup complexity where k is a constant that depends on the number of hash-functions you have implemented. This is how google's BigTable has been implemented. These filter will get you the element if it's in the set or possibly with a very low likeliness an element which is not the one you're looking for (see the graph at wikipedia -- it's approaching P(wrong_key) -> 0.01 as size is around 10000 elements, but you can go around this by implementing further hash-functions/reducing the set. </p> <p>I haven't searched for .Net implementations of this, but since the hashing calculations are independent you can use <a href="http://blogs.msdn.com/pfxteam/archive/2008/06/02/8567093.aspx" rel="noreferrer">MS's performance team's implementation of Tasks to speed that up.</a></p> <h2>"My" take -- randomize to reach average O(log n)</h2> <p>As it happens I just did a coursework involving data-structures. In this case we used C++, but it's very easy to translate to C#. We built three different data-structures; a bloom-filter, a skip-list and <a href="http://gcu.googlecode.com/files/09BinarySearchTrees.pdf" rel="noreferrer">random binary search tree</a>.</p> <p>See the code and analysis after the last paragraph.</p> <h2>Hardware-based "collections"</h2> <p>Finally, to make my answer "complete", if you truly need speed you can use something like <a href="http://en.wikipedia.org/wiki/Forwarding_information_base" rel="noreferrer">Routing-tables</a> or <a href="http://en.wikipedia.org/wiki/Content_addressable_memory" rel="noreferrer">Content-addressable memory</a> . This allows you to very quickly O(1) in principle get a "hash"-to-value lookup of your data. </p> <h2>Random Binary Search Tree/Bloom Filter C++ code</h2> <p>I would really appreciate feedback if you find mistakes in the code, or just pointers on how I can do it better (or with better usage of templates). Note that the bloom filter isn't like it would be in real life; normally you don't have to be able to delete from it and then it much much more space efficient than the hack I did to allow the <em>delete</em> to be tested.</p> <p><strong>DataStructure.h</strong></p> <pre><code>#ifndef DATASTRUCTURE_H_ #define DATASTRUCTURE_H_ class DataStructure { public: DataStructure() {countAdd=0; countDelete=0;countFind=0;} virtual ~DataStructure() {} void resetCountAdd() {countAdd=0;} void resetCountFind() {countFind=0;} void resetCountDelete() {countDelete=0;} unsigned int getCountAdd(){return countAdd;} unsigned int getCountDelete(){return countDelete;} unsigned int getCountFind(){return countFind;} protected: unsigned int countAdd; unsigned int countDelete; unsigned int countFind; }; #endif /*DATASTRUCTURE_H_*/ </code></pre> <p><strong>Key.h</strong></p> <pre><code>#ifndef KEY_H_ #define KEY_H_ #include &lt;string&gt; using namespace std; const int keyLength = 128; class Key : public string { public: Key():string(keyLength, ' ') {} Key(const char in[]): string(in){} Key(const string&amp; in): string(in){} bool operator&lt;(const string&amp; other); bool operator&gt;(const string&amp; other); bool operator==(const string&amp; other); virtual ~Key() {} }; #endif /*KEY_H_*/ </code></pre> <p><strong>Key.cpp</strong></p> <pre><code>#include "Key.h" bool Key::operator&lt;(const string&amp; other) { return compare(other) &lt; 0; }; bool Key::operator&gt;(const string&amp; other) { return compare(other) &gt; 0; }; bool Key::operator==(const string&amp; other) { return compare(other) == 0; } </code></pre> <p><strong>BloomFilter.h</strong></p> <pre><code>#ifndef BLOOMFILTER_H_ #define BLOOMFILTER_H_ #include &lt;iostream&gt; #include &lt;assert.h&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include "Key.h" #include "DataStructure.h" #define LONG_BIT 32 #define bitmask(val) (unsigned long)(1 &lt;&lt; (LONG_BIT - (val % LONG_BIT) - 1)) // TODO: Implement RW-locking on the reads/writes to the bitmap. class BloomFilter : public DataStructure { public: BloomFilter(){} BloomFilter(unsigned long length){init(length);} virtual ~BloomFilter(){} void init(unsigned long length); void dump(); void add(const Key&amp; key); void del(const Key&amp; key); /** * Returns true if the key IS BELIEVED to exist, false if it absolutely doesn't. */ bool testExist(const Key&amp; key, bool v = false); private: unsigned long hash1(const Key&amp; key); unsigned long hash2(const Key&amp; key); bool exist(const Key&amp; key); void getHashAndIndicies(unsigned long&amp; h1, unsigned long&amp; h2, int&amp; i1, int&amp; i2, const Key&amp; key); void getCountIndicies(const int i1, const unsigned long h1, const int i2, const unsigned long h2, int&amp; i1_c, int&amp; i2_c); vector&lt;unsigned long&gt; m_tickBook; vector&lt;unsigned int&gt; m_useCounts; unsigned long m_length; // number of bits in the bloom filter unsigned long m_pockets; //the number of pockets static const unsigned long m_pocketSize; //bits in each pocket }; #endif /*BLOOMFILTER_H_*/ </code></pre> <p><strong>BloomFilter.cpp</strong></p> <pre><code>#include "BloomFilter.h" const unsigned long BloomFilter::m_pocketSize = LONG_BIT; void BloomFilter::init(unsigned long length) { //m_length = length; m_length = (unsigned long)((2.0*length)/log(2))+1; m_pockets = (unsigned long)(ceil(double(m_length)/m_pocketSize)); m_tickBook.resize(m_pockets); // my own (allocate nr bits possible to store in the other vector) m_useCounts.resize(m_pockets * m_pocketSize); unsigned long i; for(i=0; i&lt; m_pockets; i++) m_tickBook[i] = 0; for (i = 0; i &lt; m_useCounts.size(); i++) m_useCounts[i] = 0; // my own } unsigned long BloomFilter::hash1(const Key&amp; key) { unsigned long hash = 5381; unsigned int i=0; for (i=0; i&lt; key.length(); i++){ hash = ((hash &lt;&lt; 5) + hash) + key.c_str()[i]; /* hash * 33 + c */ } double d_hash = (double) hash; d_hash *= (0.5*(sqrt(5)-1)); d_hash -= floor(d_hash); d_hash *= (double)m_length; return (unsigned long)floor(d_hash); } unsigned long BloomFilter::hash2(const Key&amp; key) { unsigned long hash = 0; unsigned int i=0; for (i=0; i&lt; key.length(); i++){ hash = key.c_str()[i] + (hash &lt;&lt; 6) + (hash &lt;&lt; 16) - hash; } double d_hash = (double) hash; d_hash *= (0.5*(sqrt(5)-1)); d_hash -= floor(d_hash); d_hash *= (double)m_length; return (unsigned long)floor(d_hash); } bool BloomFilter::testExist(const Key&amp; key, bool v){ if(exist(key)) { if(v) cout&lt;&lt;"Key "&lt;&lt; key&lt;&lt;" is in the set"&lt;&lt;endl; return true; }else { if(v) cout&lt;&lt;"Key "&lt;&lt; key&lt;&lt;" is not in the set"&lt;&lt;endl; return false; } } void BloomFilter::dump() { cout&lt;&lt;m_pockets&lt;&lt;" Pockets: "; // I changed u to %p because I wanted it printed in hex. unsigned long i; for(i=0; i&lt; m_pockets; i++) printf("%p ", (void*)m_tickBook[i]); cout&lt;&lt;endl; } void BloomFilter::add(const Key&amp; key) { unsigned long h1, h2; int i1, i2; int i1_c, i2_c; // tested! getHashAndIndicies(h1, h2, i1, i2, key); getCountIndicies(i1, h1, i2, h2, i1_c, i2_c); m_tickBook[i1] = m_tickBook[i1] | bitmask(h1); m_tickBook[i2] = m_tickBook[i2] | bitmask(h2); m_useCounts[i1_c] = m_useCounts[i1_c] + 1; m_useCounts[i2_c] = m_useCounts[i2_c] + 1; countAdd++; } void BloomFilter::del(const Key&amp; key) { unsigned long h1, h2; int i1, i2; int i1_c, i2_c; if (!exist(key)) throw "You can't delete keys which are not in the bloom filter!"; // First we need the indicies into m_tickBook and the // hashes. getHashAndIndicies(h1, h2, i1, i2, key); // The index of the counter is the index into the bitvector // times the number of bits per vector item plus the offset into // that same vector item. getCountIndicies(i1, h1, i2, h2, i1_c, i2_c); // We need to update the value in the bitvector in order to // delete the key. m_useCounts[i1_c] = (m_useCounts[i1_c] == 1 ? 0 : m_useCounts[i1_c] - 1); m_useCounts[i2_c] = (m_useCounts[i2_c] == 1 ? 0 : m_useCounts[i2_c] - 1); // Now, if we depleted the count for a specific bit, then set it to // zero, by anding the complete unsigned long with the notted bitmask // of the hash value if (m_useCounts[i1_c] == 0) m_tickBook[i1] = m_tickBook[i1] &amp; ~(bitmask(h1)); if (m_useCounts[i2_c] == 0) m_tickBook[i2] = m_tickBook[i2] &amp; ~(bitmask(h2)); countDelete++; } bool BloomFilter::exist(const Key&amp; key) { unsigned long h1, h2; int i1, i2; countFind++; getHashAndIndicies(h1, h2, i1, i2, key); return ((m_tickBook[i1] &amp; bitmask(h1)) &gt; 0) &amp;&amp; ((m_tickBook[i2] &amp; bitmask(h2)) &gt; 0); } /* * Gets the values of the indicies for two hashes and places them in * the passed parameters. The index is into m_tickBook. */ void BloomFilter::getHashAndIndicies(unsigned long&amp; h1, unsigned long&amp; h2, int&amp; i1, int&amp; i2, const Key&amp; key) { h1 = hash1(key); h2 = hash2(key); i1 = (int) h1/m_pocketSize; i2 = (int) h2/m_pocketSize; } /* * Gets the values of the indicies into the count vector, which keeps * track of how many times a specific bit-position has been used. */ void BloomFilter::getCountIndicies(const int i1, const unsigned long h1, const int i2, const unsigned long h2, int&amp; i1_c, int&amp; i2_c) { i1_c = i1*m_pocketSize + h1%m_pocketSize; i2_c = i2*m_pocketSize + h2%m_pocketSize; } </code></pre> <p>** RBST.h **</p> <pre><code>#ifndef RBST_H_ #define RBST_H_ #include &lt;iostream&gt; #include &lt;assert.h&gt; #include &lt;vector&gt; #include &lt;math.h&gt; #include "Key.h" #include "DataStructure.h" #define BUG(str) printf("%s:%d FAILED SIZE INVARIANT: %s\n", __FILE__, __LINE__, str); using namespace std; class RBSTNode; class RBSTNode: public Key { public: RBSTNode(const Key&amp; key):Key(key) { m_left =NULL; m_right = NULL; m_size = 1U; // the size of one node is 1. } virtual ~RBSTNode(){} string setKey(const Key&amp; key){return Key(key);} RBSTNode* left(){return m_left; } RBSTNode* right(){return m_right;} RBSTNode* setLeft(RBSTNode* left) { m_left = left; return this; } RBSTNode* setRight(RBSTNode* right) { m_right =right; return this; } #ifdef DEBUG ostream&amp; print(ostream&amp; out) { out &lt;&lt; "Key(" &lt;&lt; *this &lt;&lt; ", m_size: " &lt;&lt; m_size &lt;&lt; ")"; return out; } #endif unsigned int size() { return m_size; } void setSize(unsigned int val) { #ifdef DEBUG this-&gt;print(cout); cout &lt;&lt; "::setSize(" &lt;&lt; val &lt;&lt; ") called." &lt;&lt; endl; #endif if (val == 0) throw "Cannot set the size below 1, then just delete this node."; m_size = val; } void incSize() { #ifdef DEBUG this-&gt;print(cout); cout &lt;&lt; "::incSize() called" &lt;&lt; endl; #endif m_size++; } void decrSize() { #ifdef DEBUG this-&gt;print(cout); cout &lt;&lt; "::decrSize() called" &lt;&lt; endl; #endif if (m_size == 1) throw "Cannot decrement size below 1, then just delete this node."; m_size--; } #ifdef DEBUG unsigned int size(RBSTNode* x); #endif private: RBSTNode(){} RBSTNode* m_left; RBSTNode* m_right; unsigned int m_size; }; class RBST : public DataStructure { public: RBST() { m_size = 0; m_head = NULL; srand(time(0)); }; virtual ~RBST() {}; /** * Tries to add key into the tree and will return * true for a new item added * false if the key already is in the tree. * * Will also have the side-effect of printing to the console if v=true. */ bool add(const Key&amp; key, bool v=false); /** * Same semantics as other add function, but takes a string, * but diff name, because that'll cause an ambiguity because of inheritance. */ bool addString(const string&amp; key); /** * Deletes a key from the tree if that key is in the tree. * Will return * true for success and * false for failure. * * Will also have the side-effect of printing to the console if v=true. */ bool del(const Key&amp; key, bool v=false); /** * Tries to find the key in the tree and will return * true if the key is in the tree and * false if the key is not. * * Will also have the side-effect of printing to the console if v=true. */ bool find(const Key&amp; key, bool v = false); unsigned int count() { return m_size; } #ifdef DEBUG int dump(char sep = ' '); int dump(RBSTNode* target, char sep); unsigned int size(RBSTNode* x); #endif private: RBSTNode* randomAdd(RBSTNode* target, const Key&amp; key); RBSTNode* addRoot(RBSTNode* target, const Key&amp; key); RBSTNode* rightRotate(RBSTNode* target); RBSTNode* leftRotate(RBSTNode* target); RBSTNode* del(RBSTNode* target, const Key&amp; key); RBSTNode* join(RBSTNode* left, RBSTNode* right); RBSTNode* find(RBSTNode* target, const Key&amp; key); RBSTNode* m_head; unsigned int m_size; }; #endif /*RBST_H_*/ </code></pre> <p>** RBST.cpp **</p> <pre><code>#include "RBST.h" bool RBST::add(const Key&amp; key, bool v){ unsigned int oldSize = m_size; m_head = randomAdd(m_head, key); if (m_size &gt; oldSize){ if(v) cout&lt;&lt;"Node "&lt;&lt;key&lt;&lt; " is added into the tree."&lt;&lt;endl; return true; }else { if(v) cout&lt;&lt;"Node "&lt;&lt;key&lt;&lt; " is already in the tree."&lt;&lt;endl; return false; } if(v) cout&lt;&lt;endl; }; bool RBST::addString(const string&amp; key) { return add(Key(key), false); } bool RBST::del(const Key&amp; key, bool v){ unsigned oldSize= m_size; m_head = del(m_head, key); if (m_size &lt; oldSize) { if(v) cout&lt;&lt;"Node "&lt;&lt;key&lt;&lt; " is deleted from the tree."&lt;&lt;endl; return true; } else { if(v) cout&lt;&lt; "Node "&lt;&lt;key&lt;&lt; " is not in the tree."&lt;&lt;endl; return false; } }; bool RBST::find(const Key&amp; key, bool v){ RBSTNode* ret = find(m_head, key); if (ret == NULL){ if(v) cout&lt;&lt; "Node "&lt;&lt;key&lt;&lt; " is not in the tree."&lt;&lt;endl; return false; }else { if(v) cout&lt;&lt;"Node "&lt;&lt;key&lt;&lt; " is in the tree."&lt;&lt;endl; return true; } }; #ifdef DEBUG int RBST::dump(char sep){ int ret = dump(m_head, sep); cout&lt;&lt;"SIZE: " &lt;&lt;ret&lt;&lt;endl; return ret; }; int RBST::dump(RBSTNode* target, char sep){ if (target == NULL) return 0; int ret = dump(target-&gt;left(), sep); cout&lt;&lt; *target&lt;&lt;sep; ret ++; ret += dump(target-&gt;right(), sep); return ret; }; #endif /** * Rotates the tree around target, so that target's left * is the new root of the tree/subtree and updates the subtree sizes. * *(target) b (l) a * / \ right / \ * a ? ----&gt; ? b * / \ / \ * ? x x ? * */ RBSTNode* RBST::rightRotate(RBSTNode* target) // private { if (target == NULL) throw "Invariant failure, target is null"; // Note: may be removed once tested. if (target-&gt;left() == NULL) throw "You cannot rotate right around a target whose left node is NULL!"; #ifdef DEBUG cout &lt;&lt;"Right-rotating b-node "; target-&gt;print(cout); cout &lt;&lt; " for a-node "; target-&gt;left()-&gt;print(cout); cout &lt;&lt; "." &lt;&lt; endl; #endif RBSTNode* l = target-&gt;left(); int as0 = l-&gt;size(); // re-order the sizes l-&gt;setSize( l-&gt;size() + (target-&gt;right() == NULL ? 0 : target-&gt;right()-&gt;size()) + 1); // a.size += b.right.size + 1; where b.right may be null. target-&gt;setSize( target-&gt;size() -as0 + (l-&gt;right() == NULL ? 0 : l-&gt;right()-&gt;size()) ); // b.size += -a_0_size + x.size where x may be null. // swap b's left (for a) target-&gt;setLeft(l-&gt;right()); // and a's right (for b's left) l-&gt;setRight(target); #ifdef DEBUG cout &lt;&lt; "A-node size: " &lt;&lt; l-&gt;size() &lt;&lt; ", b-node size: " &lt;&lt; target-&gt;size() &lt;&lt; "." &lt;&lt; endl; #endif // return the new root, a. return l; }; /** * Like rightRotate, but the other way. See docs for rightRotate(RBSTNode*) */ RBSTNode* RBST::leftRotate(RBSTNode* target) { if (target == NULL) throw "Invariant failure, target is null"; if (target-&gt;right() == NULL) throw "You cannot rotate left around a target whose right node is NULL!"; #ifdef DEBUG cout &lt;&lt;"Left-rotating a-node "; target-&gt;print(cout); cout &lt;&lt; " for b-node "; target-&gt;right()-&gt;print(cout); cout &lt;&lt; "." &lt;&lt; endl; #endif RBSTNode* r = target-&gt;right(); int bs0 = r-&gt;size(); // re-roder the sizes r-&gt;setSize(r-&gt;size() + (target-&gt;left() == NULL ? 0 : target-&gt;left()-&gt;size()) + 1); target-&gt;setSize(target-&gt;size() -bs0 + (r-&gt;left() == NULL ? 0 : r-&gt;left()-&gt;size())); // swap a's right (for b's left) target-&gt;setRight(r-&gt;left()); // swap b's left (for a) r-&gt;setLeft(target); #ifdef DEBUG cout &lt;&lt; "Left-rotation done: a-node size: " &lt;&lt; target-&gt;size() &lt;&lt; ", b-node size: " &lt;&lt; r-&gt;size() &lt;&lt; "." &lt;&lt; endl; #endif return r; }; // /** * Adds a key to the tree and returns the new root of the tree. * If the key already exists doesn't add anything. * Increments m_size if the key didn't already exist and hence was added. * * This function is not called from public methods, it's a helper function. */ RBSTNode* RBST::addRoot(RBSTNode* target, const Key&amp; key) { countAdd++; if (target == NULL) return new RBSTNode(key); #ifdef DEBUG cout &lt;&lt; "addRoot("; cout.flush(); target-&gt;print(cout) &lt;&lt; "," &lt;&lt; key &lt;&lt; ") called." &lt;&lt; endl; #endif if (*target &lt; key) { target-&gt;setRight( addRoot(target-&gt;right(), key) ); target-&gt;incSize(); // Should I? RBSTNode* res = leftRotate(target); #ifdef DEBUG if (target-&gt;size() != size(target)) BUG("in addRoot 1"); #endif return res; } target-&gt;setLeft( addRoot(target-&gt;left(), key) ); target-&gt;incSize(); // Should I? RBSTNode* res = rightRotate(target); #ifdef DEBUG if (target-&gt;size() != size(target)) BUG("in addRoot 2"); #endif return res; }; /** * This function is called from the public add(key) function, * and returns the new root node. */ RBSTNode* RBST::randomAdd(RBSTNode* target, const Key&amp; key) { countAdd++; if (target == NULL) { m_size++; return new RBSTNode(key); } #ifdef DEBUG cout &lt;&lt; "randomAdd("; target-&gt;print(cout) &lt;&lt; ", \"" &lt;&lt; key &lt;&lt; "\") called." &lt;&lt; endl; #endif int r = (rand() % target-&gt;size()) + 1; // here is where we add the target as root! if (r == 1) { m_size++; // TODO: Need to lock. return addRoot(target, key); } #ifdef DEBUG printf("randomAdd recursion part, "); #endif // otherwise, continue recursing! if (*target &lt;= key) { #ifdef DEBUG printf("target &lt;= key\n"); #endif target-&gt;setRight( randomAdd(target-&gt;right(), key) ); target-&gt;incSize(); // TODO: Need to lock. #ifdef DEBUG if (target-&gt;right()-&gt;size() != size(target-&gt;right())) BUG("in randomAdd 1"); #endif } else { #ifdef DEBUG printf("target &gt; key\n"); #endif target-&gt;setLeft( randomAdd(target-&gt;left(), key) ); target-&gt;incSize(); // TODO: Need to lock. #ifdef DEBUG if (target-&gt;left()-&gt;size() != size(target-&gt;left())) BUG("in randomAdd 2"); #endif } #ifdef DEBUG printf("randomAdd return part\n"); #endif m_size++; // TODO: Need to lock. return target; }; ///////////////////////////////////////////////////////////// ///////////////////// DEL FUNCTIONS //////////////////////// ///////////////////////////////////////////////////////////// /** * Deletes a node with the passed key. * Returns the root node. * Decrements m_size if something was deleted. */ RBSTNode* RBST::del(RBSTNode* target, const Key&amp; key) { countDelete++; if (target == NULL) return NULL; #ifdef DEBUG cout &lt;&lt; "del("; target-&gt;print(cout) &lt;&lt; ", \"" &lt;&lt; key &lt;&lt; "\") called." &lt;&lt; endl; #endif RBSTNode* ret = NULL; // found the node to delete if (*target == key) { ret = join(target-&gt;left(), target-&gt;right()); m_size--; delete target; return ret; // return the newly built joined subtree! } // store a temporary size before recursive deletion. unsigned int size = m_size; if (*target &lt; key) target-&gt;setRight( del(target-&gt;right(), key) ); else target-&gt;setLeft( del(target-&gt;left(), key) ); // if the previous recursion changed the size, we need to decrement the size of this target too. if (m_size &lt; size) target-&gt;decrSize(); #ifdef DEBUG if (RBST::size(target) != target-&gt;size()) BUG("in del"); #endif return target; }; /** * Joins the two subtrees represented by left and right * by randomly choosing which to make the root, weighted on the * size of the sub-tree. */ RBSTNode* RBST::join(RBSTNode* left, RBSTNode* right) { if (left == NULL) return right; if (right == NULL) return left; #ifdef DEBUG cout &lt;&lt; "join("; left-&gt;print(cout); cout &lt;&lt; ","; right-&gt;print(cout) &lt;&lt; ") called." &lt;&lt; endl; #endif // Find the chance that we use the left tree, based on its size over the total tree size. // 3 s.d. randomness :-p e.g. 60.3% chance. bool useLeft = ((rand()%1000) &lt; (signed)((float)left-&gt;size()/(float)(left-&gt;size() + right-&gt;size()) * 1000.0)); RBSTNode* subtree = NULL; if (useLeft) { subtree = join(left-&gt;right(), right); left-&gt;setRight(subtree) -&gt;setSize((left-&gt;left() == NULL ? 0 : left-&gt;left()-&gt;size()) + subtree-&gt;size() + 1 ); #ifdef DEBUG if (size(left) != left-&gt;size()) BUG("in join 1"); #endif return left; } subtree = join(right-&gt;left(), left); right-&gt;setLeft(subtree) -&gt;setSize((right-&gt;right() == NULL ? 0 : right-&gt;right()-&gt;size()) + subtree-&gt;size() + 1); #ifdef DEBUG if (size(right) != right-&gt;size()) BUG("in join 2"); #endif return right; }; ///////////////////////////////////////////////////////////// ///////////////////// FIND FUNCTIONS /////////////////////// ///////////////////////////////////////////////////////////// /** * Tries to find the key in the tree starting * search from target. * * Returns NULL if it was not found. */ RBSTNode* RBST::find(RBSTNode* target, const Key&amp; key) { countFind++; // Could use private method only counting the first call. if (target == NULL) return NULL; // not found. if (*target == key) return target; // found (does string override ==?) if (*target &lt; key) return find(target-&gt;right(), key); // search for gt to the right. return find(target-&gt;left(), key); // search for lt to the left. }; #ifdef DEBUG unsigned int RBST::size(RBSTNode* x) { if (x == NULL) return 0; return 1 + size(x-&gt;left()) + size(x-&gt;right()); } #endif </code></pre> <p>I'll save the SkipList for another time since it's already possible to find good implementations of a SkipList from the links and my version wasn't much different.</p> <p>The graphs generated from the test-file are as follows:</p> <p><strong>Graph showing time taken to add new items for BloomFilter, RBST and SkipList.</strong> <a href="http://haf.se/content/dl/addtimer.png" rel="noreferrer">graph http://haf.se/content/dl/addtimer.png</a></p> <p><strong>Graph showing time taken to find items for BloomFilter, RBST and SkipList</strong> <a href="http://haf.se/content/dl/findtimer.png" rel="noreferrer">graph http://haf.se/content/dl/findtimer.png</a></p> <p><strong>Graph showing time taken to delete items for BloomFilter, RBST and SkipList</strong> <a href="http://haf.se/content/dl/deltimer.png" rel="noreferrer">graph http://haf.se/content/dl/deltimer.png</a></p> <p>So as you can see, the random binary search tree was rather a lot better than the SkipList. The bloom filter lives up to its O(k).</p>
1,259,269
What's the best C# Twitter API for a twitter bot
<p>I'm writing a C# app that will be required to integrate with twitter, I need to be able to do the following:</p> <ul> <li>send direct messages</li> <li>read all messages that are either @helloapp or #helloapp</li> </ul> <p>If you are interested the app is part of <a href="http://carsonified.com" rel="noreferrer">Carsonified</a>'s app in 4 days for FOWA. Read more <a href="http://thinkvitamin.com/code/sketches-wireframes-logo-ideas-meet-our-new-app/" rel="noreferrer">here</a> or see the <a href="http://search.twitter.com/search?q=%23helloapp" rel="noreferrer">tweets</a>.</p>
1,259,295
6
1
null
2009-08-11 09:21:47.453 UTC
9
2014-11-21 01:27:41.293 UTC
2011-08-21 19:16:55.967 UTC
null
239,076
null
27,782
null
1
25
c#|twitter
17,896
<p><a href="https://github.com/danielcrenna/tweetsharp" rel="noreferrer">TweetSharp</a> can take care of both those requirements.</p> <p>Yedda doesn't support Direct Messages as of now.</p>
1,134,667
Django required field in model form
<p>I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py</p> <pre><code>class CircuitForm(ModelForm): class Meta: model = Circuit exclude = ('lastPaged',) def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) self.fields['begin'].widget = widgets.AdminSplitDateTime() self.fields['end'].widget = widgets.AdminSplitDateTime() </code></pre> <p>In the actual Circuit model, the fields are defined like this:</p> <pre><code>begin = models.DateTimeField('Start Time', null=True, blank=True) end = models.DateTimeField('Stop Time', null=True, blank=True) </code></pre> <p>My views.py for this is here:</p> <pre><code>def addCircuitForm(request): if request.method == 'POST': form = CircuitForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/sla/all') form = CircuitForm() return render_to_response('sla/add.html', {'form': form}) </code></pre> <p>What can I do so that the two fields aren't required?</p>
1,429,646
6
2
null
2009-07-15 23:37:16.727 UTC
23
2017-02-15 10:28:00.377 UTC
2015-12-19 09:42:33.833 UTC
null
546,822
null
139,082
null
1
78
python|django|forms|model|widget
85,011
<p>If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:</p> <pre><code>def __init__(self, *args, **kwargs): super(CircuitForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = False </code></pre> <p>The redefined constructor won't harm any functionality.</p>
680,044
log4net argument to LogManager.GetLogger
<p>Why do most log4net examples get the logger for a class by doing this:</p> <pre><code>private static ILog logger = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); </code></pre> <p>Rather than just passing typeof(MyClass):</p> <pre><code>private static ILog logger = LogManager.GetLogger(typeof(MyClass)); </code></pre> <p>Is there any other reason for doing this, beside the fact that the first option does not require you to type a specific class name?</p>
680,065
6
0
null
2009-03-25 02:44:54.283 UTC
14
2022-07-09 01:14:35.853 UTC
null
null
null
Andy White
60,096
null
1
99
log4net
85,872
<p>I think you've got the reason. I do it that way so I don't have to worry about the class name and can just copy and paste boiler plate code in a new class.</p> <p>For the official answer, see: How do I get the fully-qualified name of a class in a static block? at the <a href="http://logging.apache.org/log4net/release/faq.html#static-class-name" rel="noreferrer">log4net faq</a></p>
42,334,698
Error installing json 1.8.3 with ruby 2.4
<p>[version information]</p> <p>ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-linux] / gem 2.0.3 / Windows 10</p> <p>I ran <code>bundle install</code> and it told me to run <code>gem install json -v '1.8.3'</code></p> <p>I did that and got a <em>Failed to build gem native extension</em> error.</p> <pre><code>Building native extensions. This could take a while... ERROR: Error installing json: ERROR: Failed to build gem native extension. /home/ec2-user/.rvm/rubies/ruby-2.4.0/bin/ruby extconf.rb creating Makefile make compiling generator.c generator.c: In function ‘generate_json’: generator.c:861:25: error: ‘rb_cFixnum’ undeclared (first use in this function) } else if (klass == rb_cFixnum) { ^ generator.c:861:25: note: each undeclared identifier is reported only once for each function it appears in generator.c:863:25: error: ‘rb_cBignum’ undeclared (first use in this function) } else if (klass == rb_cBignum) { ^ generator.c: At top level: cc1: warning: unrecognized command line option "-Wno-self-assign" [enabled by default] cc1: warning: unrecognized command line option "-Wno-constant-logical-operand" [enabled by default] cc1: warning: unrecognized command line option "-Wno-parentheses-equality" [enabled by default] cc1: warning: unrecognized command line option "-Wno-tautological-compare" [enabled by default] make: *** [generator.o] Error 1 Gem files will remain installed in /home/ec2-user/.rvm/gems/ruby-2.4.0/gems/json-1.8.3 for inspection. Results logged to /home/ec2-user/.rvm/gems/ruby-2.4.0/gems/json-1.8.3/ext/json/ext/generator/gem_make.out </code></pre> <p>I've checked several documents. I installed Devkit and json 1.8.5 but my project keeps the message that "install json 1.8.3" How can I solve this problem??</p> <p><code>/home/ec2-user/.rvm/gems/ruby-2.4.0/gems/json-1.8.3</code> contains:</p> <pre><code>../ ./ data/ diagrams/ ext/ java/ lib/ tests/ tools/ install.rb* .gitignore .travis.yml CHANGES COPYING COPYING-json-jruby GPL Gemfile README-json-jruby.markdown README.rdoc Rakefile </code></pre> <p><code>/home/ec2-user/.rvm/gems/ruby-2.4.0/gems/json-1.8.3/ext/json/ext/generator/gem_make.out</code> contains:</p> <pre><code>user/.rvm/gems/ruby-2.4.0/gems/json-1.8.3/ext/json/ext/generator/gem_make.out /home/ec2-user/.rvm/rubies/ruby-2.4.0/bin/ruby extconf.rb creating Makefile make compiling generator.c generator.c: In function ‘generate_json’: generator.c:861:25: error: ‘rb_cFixnum’ undeclared (first use in this function) } else if (klass == rb_cFixnum) { ^ generator.c:861:25: note: each undeclared identifier is reported only once for each function it appears in generator.c:863:25: error: ‘rb_cBignum’ undeclared (first use in this function) } else if (klass == rb_cBignum) { ^ generator.c: At top level: cc1: warning: unrecognized command line option "-Wno-self-assign" [enabled by default] cc1: warning: unrecognized command line option "-Wno-constant-logical-operand" [enabled by default] cc1: warning: unrecognized command line option "-Wno-parentheses-equality" [enabled by default] cc1: warning: unrecognized command line option "-Wno-tautological-compare" [enabled by default] make: *** [generator.o] Error 1 </code></pre>
42,337,669
8
3
null
2017-02-20 00:32:29.54 UTC
3
2020-06-06 04:22:51.723 UTC
2017-08-31 14:18:45.453 UTC
null
421,705
null
6,698,218
null
1
29
ruby
17,570
<p>I ran into the same issue recently as well, try and see if there's a newer version of whatever gem you're using that depends on json 1.8.3. This is happening because Ruby 2.4 unified <a href="https://bugs.ruby-lang.org/issues/12005" rel="noreferrer">Fixnum and Bignum into Integer</a>. If you're able to upgrade to <a href="https://github.com/flori/json/issues/311" rel="noreferrer">json 1.8.5</a> or higher, it should help fix your problems.</p> <p>You could also try and update the gem you're using and try to relax the version constraints (I've found this to work with a lot of projects, but not all) like so:</p> <pre><code>gem 'json', '&gt;= 1.8' </code></pre>
30,811,668
PHP 7: Missing VCRUNTIME140.dll
<p>I have an error when I start PHP&nbsp;7 on Windows. When I run <code>php</code> on the command line, it returns a message box with system error:</p> <blockquote> <p>The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.</p> </blockquote> <p>After that, <code>CLI</code> is crashing.</p> <p>As I don't want to install a DLL file from an external website, I don't know how to fix this!</p> <p><strong>PHP version:</strong> <a href="http://windows.php.net/downloads/qa/php-7.0.0alpha1-Win32-VC14-x64.zip" rel="noreferrer">7.0.0alpha1 VC14 x64 Thread Safe</a></p>
30,826,746
9
4
null
2015-06-12 20:27:53.227 UTC
22
2020-08-25 21:30:05.167 UTC
2017-05-30 21:32:09.363 UTC
null
5,282,060
null
4,255,773
null
1
174
php|windows|dll|php-7
648,352
<p>On the <em>side bar</em> of the <a href="http://windows.php.net/qa/" rel="noreferrer">PHP 7 alpha download page</a>, it does say this:</p> <blockquote> <p>VC9, VC11 &amp; VC14 More recent versions of PHP are built with VC9, VC11 or VC14 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.</p> <ul> <li><p>The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 <a href="http://www.microsoft.com/en-us/download/details.aspx?id=5582" rel="noreferrer">x86</a> or <a href="http://www.microsoft.com/en-us/download/details.aspx?id=15336" rel="noreferrer">x64</a> installed</p></li> <li><p>The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 <a href="http://www.microsoft.com/en-us/download/details.aspx?id=30679" rel="noreferrer">x86 or x64</a> installed</p></li> <li><p>The VC14 builds require to have the Visual C++ Redistributable for Visual Studio 2015 <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48145" rel="noreferrer">x86 or x64</a> installed</p></li> </ul> </blockquote> <p><sup>There's been a problem with some of those links, so the files are also available from <a href="http://www.softpedia.com/get/Programming/Components-Libraries/Microsoft-Visual-C-Redistributable-Package.shtml#download" rel="noreferrer">Softpedia</a>.</sup></p> <p>In the case of the PHP 7 alpha, it's the last option that's required.</p> <p>I think that the placement of this information is poor, as it's kind of marginalized (i.e.: it's basically literally in the margin!) whereas it's actually critical for the software to run.</p> <p>I documented my experiences of getting PHP 7 alpha up and running on Windows 8.1 in <a href="http://blog.adamcameron.me/2015/06/php-getting-php7-alpha-running-on.html" rel="noreferrer">PHP: getting PHP7 alpha running on Windows 8.1</a>, and it covers some more symptoms that might crop up. They're out of scope for this question but might help other people.</p> <p>Other symptom of this issue:</p> <ul> <li>Apache not starting, claiming <code>php7apache2_4.dll</code> is missing despite it definitely being in place, and offering nothing else in any log.</li> <li><code>php-cgi.exe - The FastCGI process exited unexpectedly</code> (as per @ftexperts's comment below)</li> </ul> <p>Attempted solution:</p> <ul> <li>Using the <code>php7apache2_4.dll</code> file from an earlier PHP 7 dev build. <em>This did not work.</em></li> </ul> <p>(I include those for googleability.)</p>
20,916,472
Why use !!(condition) instead of (condition)?
<p>I've seen code where people have used conditional clauses with two '!'s</p> <pre><code>#define check_bit(var, pos) (!!((var) &amp; (1 &lt;&lt; (pos)))) #define likely(x) __builtin_expect(!!(x),1) #define unlikely(x) __builtin_expect(!!(x),0) </code></pre> <p>are some of the examples I could find.</p> <p>Is there any advantage in using <code>!!(condition)</code> over <code>(condition)</code>?</p>
20,916,491
4
4
null
2014-01-04 03:27:57.257 UTC
3
2015-05-08 21:54:25.57 UTC
2014-01-04 04:12:15.49 UTC
null
1,708,801
null
1,331,592
null
1
35
c|logical-operators
2,693
<p>Well if the variable you are applying <code>!!</code> is not already a <code>bool</code>(<em>either zero or one</em>) then it will <em>normalize</em> the value to either <code>0</code> or <code>1</code>.</p> <p>With respect to <code>__builtin_expect</code> this <a href="http://comments.gmane.org/gmane.linux.kernel.kernelnewbies/5700" rel="noreferrer">kernel newbies thread</a> discusses the notation and one of the responses explains (<em>emphasis mine</em>):</p> <blockquote> <p>The signature of __builtin_expect</p> <p><a href="http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html" rel="noreferrer">http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html</a>) is:</p> <p>long __builtin_expect (long exp, long c)</p> <p>Note that the exp parameter should be an integral expression, thus no pointers or floating point types there. The <strong>double negation handles the conversion from these types to integral expressions automatically</strong>. This way, <strong>you can simply write: likely(ptr) instead of likely(ptr != NULL)</strong>.</p> </blockquote> <p>For reference in <em>C99</em> <code>bool</code> macro expands to <code>_Bool</code>, <code>true</code> expands to <code>1</code> and <code>false</code> expands to <code>0</code>. The details are given in the draft standard section <code>7.16</code> <em>Boolean type and values </em>.</p> <p>Logical negation is covered in <code>6.5.3.3</code> <em>Unary arithmetic operators</em> in paragraph <em>5</em>:</p> <blockquote> <p>The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).</p> </blockquote>
33,138,979
How to change ${USER} variable in IntelliJ IDEA without changing OS user name?
<p>By <code>${USER}</code> Intellij idea <a href="https://www.jetbrains.com/idea/help/creating-and-editing-file-templates.html" rel="noreferrer">means</a> the login name of the current user. But what if login differ from name used as developer name? Is it possible to set <code>USER</code> to other value without changing OS login name?</p>
33,140,805
3
3
null
2015-10-15 02:48:07.073 UTC
17
2022-08-29 15:20:17.733 UTC
2018-02-19 14:31:29.85 UTC
null
1,000,551
null
1,251,549
null
1
43
java|templates|intellij-idea
29,030
<p>You can modify the file <strong>idea.exe.vmoptions</strong> or <strong>idea64.exe.vmoptions</strong>, which should be in the bin folder of your IDE installation. For linux version, it could be <strong>idea.vmoptions</strong>. You need to add there a parameter:</p> <pre><code>-Duser.name=YOURNAME </code></pre> <h3>How to open the file:</h3> <ul> <li><code>Ctrl+Shift+A</code> &gt; type &quot;vm options&quot; &gt; select option</li> <li>Help &gt; Edit custom VM options...</li> </ul> <p>This would make your <code>${USER}</code> variable inside IntelliJ Idea equals to parameter value and you don't have to change the current OS user login name. I've just tested it in the IntelliJ Idea 14.1.3 with file and code templates.</p>
1,821,429
DBGrid get selected cell
<p>I need to get the value of the selected cell of a DBGrid in Delphi.</p> <p>I have no idea how to do it. I tried dbGrid's OnMouseMove</p> <pre><code>pt : TGridCoord; ... pt:=dbGrid.MouseCoord(x, y); </code></pre> <p>[Edited] I can use the OnCellClick to get the value of the cell with "Column.Field.AsString", but I want to get the value from the first column when I click on any column of that row.</p>
1,821,675
6
0
null
2009-11-30 18:11:20.117 UTC
null
2017-09-13 14:44:21.63 UTC
2011-05-17 19:04:53.927 UTC
null
496,830
null
184,401
null
1
5
delphi|dbgrid
58,186
<p>Found it.</p> <p><code>dbGrid.Fields[0].AsString</code> gets the value of the first column of the selected row.</p>
1,796,510
Accessing a Python traceback from the C API
<p>I'm having some trouble figuring out the proper way to walk a Python traceback using the C API. I'm writing an application that embeds the Python interpreter. I want to be able to execute arbitrary Python code, and if it raises an exception, to translate it to my own application-specific C++ exception. For now, it is sufficient to extract just the file name and line number where the Python exception was raised. This is what I have so far:</p> <pre><code>PyObject* pyresult = PyObject_CallObject(someCallablePythonObject, someArgs); if (!pyresult) { PyObject* excType, *excValue, *excTraceback; PyErr_Fetch(&amp;excType, &amp;excValue, &amp;excTraceback); PyErr_NormalizeException(&amp;excType, &amp;excValue, &amp;excTraceback); PyTracebackObject* traceback = (PyTracebackObject*)traceback; // Advance to the last frame (python puts the most-recent call at the end) while (traceback-&gt;tb_next != NULL) traceback = traceback-&gt;tb_next; // At this point I have access to the line number via traceback-&gt;tb_lineno, // but where do I get the file name from? // ... } </code></pre> <p>Digging around in the Python source code, I see they access both the filename and module name of the current frame via the <code>_frame</code> structure, which looks like it is a privately-defined struct. My next idea was to programmatically load the Python 'traceback' module and call its functions with the C API. Is this sane? Is there a better way to access a Python traceback from C?</p>
1,796,569
7
2
null
2009-11-25 12:05:44.487 UTC
10
2021-12-02 10:26:23.66 UTC
null
null
null
null
4,828
null
1
30
python
13,062
<p>I've discovered that <code>_frame</code> is actually defined in the <code>frameobject.h</code> header included with Python. Armed with this plus looking at <code>traceback.c</code> in the Python C implementation, we have:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;frameobject.h&gt; PyTracebackObject* traceback = get_the_traceback(); int line = traceback-&gt;tb_lineno; const char* filename = PyString_AsString(traceback-&gt;tb_frame-&gt;f_code-&gt;co_filename); </code></pre> <p>But this still seems really dirty to me.</p>
2,063,438
Rails - How do you test ActionMailer sent a specific email in tests
<p>Currently in my tests I do something like this to test if an email is queued to be sent </p> <pre><code>assert_difference('ActionMailer::Base.deliveries.size', 1) do get :create_from_spreedly, {:user_id =&gt; @logged_in_user.id} end </code></pre> <p>but if i a controller action can send two different emails i.e. one to the user if sign up goes fine or a notification to admin if something went wrong - how can i test which one actually got sent. The code above would pass regardless.</p>
2,064,113
7
0
null
2010-01-14 10:30:27.053 UTC
15
2020-09-23 10:28:21.173 UTC
2014-06-16 21:19:06.07 UTC
null
168,143
null
189,090
null
1
53
ruby-on-rails|unit-testing|actionmailer
41,858
<p>When using the ActionMailer during tests, all mails are put in a big array called <code>deliveries</code>. What you basically are doing (and is sufficient mostly) is checking if emails are present in the array. But if you want to specifically check for a certain email, you have to know what is actually stored in the array. Luckily the emails themselves are stored, thus you are able to iterate through the array and check each email.</p> <p>See <a href="http://api.rubyonrails.org/classes/ActionMailer/Base.html" rel="noreferrer">ActionMailer::Base</a> to see what configuration methods are available, which you can use to determine what emails are present in the array. Some of the most suitable methods for your case probably are</p> <ul> <li><code>recipients</code>: Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the To: header.</li> <li><code>subject</code>: The subject of your email. Sets the Subject: header. </li> </ul>
2,269,803
How to get all enum values in Java?
<p>I came across this problem that I without knowing the actual <code>enum</code> type I need to iterate its possible values.</p> <pre><code>if (value instanceof Enum){ Enum enumValue = (Enum)value; } </code></pre> <p>Any ideas how to extract from enumValue its possible values ?</p>
2,269,871
8
0
null
2010-02-16 00:02:49.803 UTC
18
2022-01-18 14:53:18.323 UTC
2017-09-06 09:18:00.193 UTC
null
2,147,927
null
141,321
null
1
123
java|enums
167,335
<p>Call <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Class.html#getEnumConstants()" rel="noreferrer"><code>Class#getEnumConstants</code></a> to get the enum’s elements (or get null if not an enum class).</p> <pre><code>Object[] possibleValues = enumValue.getDeclaringClass().getEnumConstants(); </code></pre>
1,346,207
Qt Application Performance vs. WinAPI/MFC/WTL/
<p>I'm considering writing a new Windows GUI app, where one of the requirements is that the app must be very responsive, quick to load, and have a light memory footprint.</p> <p>I've used WTL for previous apps I've built with this type of requirement, but as I use .NET all the time in my day job WTL is getting more and more painful to go back to. I'm not interested in using .NET for this app, as I still find the performance of larger .NET UIs lacking, but I am interested in using a better C++ framework for the UI - like Qt.</p> <p>What I want to be sure of before starting is that I'm not going to regret this on the performance front. </p> <p><strong>So: Is Qt fast?</strong></p> <p>I'll try and qualify the question by examples of what I'd like to come close to matching: My current WTL app is <a href="http://pnotepad.org/" rel="noreferrer">Programmer's Notepad</a>. The current version I'm working on weighs in at about 4mb of code for a 32-bit, release compiled version with a single language translation. On a modern fast PC it takes 1-3 seconds to load, which is important as people fire it up often to avoid IDEs etc. The memory footprint is usually 12-20 mb on 64-bit Win7 once you've been editing for a while. You can run the app non-stop, leave it minimized, whatever and it always jumps to attention instantly when you switch to it.</p> <p>For the sake of argument let's say I want to port my WTL app to Qt for potential future cross-platform support and/or the much easier UI framework. I want to come close to if not match this level of performance with Qt.</p>
1,346,278
9
0
null
2009-08-28 10:37:59.443 UTC
12
2012-06-18 03:49:14.53 UTC
2011-05-23 10:53:39.713 UTC
null
122,460
null
4,591
null
1
35
c++|performance|qt
26,092
<p>Going native API is the most performant choice by definition - anything other than that is a wrapper around native API.</p> <p>What exactly do you expect to be the performance bottleneck? Any strict numbers? Honestly, vague ,,very responsive, quick to load, and have a light memory footprint'' sounds like a requirement gathering bug to me. Performance is often overspecified.</p> <p>To the point:</p> <p>Qt's signal-slot mechanism is really fast. It's statically typed and translates with MOC to quite simple slot method calls.</p> <p>Qt offers nice multithreading support, so that you can have responsive GUI in one thread and whatever else in other threads without much hassle. That might work.</p>
1,840,538
Faster alternative in Oracle to SELECT COUNT(*) FROM sometable
<p>I've notice that in Oracle, the query</p> <pre><code>SELECT COUNT(*) FROM sometable; </code></pre> <p>is very slow for large tables. It seems like the database it actually going through every row and incrementing a counter one at a time. I would think that there would be a counter somewhere in the table how many rows that table has.</p> <p>So if I want to check the number of rows in a table in Oracle, what is the fastest way to do that?</p>
1,840,613
11
3
null
2009-12-03 15:18:40.63 UTC
19
2020-02-04 15:12:44.097 UTC
null
null
null
null
1,694
null
1
69
oracle|count
204,973
<p>Think about it: the database really has to go to every row to do that. <strong>In a multi-user environment my <code>COUNT(*)</code> could be different from your <code>COUNT(*)</code></strong>. It would be impractical to have a different counter for each and every session so you have literally to count the rows. Most of the time anyway you would have a WHERE clause or a JOIN in your query so your hypothetical counter would be of litte practical value.</p> <p>There are ways to speed up things however: if you have an INDEX on a NOT NULL column Oracle will count the rows of the index instead of the table. In a proper relational model all tables have a primary key so the <code>COUNT(*)</code> will use the index of the primary key.</p> <p>Bitmap index have entries for NULL rows so a COUNT(*) will use a bitmap index if there is one available.</p>
1,933,241
Is valid HTML5 OK to use now?
<p>I've been reading about HTML5 and would like to start using some of it, particularly datasets as I've found an interesting looking jQuery plugin that I can start using...</p> <p><a href="http://www.barklund.org/blog/2009/08/28/html-5-datasets/" rel="noreferrer">http://www.barklund.org/blog/2009/08/28/html-5-datasets/</a></p> <p>Now, I understand that older browsers like IE6 may not like having extra attributes in there and may not know what to do with them but if they ignore them and the site still validates using an HTML5 validator then that should be OK, no?</p> <p>I especially want to make sure I'm not going to get penalised by Google etc. for not having valid markup and that I'm not going to get complaints from clients that their site is "not valid" when they check it using a bog standard W3C validator.</p> <p>What are people's thoughts on this?</p>
1,933,377
14
16
null
2009-12-19 15:46:34.093 UTC
8
2012-10-01 12:24:53.323 UTC
2009-12-19 15:53:43.29 UTC
null
6,144
null
56,007
null
1
37
jquery|css|html
3,074
<p>I'd recommend checking out <a href="http://fortuito.us/diveintohtml5/" rel="nofollow noreferrer">Dive Into HTML 5</a> and deciding for yourself if you think the tradeoffs are acceptable. So far as I've heard, there are no negative SEO implications for using HTML 5. I just ran the w3c validator on <em>Dive Into HTML 5</em> and it automatically detected that it was HTML 5 and validated it, so I don't think that will be a concern, either.</p>
1,589,466
Execute stored procedure with an Output parameter?
<p>I have a stored procedure that I am trying to test. I am trying to test it through SQL Management Studio. In order to run this test I enter ...</p> <pre><code>exec my_stored_procedure 'param1Value', 'param2Value' </code></pre> <p>The final parameter is an <code>output parameter</code>. However, I do not know how to test a stored procedure with output parameters.</p> <p>How do I run a stored procedure with an output parameter?</p>
1,589,493
14
0
null
2009-10-19 15:44:11.99 UTC
35
2022-04-08 18:31:51.48 UTC
2013-10-09 02:54:53.51 UTC
null
729,907
null
70,192
null
1
237
sql-server|stored-procedures
843,713
<p>The easy way is to right-click on the procedure in Sql Server Management Studio (SSMS), select 'Execute stored procedure...&quot; and add values for the input parameters as prompted. SSMS will then generate the code to run the procedure in a new query window, and execute it for you. You can study the generated code to see how it is done.</p>
2,263,096
CSS file not refreshing in browser
<p>When I make any changes to my CSS file, the changes are not reflected in the browser. How can I fix this?</p>
2,263,105
15
3
null
2010-02-14 22:34:17.877 UTC
14
2022-02-14 12:33:23.797 UTC
2019-03-15 17:56:19.63 UTC
null
8,206,432
null
14,752
null
1
69
css
135,570
<p>Try opening the style sheet itself (by entering its address into the browser's address bar) and pressing <kbd>F5</kbd>. If it still doesn't refresh, your problem lies elsewhere.</p> <p>If you update a style sheet and want to make sure it gets refreshed in every visitor's cache, a very popular method to do that is to add a version number as a GET parameter. That way, the style sheet gets refreshed when necessary, but not more often than that.</p> <pre><code>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;styles.css?version=51&quot;&gt; </code></pre>
33,949,786
How could I use batch normalization in TensorFlow?
<p>I would like to use <em>batch normalization</em> in TensorFlow. I found the related C++ source code in <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/nn_ops.cc" rel="noreferrer"><code>core/ops/nn_ops.cc</code></a>. However, I did not find it documented on tensorflow.org.</p> <p>BN has different semantics in MLP and CNN, so I am not sure what exactly this BN does.</p> <p>I did not find a method called <code>MovingMoments</code> either.</p>
33,950,177
8
4
null
2015-11-27 03:17:52.33 UTC
47
2018-07-11 17:34:39.07 UTC
2018-07-08 14:42:24.463 UTC
null
3,924,118
null
3,090,897
null
1
78
python|tensorflow
90,529
<p><strong>Update July 2016</strong> The easiest way to use batch normalization in TensorFlow is through the higher-level interfaces provided in either <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/layers.py" rel="noreferrer">contrib/layers</a>, <a href="http://tflearn.org/layers/normalization/" rel="noreferrer">tflearn</a>, or <a href="https://github.com/tensorflow/models/blob/master/inception/inception/slim/ops.py" rel="noreferrer">slim</a>.</p> <p><strong>Previous answer if you want to DIY</strong>: The documentation string for this has improved since the release - see the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/nn_ops.cc#L65" rel="noreferrer">docs comment in the master branch</a> instead of the one you found. It clarifies, in particular, that it's the output from <code>tf.nn.moments</code>.</p> <p>You can see a very simple example of its use in the <a href="https://github.com/tensorflow/tensorflow/blob/3972c791b9f4d9a61b9ad6399b481df396f359ff/tensorflow/python/ops/nn_test.py#L518" rel="noreferrer">batch_norm test code</a>. For a more real-world use example, I've included below the helper class and use notes that I scribbled up for my own use (no warranty provided!):</p> <pre class="lang-py prettyprint-override"><code>"""A helper class for managing batch normalization state. This class is designed to simplify adding batch normalization (http://arxiv.org/pdf/1502.03167v3.pdf) to your model by managing the state variables associated with it. Important use note: The function get_assigner() returns an op that must be executed to save the updated state. A suggested way to do this is to make execution of the model optimizer force it, e.g., by: update_assignments = tf.group(bn1.get_assigner(), bn2.get_assigner()) with tf.control_dependencies([optimizer]): optimizer = tf.group(update_assignments) """ import tensorflow as tf class ConvolutionalBatchNormalizer(object): """Helper class that groups the normalization logic and variables. Use: ewma = tf.train.ExponentialMovingAverage(decay=0.99) bn = ConvolutionalBatchNormalizer(depth, 0.001, ewma, True) update_assignments = bn.get_assigner() x = bn.normalize(y, train=training?) (the output x will be batch-normalized). """ def __init__(self, depth, epsilon, ewma_trainer, scale_after_norm): self.mean = tf.Variable(tf.constant(0.0, shape=[depth]), trainable=False) self.variance = tf.Variable(tf.constant(1.0, shape=[depth]), trainable=False) self.beta = tf.Variable(tf.constant(0.0, shape=[depth])) self.gamma = tf.Variable(tf.constant(1.0, shape=[depth])) self.ewma_trainer = ewma_trainer self.epsilon = epsilon self.scale_after_norm = scale_after_norm def get_assigner(self): """Returns an EWMA apply op that must be invoked after optimization.""" return self.ewma_trainer.apply([self.mean, self.variance]) def normalize(self, x, train=True): """Returns a batch-normalized version of x.""" if train: mean, variance = tf.nn.moments(x, [0, 1, 2]) assign_mean = self.mean.assign(mean) assign_variance = self.variance.assign(variance) with tf.control_dependencies([assign_mean, assign_variance]): return tf.nn.batch_norm_with_global_normalization( x, mean, variance, self.beta, self.gamma, self.epsilon, self.scale_after_norm) else: mean = self.ewma_trainer.average(self.mean) variance = self.ewma_trainer.average(self.variance) local_beta = tf.identity(self.beta) local_gamma = tf.identity(self.gamma) return tf.nn.batch_norm_with_global_normalization( x, mean, variance, local_beta, local_gamma, self.epsilon, self.scale_after_norm) </code></pre> <p>Note that I called it a <code>ConvolutionalBatchNormalizer</code> because it pins the use of <code>tf.nn.moments</code> to sum across axes 0, 1, and 2, whereas for non-convolutional use you might only want axis 0.</p> <p>Feedback appreciated if you use it.</p>
8,444,710
Java way to check if a string is palindrome
<p>I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations</p>
8,444,732
11
2
null
2011-12-09 11:19:58.757 UTC
12
2017-08-09 15:09:03.597 UTC
2017-08-09 15:09:03.597 UTC
null
1,008,222
null
1,008,222
null
1
20
java|string
226,622
<p>You can try something like this :</p> <pre><code> String variable = ""; #write a string name StringBuffer rev = new StringBuffer(variable).reverse(); String strRev = rev.toString(); if(variable.equalsIgnoreCase(strRev)) # Check the condition </code></pre>
6,874,958
webkitTransitionEnd event fired when transitions end on div AND transitions end on all CHILD divs?
<p>All,</p> <p>I have a situation that looks roughly like this:</p> <p>My HTML page a contains div (which I'll call <strong>"parentDiv"</strong>) on which I'm performing a transition. When that transition ends, it should call <strong>"onTransitionEndParent"</strong></p> <p>parentDiv contains a div (which I'll call <strong>"childDiv"</strong>) on which I'm performing a <em>different</em> transition. When that transition ends, it should call <strong>"onTransitionEndChild"</strong>.</p> <p>So, my code looks roughly like this:</p> <pre><code>parentDiv.addEventListener("webkitTransitionEnd", onTransitionEndParent, false); childDiv.addEventListener("webkitTransitionEnd", onTransitionEndChild, false); </code></pre> <p>The problem I'm finding...</p> <p>onTransitionEndParent is called when the parentDiv's transition ends (correct). However, it's <strong>ALSO</strong> called when childDiv's transition ends (not what I expected...)</p> <p>In other words...</p> <ul> <li>onTransitionEndChild is called when childDiv's transition ends</li> <li>onTransitionEndParent is called when parentDiv's transition ends <strong>AND AGAIN</strong> when childDiv's transition ends</li> </ul> <p>Is this the correct behavior, or am I doing something wrong?</p> <p>Is there a way to make sure that onTransitionEndParent is ONLY called when the parentDiv's transition ends, and NOT when any of it's child div's transitions end?</p> <p>Many thanks in advance.</p>
6,875,324
3
0
null
2011-07-29 14:49:45.447 UTC
9
2016-10-13 20:59:47.213 UTC
2011-07-29 15:05:45.217 UTC
null
49,383
null
49,383
null
1
18
javascript|animation|css|webkit
12,402
<p><code>transitionEnd</code> is so called bubbling event that is being dispatched (bubbles up) from child to its parents. </p> <p>Options for you:</p> <ol> <li>Either analyze <code>event.target</code> property of the event object - it should contain element with ended transition.</li> <li>Or to install transitionEnd event handlers on each child element and call <code>event.stopPropagation()</code> so to prevent its bubbling.</li> </ol>
6,418,493
Bash variable expansion on tab complete
<p>I'm running Ubuntu 11.04, and I'm seeing some odd behaviour when I try to use tab-completion in bash on a path that starts with a variable. If I've got TOP=/scratch, and I try to tab-complete:</p> <p>cd $TOP/foo</p> <p>it changes to:</p> <p>cd \$TOP/foo</p> <p>I'd prefer it to complete to: cd $TOP/foobar or cd /scratch/foobar but I'd settle for it just not changing the line and requiring me to un-escape the $. </p> <p>Does anyone know where in bash/readline I should look to fix this?</p>
6,418,681
3
3
null
2011-06-20 22:55:43.983 UTC
9
2015-05-18 17:19:33.553 UTC
null
null
null
null
807,491
null
1
42
bash|readline|bash-completion
11,961
<p>Found the bug report, please register (if not already registered) and add yourself to the 'people affected' list, I just did:</p> <p><a href="https://bugs.launchpad.net/ubuntu/+source/bash/+bug/778627" rel="noreferrer">https://bugs.launchpad.net/ubuntu/+source/bash/+bug/778627</a></p> <h3>Workarounds</h3> <p>Try enabling <code>direxpand</code> or <code>cdable_vars</code>:</p> <pre><code>shopt -s direxpand # or shopt -s cdable_vars </code></pre> <p>Apparently <a href="http://www.linuxquestions.org/questions/linux-general-1/bash-auto-complete-of-environment-variables-613203/#post3023856" rel="noreferrer"><kbd>Esc</kbd><kbd>Tab</kbd> might be a workaround</a>:</p> <blockquote> <p>I haven't found a proper solution to this, but there's a workaround. The escaping of environment variables can be disabled by pressing Esc followed by tab.</p> <pre><code># cd $SO + [Esc] + [Tab] # cd $SOME_DIR </code></pre> </blockquote> <hr> <p><sub> Confirm that as a bug! I just confirmed that the same thing works on</p> <pre><code>No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 10.10 Release: 10.10 Codename: maverick </code></pre> <p>I get broken behaviour on (up-to-date) natty:</p> <pre><code>No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 11.04 Release: 11.04 Codename: natty </code></pre> <p>Although I must add that I do <em>not</em> the slash escaped, but the path (while valid, existing, accessible and readable) is not getting expanded. </sub></p> <p>Info: <a href="https://help.ubuntu.com/community/ReportingBugs" rel="noreferrer">https://help.ubuntu.com/community/ReportingBugs</a></p>
6,860,186
Log.INFO vs. Log.DEBUG
<p>I am developing a large commercial program and keep confusing myself between what kind of information i want to log with Log.INFO and Log.DEBUG.</p> <p>Are there any standards or canonical Python Enhancement Proposal / Java standard conventions / rules defined for other languages on what each type of log message contains?</p>
6,860,279
3
1
null
2011-07-28 13:59:53.03 UTC
37
2021-06-08 07:30:26.973 UTC
2021-06-08 07:30:26.973 UTC
null
508,907
null
863,553
null
1
120
logging
144,988
<p>I usually try to use it like this:</p> <ul> <li>DEBUG: Information interesting for Developers, when trying to debug a problem.</li> <li>INFO: Information interesting for Support staff trying to figure out the context of a given error</li> <li>WARN to FATAL: Problems and Errors depending on level of damage.</li> </ul>
6,981,045
How to setup the starting form of a winforms project in Visual Studio 2010
<p>Does anybody know how to setup the starting form of a winforms project in Visual Studio 2010? I have ridden to go to Project Properties and change Startup Object, but in dowpdownlist the only options available were "(None)" and "ProjectName.Program.cs". The "program.cs" is my default code file. Please help me. (Im working in C#)</p>
6,981,091
4
1
null
2011-08-08 10:51:20.663 UTC
2
2015-02-19 02:59:57.623 UTC
2011-08-08 11:37:09.84 UTC
null
22,186
null
865,312
null
1
25
c#|winforms|visual-studio
38,737
<p>In your Program.cs, there is line like:</p> <pre><code>Application.Run(new Form1()); </code></pre> <p>where you can substitute the form you'd like to start. If you change <code>Form1</code> to another Form class, your project will start with that one.</p>
23,925,907
Slidedown and slideup layout with animation
<p>how can I display a layout in the center with slideUp when I press the button, and press again to hide ... slideDown in ANDROID</p> <p>help me with that, thnkss</p>
23,926,196
6
2
null
2014-05-29 04:52:43.507 UTC
20
2021-09-07 06:55:12.543 UTC
2018-03-24 13:01:50.943 UTC
null
2,649,012
null
1,342,664
null
1
59
android|animation|slidedown|slideup
132,516
<p>Create two animation xml under res/anim folder </p> <p>slide_down.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;translate android:duration="1000" android:fromYDelta="0" android:toYDelta="100%" /&gt; &lt;/set&gt; </code></pre> <p>slide_up.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;translate android:duration="1000" android:fromYDelta="100%" android:toYDelta="0" /&gt; &lt;/set&gt; </code></pre> <p>Load animation Like bellow Code and start animation when you want According to your Requirement </p> <pre><code>//Load animation Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down); Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up); // Start animation linear_layout.startAnimation(slide_down); </code></pre>
18,250,888
Map the Exception of a failed Future
<p>What's the cleanest way to <code>map</code> the <code>Exception</code> of a failed <code>Future</code> in scala?</p> <p>Say I have:</p> <pre><code>import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global val f = Future { if(math.random &lt; 0.5) 1 else throw new Exception("Oh no") } </code></pre> <p>If the Future succeeds with <code>1</code>, I'd like to keep that, however if it fails I would like to change the <code>Exception</code> to a different <code>Exception</code>.</p> <p>The best I could come up with is transform, however that requires me to make a needless function for the success case:</p> <pre><code>val f2 = f.transform(s =&gt; s, cause =&gt; new Exception("Something went wrong", cause)) </code></pre> <p>Is there any reason there is no <code>mapFailure(PartialFunction[Throwable,Throwable])</code>?</p>
18,252,823
2
2
null
2013-08-15 10:32:08.377 UTC
7
2017-05-10 15:10:54.047 UTC
2015-12-20 21:48:50.99 UTC
null
936,869
null
936,869
null
1
38
scala|akka|future|scala-2.10
25,954
<p>There is also:</p> <pre><code>f recover { case cause =&gt; throw new Exception("Something went wrong", cause) } </code></pre> <p>Since Scala 2.12 you can do:</p> <pre><code>f transform { case s @ Success(_) =&gt; s case Failure(cause) =&gt; Failure(new Exception("Something went wrong", cause)) } </code></pre> <p>or</p> <pre><code>f transform { _.transform(Success(_), cause =&gt; Failure(new Exception("Something went wrong", cause)))} </code></pre>
15,810,404
MYSQL WHERE LIKE Statement
<p>I am attempting to use the LIKE clause in a mysql statement as follows:</p> <pre><code>SELECT * FROM batches WHERE FilePath LIKE '%Parker_Apple_Ben_20-10-1956%' </code></pre> <p>The data matched data within the 'FilePath' Column is:</p> <pre><code>C:\SCAN\Parker_Apple_Ben_20-10-1830\TEST </code></pre> <p>The above SQL statement works fine and picks up the relevent row, but if I for example add the "\" character into the end of the LIKE clause (like follows) it does not pick up the row correctly:</p> <pre><code>SELECT * FROM batches WHERE FilePath LIKE '%Parker_Apple_Ben_20-10-1956\%' </code></pre> <p>Funnily enough though if I place a '\' character at the beginning of LIKE clause (like follows) it picks up the row perfectly fine - this has me baffled. </p> <pre><code>SELECT * FROM batches WHERE FilePath LIKE '%\Parker_Apple_Ben_20-10-1956%' </code></pre>
15,810,712
6
0
null
2013-04-04 11:55:44.56 UTC
0
2013-04-04 12:15:08.593 UTC
2013-04-04 12:07:07.773 UTC
null
426,671
null
742,465
null
1
9
mysql|sql-like
50,801
<p>Within LIKE, <code>_</code> is a wildcard matching a single character and so that needs escaping to correctly match a literal '_' instead of potentially matching anything. Additionally you are mentioning trying to match a string ending in 1830 with a like ending 1956. Finally as mentioned by J W and the MySQL documentation you need to escape backslashes twice</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like</a></p> <blockquote> <p>Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings. For example, to search for “\n”, specify it as “\n”. To search for “\”, specify it as “\\”; this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.</p> </blockquote> <p>Try </p> <pre><code>SELECT * FROM batches WHERE FilePath LIKE '%Parker\_Apple\_Ben\_20-10-1830\\\\%' </code></pre> <p><a href="http://sqlfiddle.com/#!2/3ce74/3" rel="noreferrer">http://sqlfiddle.com/#!2/3ce74/3</a></p>
35,301,269
Which date class should I use in Java 8?
<p>There is a whole set of date's classes in Java 8:</p> <ul> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html" rel="noreferrer"><strong><code>java.time.LocalDateTime</code></strong></a>;</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html" rel="noreferrer"><strong><code>java.time.ZonedDateTime</code></strong></a>;</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html" rel="noreferrer"><strong><code>java.time.Instant</code></strong></a>;</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html" rel="noreferrer"><strong><code>java.time.OffsetDateTime</code></strong></a>;</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html" rel="noreferrer"><strong><code>java.sql.Timestamp</code></strong></a>;</li> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer"><strong><code>java.util.Date</code></strong></a>.</li> </ul> <p>I already passed over their JavaDocs and paid attention that all these classes contain all the methods I need. Thus, for the moment, I can select them randomly. But I guess that there is some reason why there are 6 separate classes and each of them is dedicated to the specific purpose.</p> <p>Technical information &amp; requirements:</p> <ol> <li>The input is in <code>String</code>, which is converted to one of these date formats.</li> <li>I don't need to display the time zones but when I compare two dates it's important to be capable to compare correctly the time in New York and in Paris.</li> <li>The precise level is seconds, there is no need to use milliseconds.</li> <li>The required operations: <ul> <li>find max/min date;</li> <li>sort objects by date;</li> <li>calculate date &amp; time period (difference between two dates);</li> <li>insert objects to MongoDB and retrieve them from a db by date (e.g. all objects after specific date).</li> </ul></li> </ol> <p>My questions:</p> <ol> <li>Which aspects should I bear in mind in order to choose the optimal format among these four options from the performance &amp; maintainability points of view?</li> <li>Is there any reason why I should avoid some of these date classes?</li> </ol>
35,312,599
1
10
null
2016-02-09 20:11:50.597 UTC
6
2019-02-21 16:04:19.51 UTC
2019-02-21 16:04:19.51 UTC
null
462,347
null
462,347
null
1
28
java|date|datetime|timestamp|java-8
8,846
<p>Each one of the <code>Date</code> classes are for specific purposes: </p> <ul> <li><p>If you want to use your Date in an <code>SQL</code>/<code>JDBC</code> context, use the <code>java.sql.Timestamp</code>.</p></li> <li><p><code>java.util.Date</code> is the old Java API, it is not thread safe, you can difficultly handle time zoning, and on the top of all, it is poorly designed: one simple uniformity is that months start from 1 while days start from 0.</p></li> <li><p><code>java.time.LocalDateTime</code> is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second, which you need exactly.</p></li> <li><p><code>java.time.ZonedDateTime</code> class stores all date and time fields, so you can use it to deal with values like: <code>27th January 1990 at 15:40.30.123123123 +02:00</code> in the Europe/Paris time-zone.</p></li> </ul> <p>To do your task, the <code>ZonedDateTime</code> class handles conversion from the local time-line of <code>LocalDateTime</code> to the instant time-line of <code>Instant</code>(which models a single instantaneous point on the time-line). The difference between the two time-lines, represented by a <code>ZoneOffset</code>, is the offset from UTC/Greenwich.</p> <p>To calculate duration and period: there is the <code>java.time.Duration</code> which is a time-based amount of time, such as '20.5 seconds', and <code>java.time.Period</code>, which is a date-based amount of time (like: 26 years, 2 months and 2 days).</p> <p>To get max and min dates, you can use the Java 8 lambdas in something like: </p> <pre><code>Date maxDate = list.stream().map(yourInstance -&gt; yourInstance.date).max(Date::compareTo).get(); Date minDate = list.stream().map(yourInstance -&gt; yourInstance.date).min(Date::compareTo).get(); </code></pre>
5,202,158
How to display progress dialog before starting an activity in Android?
<p>How do you display a progress dialog before starting an activity (i.e., while the activity is loading some data) in Android?</p>
5,202,186
2
1
null
2011-03-05 06:32:32.697 UTC
15
2018-10-15 20:13:56.833 UTC
2018-10-15 20:13:56.833 UTC
null
3,623,128
null
535,026
null
1
36
android|android-activity|progressdialog|android-progressbar|android-dialog
34,443
<p>You should load data in an <a href="http://developer.android.com/reference/android/os/AsyncTask.html">AsyncTask</a> and update your interface when the data finishes loading.</p> <p>You could even start a new activity in your AsyncTask's <code>onPostExecute()</code> method.</p> <p>More specifically, you will need a new class that extends AsyncTask:</p> <pre><code>public class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { public MyTask(ProgressDialog progress) { this.progress = progress; } public void onPreExecute() { progress.show(); } public void doInBackground(Void... unused) { ... do your loading here ... } public void onPostExecute(Void unused) { progress.dismiss(); } } </code></pre> <p>Then in your activity you would do:</p> <pre><code>ProgressDialog progress = new ProgressDialog(this); progress.setMessage("Loading..."); new MyTask(progress).execute(); </code></pre>
16,067
Prototyping with Python code before compiling
<p>I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p> <p>What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, <a href="http://www.swig.org/" rel="nofollow noreferrer">SWIG</a>, <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html" rel="nofollow noreferrer">Boost.Python</a>, <a href="http://cython.org/" rel="nofollow noreferrer">Cython</a> or <a href="http://www.riverbankcomputing.co.uk/software/sip/intro" rel="nofollow noreferrer">Python SIP</a>?</p> <p>For this particular use case (a fitting library), I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.</p>
1,661,276
7
0
null
2008-08-19 12:32:38.903 UTC
14
2020-09-22 10:10:12 UTC
2020-09-22 10:10:12 UTC
Brendan
2,897,989
Brendan
199
null
1
22
python|swig|ctypes|prototyping|python-sip
4,777
<p>Finally a question that I can really put a value answer to :). </p> <p>I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:</p> <p><strong>Disclaimer</strong>: This is my personal experience. I am not involved with any of these projects. </p> <p><strong>swig:</strong> does not play well with c++. It should, but name mangling problems in the linking step was a major headache for me on linux &amp; Mac OS X. If you have C code and want it interfaced to python, it is a good solution. I wrapped the GTS for my needs and needed to write basically a C shared library which I could connect to. I would not recommend it.</p> <p><strong>Ctypes:</strong> I wrote a libdc1394 (IEEE Camera library) wrapper using ctypes and it was a very straigtforward experience. You can find the code on <a href="https://launchpad.net/pydc1394" rel="noreferrer">https://launchpad.net/pydc1394</a>. It is a lot of work to convert headers to python code, but then everything works reliably. This is a good way if you want to interface an external library. Ctypes is also in the stdlib of python, so everyone can use your code right away. This is also a good way to play around with a new lib in python quickly. I can recommend it to interface to external libs. </p> <p><strong>Boost.Python</strong>: Very enjoyable. If you already have C++ code of your own that you want to use in python, go for this. It is very easy to translate c++ class structures into python class structures this way. I recommend it if you have c++ code that you need in python. </p> <p><strong>Pyrex/Cython:</strong> Use Cython, not Pyrex. Period. Cython is more advanced and more enjoyable to use. Nowadays, I do everything with cython that i used to do with SWIG or Ctypes. It is also the best way if you have python code that runs too slow. The process is absolutely fantastic: you convert your python modules into cython modules, build them and keep profiling and optimizing like it still was python (no change of tools needed). You can then apply as much (or as little) C code mixed with your python code. This is by far faster then having to rewrite whole parts of your application in C; you only rewrite the inner loop. </p> <p><strong>Timings</strong>: ctypes has the highest call overhead (~700ns), followed by boost.python (322ns), then directly by swig (290ns). Cython has the lowest call overhead (124ns) and the best feedback where it spends time on (cProfile support!). The numbers are from my box calling a trivial function that returns an integer from an interactive shell; module import overhead is therefore not timed, only function call overhead is. It is therefore easiest and most productive to get python code fast by profiling and using cython.</p> <p><strong>Summary</strong>: For your problem, use Cython ;). I hope this rundown will be useful for some people. I'll gladly answer any remaining question.</p> <hr> <p><strong>Edit</strong>: I forget to mention: for numerical purposes (that is, connection to NumPy) use Cython; they have support for it (because they basically develop cython for this purpose). So this should be another +1 for your decision. </p>
814,219
How does one target IE7 and IE8 with valid CSS?
<p>I want to target IE7 and IE8 with W3C-compliant CSS. Sometimes fixing CSS for one version does not fix for the other. How can I achieve this?</p>
4,349,295
7
1
null
2009-05-02 05:38:24.783 UTC
59
2020-07-09 22:49:37.62 UTC
2012-11-28 23:28:47.117 UTC
null
652,722
null
88,493
null
1
65
css|internet-explorer|internet-explorer-8|web-standards
139,553
<p><strong>Explicitly Target IE versions without hacks using HTML and CSS</strong></p> <p>Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <code>&lt;html&gt;</code> element so you can select based on browser later.</p> <p>Example</p> <pre><code>&lt;!doctype html&gt; &lt;!--[if IE]&gt;&lt;![endif]--&gt; &lt;!--[if lt IE 7 ]&gt; &lt;html lang="en" class="ie6"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7 ]&gt; &lt;html lang="en" class="ie7"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8 ]&gt; &lt;html lang="en" class="ie8"&gt; &lt;![endif]--&gt; &lt;!--[if IE 9 ]&gt; &lt;html lang="en" class="ie9"&gt; &lt;![endif]--&gt; &lt;!--[if (gt IE 9)|!(IE)]&gt;&lt;!--&gt;&lt;html lang="en"&gt;&lt;!--&lt;![endif]--&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>Then in your CSS you can very strictly access your target browser.</p> <p>Example</p> <pre><code>.ie6 body { border:1px solid red; } .ie7 body { border:1px solid blue; } </code></pre> <p>For more information check out <a href="http://html5boilerplate.com/" rel="noreferrer">http://html5boilerplate.com/</a> </p> <p><strong>Target IE versions with CSS "Hacks"</strong> </p> <p>More to your point, here are the hacks that let you target IE versions.</p> <p>Use "\9" to target IE8 and below.<br> Use "*" to target IE7 and below.<br> Use "_" to target IE6.</p> <p>Example:</p> <pre><code>body { border:1px solid red; /* standard */ border:1px solid blue\9; /* IE8 and below */ *border:1px solid orange; /* IE7 and below */ _border:1px solid blue; /* IE6 */ } </code></pre> <p><strong>Update: Target IE10</strong></p> <p>IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <code>&lt;html&gt;</code> element</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;!--[if !IE]&gt;&lt;!--&gt;&lt;script&gt;if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}&lt;/script&gt;&lt;!--&lt;![endif]--&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt; </code></pre>
685,015
What is the best Twitter API wrapper/library for .NET?
<p>I'm looking for a way to programatically generate a twitter feed for a .NET application. Any recommendations as to a good wrapper for the twitter api to ease the work?</p> <p>Boaz</p>
1,121,499
8
0
null
2009-03-26 09:12:46.213 UTC
32
2021-01-10 06:12:32.547 UTC
null
null
null
Boaz
2,892
null
1
53
.net|api|twitter
37,950
<p><a href="https://www.nuget.org/packages/TweetSharp/" rel="nofollow noreferrer">TweetSharp</a> looks like it should be a decent option as well.</p>
1,026,973
What's the difference between the various methods to get an Android Context?
<p>In various bits of Android code I've seen:</p> <pre><code> public class MyActivity extends Activity { public void method() { mContext = this; // since Activity extends Context mContext = getApplicationContext(); mContext = getBaseContext(); } } </code></pre> <p>However I can't find any decent explanation of which is preferable, and under what circumstances which should be used.</p> <p>Pointers to documentation on this, and guidance about what might break if the wrong one is chosen, would be much appreciated.</p>
1,027,438
8
1
null
2009-06-22 12:38:14.683 UTC
194
2021-10-12 09:55:08.733 UTC
2021-10-12 09:55:08.733 UTC
null
6,782
null
6,782
null
1
403
android|android-context
94,053
<p>I agree that documentation is sparse when it comes to Contexts in Android, but you can piece together a few facts from various sources.</p> <p><a href="http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html" rel="noreferrer">This blog post</a> on the official Google Android developers blog was written mostly to help address memory leaks, but provides some good information about contexts as well:</p> <blockquote> <p>In a regular Android application, you usually have two kinds of Context, Activity and Application.</p> </blockquote> <p>Reading the article a little bit further tells about the difference between the two and when you might want to consider using the application Context (<code>Activity.getApplicationContext()</code>) rather than using the Activity context <code>this</code>). Basically the Application context is associated with the Application and will always be the same throughout the life cycle of your app, where as the Activity context is associated with the activity and could possibly be destroyed many times as the activity is destroyed during screen orientation changes and such.</p> <p>I couldn't find really anything about when to use getBaseContext() other than a post from Dianne Hackborn, one of the Google engineers working on the Android SDK:</p> <blockquote> <p>Don't use getBaseContext(), just use the Context you have.</p> </blockquote> <p>That was from a post on the <a href="http://groups.google.com/group/android-developers/browse_thread/thread/dbe5f18d3dba9aa9/fa4b981f635f16db?lnk=gst&amp;q=getbaseContext#fa4b981f635f16db" rel="noreferrer">android-developers newsgroup</a>, you may want to consider asking your question there as well, because a handful of the people working on Android actual monitor that newsgroup and answer questions.</p> <p>So overall it seems preferable to use the global application context when possible.</p>
457,316
Combining two expressions (Expression<Func<T, bool>>)
<p>I have two expressions of type <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code> and I want to take to OR, AND or NOT of these and get a new expression of the same type</p> <pre><code>Expression&lt;Func&lt;T, bool&gt;&gt; expr1; Expression&lt;Func&lt;T, bool&gt;&gt; expr2; ... //how to do this (the code below will obviously not work) Expression&lt;Func&lt;T, bool&gt;&gt; andExpression = expr AND expr2 </code></pre>
457,328
9
0
null
2009-01-19 11:29:08.45 UTC
101
2022-09-14 13:45:52.95 UTC
2009-06-27 01:04:57.743 UTC
null
62,653
BjartN
56,648
null
1
305
c#|linq|lambda|expression
134,904
<p>Well, you can use <code>Expression.AndAlso</code> / <code>OrElse</code> etc to combine logical expressions, but the problem is the parameters; are you working with the same <code>ParameterExpression</code> in expr1 and expr2? If so, it is easier:</p> <pre><code>var body = Expression.AndAlso(expr1.Body, expr2.Body); var lambda = Expression.Lambda&lt;Func&lt;T,bool&gt;&gt;(body, expr1.Parameters[0]); </code></pre> <p>This also works well to negate a single operation:</p> <pre><code>static Expression&lt;Func&lt;T, bool&gt;&gt; Not&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; expr) { return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;( Expression.Not(expr.Body), expr.Parameters[0]); } </code></pre> <p>Otherwise, depending on the LINQ provider, you might be able to combine them with <code>Invoke</code>:</p> <pre><code>// OrElse is very similar... static Expression&lt;Func&lt;T, bool&gt;&gt; AndAlso&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; left, Expression&lt;Func&lt;T, bool&gt;&gt; right) { var param = Expression.Parameter(typeof(T), "x"); var body = Expression.AndAlso( Expression.Invoke(left, param), Expression.Invoke(right, param) ); var lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(body, param); return lambda; } </code></pre> <p>Somewhere, I have got some code that re-writes an expression-tree replacing nodes to remove the need for <code>Invoke</code>, but it is quite lengthy (and I can't remember where I left it...)</p> <hr> <p>Generalized version that picks the simplest route:</p> <pre><code>static Expression&lt;Func&lt;T, bool&gt;&gt; AndAlso&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; expr1, Expression&lt;Func&lt;T, bool&gt;&gt; expr2) { // need to detect whether they use the same // parameter instance; if not, they need fixing ParameterExpression param = expr1.Parameters[0]; if (ReferenceEquals(param, expr2.Parameters[0])) { // simple version return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;( Expression.AndAlso(expr1.Body, expr2.Body), param); } // otherwise, keep expr1 "as is" and invoke expr2 return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;( Expression.AndAlso( expr1.Body, Expression.Invoke(expr2, param)), param); } </code></pre> <p>Starting from .NET 4.0, there is the <code>ExpressionVisitor</code> class which allows you to build expressions that are EF safe.</p> <pre><code> public static Expression&lt;Func&lt;T, bool&gt;&gt; AndAlso&lt;T&gt;( this Expression&lt;Func&lt;T, bool&gt;&gt; expr1, Expression&lt;Func&lt;T, bool&gt;&gt; expr2) { var parameter = Expression.Parameter(typeof (T)); var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[0], parameter); var left = leftVisitor.Visit(expr1.Body); var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[0], parameter); var right = rightVisitor.Visit(expr2.Body); return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;( Expression.AndAlso(left, right), parameter); } private class ReplaceExpressionVisitor : ExpressionVisitor { private readonly Expression _oldValue; private readonly Expression _newValue; public ReplaceExpressionVisitor(Expression oldValue, Expression newValue) { _oldValue = oldValue; _newValue = newValue; } public override Expression Visit(Expression node) { if (node == _oldValue) return _newValue; return base.Visit(node); } } </code></pre>
198,409
How do you test running time of VBA code?
<p>Is there code in VBA I can wrap a function with that will let me know the time it took to run, so that I can compare the different running times of functions?</p>
198,702
9
0
null
2008-10-13 17:49:02.24 UTC
47
2022-04-08 15:24:57.387 UTC
2008-10-13 17:55:50.993 UTC
Lance Roberts
13,295
Lance Roberts
13,295
null
1
100
optimization|testing|vba|profiling|performance
148,198
<p>Unless your functions are very slow, you're going to need a very high-resolution timer. The most accurate one I know is <code>QueryPerformanceCounter</code>. Google it for more info. Try pushing the following into a class, call it <code>CTimer</code> say, then you can make an instance somewhere global and just call <code>.StartCounter</code> and <code>.TimeElapsed</code></p> <pre><code>Option Explicit Private Type LARGE_INTEGER lowpart As Long highpart As Long End Type Private Declare Function QueryPerformanceCounter Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long Private Declare Function QueryPerformanceFrequency Lib "kernel32" (lpFrequency As LARGE_INTEGER) As Long Private m_CounterStart As LARGE_INTEGER Private m_CounterEnd As LARGE_INTEGER Private m_crFrequency As Double Private Const TWO_32 = 4294967296# ' = 256# * 256# * 256# * 256# Private Function LI2Double(LI As LARGE_INTEGER) As Double Dim Low As Double Low = LI.lowpart If Low &lt; 0 Then Low = Low + TWO_32 End If LI2Double = LI.highpart * TWO_32 + Low End Function Private Sub Class_Initialize() Dim PerfFrequency As LARGE_INTEGER QueryPerformanceFrequency PerfFrequency m_crFrequency = LI2Double(PerfFrequency) End Sub Public Sub StartCounter() QueryPerformanceCounter m_CounterStart End Sub Property Get TimeElapsed() As Double Dim crStart As Double Dim crStop As Double QueryPerformanceCounter m_CounterEnd crStart = LI2Double(m_CounterStart) crStop = LI2Double(m_CounterEnd) TimeElapsed = 1000# * (crStop - crStart) / m_crFrequency End Property </code></pre>
125,367
Dynamic type languages versus static type languages
<p>What are the advantages and limitations of dynamic type languages compared to static type languages?</p> <p><strong>See also</strong>: <a href="https://stackoverflow.com/questions/42934/whats-with-the-love-of-dynamic-languages">whats with the love of dynamic languages</a> (a far more argumentative thread...)</p>
125,379
9
7
null
2008-09-24 04:05:00.947 UTC
133
2020-08-26 22:33:10 UTC
2017-05-23 12:18:22.093 UTC
Rob Cooper
-1
cvs
11,034
null
1
207
programming-languages|dynamic-languages|type-systems
128,629
<p>The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).</p> <p>A good take on the issue is from <a href="http://www.ics.uci.edu/~lopes/teaching/inf212W12/readings/rdl04meijer.pdf" rel="noreferrer">Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages</a> by Erik Meijer and Peter Drayton at Microsoft:</p> <blockquote> <p>Advocates of static typing argue that the advantages of static typing include earlier detection of programming mistakes (e.g. preventing adding an integer to a boolean), better documentation in the form of type signatures (e.g. incorporating number and types of arguments when resolving names), more opportunities for compiler optimizations (e.g. replacing virtual calls by direct calls when the exact type of the receiver is known statically), increased runtime efficiency (e.g. not all values need to carry a dynamic type), and a better design time developer experience (e.g. knowing the type of the receiver, the IDE can present a drop-down menu of all applicable members). Static typing fanatics try to make us believe that “well-typed programs cannot go wrong”. While this certainly sounds impressive, it is a rather vacuous statement. Static type checking is a compile-time abstraction of the runtime behavior of your program, and hence it is necessarily only partially sound and incomplete. This means that programs can still go wrong because of properties that are not tracked by the type-checker, and that there are programs that while they cannot go wrong cannot be type-checked. The impulse for making static typing less partial and more complete causes type systems to become overly complicated and exotic as witnessed by concepts such as “phantom types” [11] and “wobbly types” [10]. This is like trying to run a marathon with a ball and chain tied to your leg and triumphantly shouting that you nearly made it even though you bailed out after the first mile.</p> <p>Advocates of dynamically typed languages argue that static typing is too rigid, and that the softness of dynamically languages makes them ideally suited for prototyping systems with changing or unknown requirements, or that interact with other systems that change unpredictably (data and application integration). Of course, dynamically typed languages are indispensable for dealing with truly dynamic program behavior such as method interception, dynamic loading, mobile code, runtime reflection, etc. In the mother of all papers on scripting [16], John Ousterhout argues that statically typed systems programming languages make code less reusable, more verbose, not more safe, and less expressive than dynamically typed scripting languages. This argument is parroted literally by many proponents of dynamically typed scripting languages. We argue that this is a fallacy and falls into the same category as arguing that the essence of declarative programming is eliminating assignment. Or as John Hughes says [8], it is a logical impossibility to make a language more powerful by omitting features. Defending the fact that delaying all type-checking to runtime is a good thing, is playing ostrich tactics with the fact that errors should be caught as early in the development process as possible.</p> </blockquote>
389,827
Namespaces in C
<p>Is there a way to (ab)use the <strong>C</strong> preprocessor to emulate namespaces in <strong>C</strong>?</p> <p>I'm thinking something along these lines:</p> <pre><code>#define NAMESPACE name_of_ns some_function() { some_other_function(); } </code></pre> <p>This would get translated to:</p> <pre><code>name_of_ns_some_function() { name_of_ns_some_other_function(); } </code></pre>
390,155
10
0
null
2008-12-23 19:27:28.637 UTC
59
2020-06-02 22:19:04.73 UTC
2016-02-03 15:30:59.13 UTC
null
4,370,109
Kim
46,450
null
1
61
c++|c|namespaces|c-preprocessor
59,360
<p>When using namespace prefixes, I normally add macros for the shortened names which can be activated via <code>#define NAMESPACE_SHORT_NAMES</code> before inclusion of the header. A header foobar.h might look like this:</p> <pre><code>// inclusion guard #ifndef FOOBAR_H_ #define FOOBAR_H_ // long names void foobar_some_func(int); void foobar_other_func(); // short names #ifdef FOOBAR_SHORT_NAMES #define some_func(...) foobar_some_func(__VA_ARGS__) #define other_func(...) foobar_other_func(__VA_ARGS__) #endif #endif </code></pre> <p>If I want to use short names in an including file, I'll do</p> <pre><code>#define FOOBAR_SHORT_NAMES #include "foobar.h" </code></pre> <p>I find this a cleaner and more useful solution than using namespace macros as described by Vinko Vrsalovic (in the comments).</p>
138,670
How unique is the php session id
<p>How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?</p>
138,861
10
0
null
2008-09-26 10:41:50.883 UTC
27
2021-05-13 16:38:41.847 UTC
2013-07-03 12:48:58.557 UTC
user2541941
null
Jalov
22,629
null
1
92
php|session|guid
76,517
<p>Session_id can indeed be duplicated, but the probability is very low. If you have a website with a fair traffic, it may happens once in you web site life, and will just annoy one user for one session.</p> <p>This is not worth to care about unless you expect to build a very high traffic website or a service for the bank industry.</p>
2,041
How do I create a branch?
<p>How do I create a branch in SVN?</p>
2,310
10
0
null
2008-08-05 09:25:29 UTC
123
2020-03-27 05:54:59.327 UTC
2019-05-24 21:18:36.8 UTC
ChanChan
3,345,644
null
269
null
1
656
svn|version-control|branch|branching-and-merging
669,173
<p>Branching in Subversion is facilitated by a very very light and efficient copying facility.</p> <p>Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the <code>svn copy</code> command.</p> <p>Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style.</p> <p>Common styles are to have a bunch of folders at the top of your repository called <code>tags</code>, <code>branches</code>, <code>trunk</code>, etc. - that allows you to copy your whole <code>trunk</code> (or sub-sets) into the <code>tags</code> and/or <code>branches</code> folders. If you have more than one project you might want to replicate this kind of structure under each project:</p> <p>It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete.</p>
662,421
"No X11 DISPLAY variable" - what does it mean?
<p>I am trying to install a Java application on my Linux machine (Slackware). </p> <p>I have received the following error, and I do not understand it. </p> <p>Could you advise me how to approach the problem? Thank you.</p> <p>Here is what I get: (I see that some <strong>X11 DISPLAY</strong> variable needs to be set, but what value should I give it and how?)</p> <pre><code>~$ java -jar gate-5.0-beta1-build3048-installer.jar - ERROR - java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. java.awt.HeadlessException: No X11 DISPLAY variable was set, but this program performed an operation which requires it. at java.awt.GraphicsEnvironment.checkHeadless(Graphic sEnvironment.java:159) at java.awt.Window.&lt;init&gt;(Window.java:407) at java.awt.Frame.&lt;init&gt;(Frame.java:402) at net.sourceforge.mlf.metouia.borders.MetouiaDotsBuf fer.&lt;init&gt;(MetouiaDotsBuffer.java:105) at net.sourceforge.mlf.metouia.borders.MetouiaDots.&lt;i nit&gt;(MetouiaDots.java:66) at net.sourceforge.mlf.metouia.borders.MetouiaToolBar Border.&lt;init&gt;(MetouiaToolBarBorder.java:49) at net.sourceforge.mlf.metouia.MetouiaLookAndFeel.ini tComponentDefaults(MetouiaLookAndFeel.java:241) at javax.swing.plaf.basic.BasicLookAndFeel.getDefault s(BasicLookAndFeel.java:130) at javax.swing.plaf.metal.MetalLookAndFeel.getDefault s(MetalLookAndFeel.java:1591) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:537) at javax.swing.UIManager.setLookAndFeel(UIManager.jav a:581) at com.izforge.izpack.installer.GUIInstaller.loadLook AndFeel(GUIInstaller.java:373) at com.izforge.izpack.installer.GUIInstaller.&lt;init&gt;(G UIInstaller.java:116) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Construc tor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:30 at com.izforge.izpack.installer.Installer.main(Instal ler.java:62) </code></pre>
662,429
11
2
null
2009-03-19 14:28:50.733 UTC
24
2022-06-27 09:10:49.843 UTC
2018-04-23 20:40:14.743 UTC
null
5,321,363
null
42,155
null
1
117
java|linux|variables|x11|headless
589,924
<p>If you're on the main display, then</p> <pre><code>export DISPLAY=:0.0 </code></pre> <p>or if you're using csh or tcsh</p> <pre><code>setenv DISPLAY :0.0 </code></pre> <p>before running your app.</p> <p>Actually, I'm surprised it isn't set automatically. Are you trying to start this application from a non-graphic terminal? If not, have you modified the default .profile, .login, .bashrc or .cshrc?</p> <p>Note that setting the DISPLAY to :0.0 pre-supposes that you're sitting at the main display, as I said, or at least that the main display is logged on to your user id. If it's not logged on, or it's a different userid, this will fail. </p> <p>If you're coming in from another machine, and you're at the main display of that machine and it's running X, then you can use "ssh -X hostname" to connect to that host, and ssh will forward the X display back. ssh will also make sure that the DISPLAY environment variable is set correctly (providing it isn't being messed with in the various dot files I mentioned above). In a "ssh -X" session, the DISPLAY environment variable will have a value like "localhost:11.0", which will point to the socket that ssh is tunnelling to your local box.</p>
250,394
Does anyone know of any C/C++/C# code libraries that do audio synthesizer emulation?
<p>I'm trying to write a software synthesizer that recreates the sounds made by classic synthesizers like the Moog and the DX7. Does anyone know of any code resources for something like this? Thanks.</p>
250,701
12
0
null
2008-10-30 14:41:07.783 UTC
21
2016-09-30 11:32:18.77 UTC
null
null
null
MusiGenesis
14,606
null
1
19
c#|c++|c|audio|synthesizer
13,378
<p>There are an awful lot of C/C++ libraries out there, most no longer updated. There's not much for C#, but I have seen a couple. I haven't really used any of them in anger, so I can't give any recommendations.</p> <p>I would start with <a href="http://www.harmony-central.com/Computer/Programming/" rel="noreferrer">Harmony Central</a> and see if you find anything of use there.</p> <p>Alternatively, a search for <a href="http://www.google.co.uk/search?hl=en&amp;q=analog+synthesis+site%3Asourceforge.net&amp;meta=" rel="noreferrer">analog synthesis</a> on sourceforge.net has plenty of results.</p>
455,037
Convert tabs to spaces in Notepad++
<p>How do I convert tabs to spaces in Notepad++? </p> <p>I found <a href="http://www.texteditors.info/notepad-replacements-compared.php" rel="noreferrer">a webpage</a> that suggests it's possible, but I couldn't find any information about how to do it. </p> <p>I would like to be able to do that, because some web forms don't respect code with tabs in them.</p>
7,471,232
12
0
null
2009-01-18 12:10:16.063 UTC
203
2017-12-30 11:21:48.087 UTC
2017-12-30 11:21:48.087 UTC
null
4,284,627
Helephant
13,028
null
1
1,227
notepad++|whitespace|indentation
892,880
<p>To convert existing tabs to spaces, press <code>Edit-&gt;Blank Operations-&gt;TAB to Space</code>.</p> <p>If in the future you want to enter spaces instead of tab when you press tab key:</p> <ol> <li>Go to <code>Settings-&gt;Preferences...-&gt;Language</code> (since version 7.1) or <code>Settings-&gt;Preferences...-&gt;Tab Settings</code> (previous versions)</li> <li>Check <code>Replace by space</code></li> <li>(<em>Optional</em>) You can set the number of spaces to use in place of a Tab by changing the <code>Tab size</code> field.</li> </ol> <p><a href="https://i.stack.imgur.com/cDrHP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cDrHP.png" alt="Screenshot of Replace by space"></a></p>
503,743
How do I remove a folder from source control with TortoiseSVN?
<p>How do I remove a folder from being source controlled with <a href="http://en.wikipedia.org/wiki/TortoiseSVN" rel="noreferrer">TortoiseSVN</a>?</p>
3,415,184
13
5
null
2009-02-02 16:07:00.8 UTC
29
2017-08-30 14:09:49.497 UTC
2014-06-30 09:34:10.193 UTC
null
761,095
Chance
48,266
null
1
133
svn|version-control|tortoisesvn
103,829
<p>There is a dedicated item in the extended context menu:</p> <ul> <li>Hold the <kbd>Shift</kbd> key down and right click on the folder.</li> <li>Under the TortoiseSVN menu click on "Delete (keep local)"</li> </ul> <p><img src="https://i.stack.imgur.com/yDETm.png" alt="enter image description here"></p> <p>Image cropped from <a href="http://tortoisesvn.net/extendedcontextmenu.html" rel="noreferrer">TortoiseSVN's extended context menu</a> page.<br> <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html#tsvn-dug-rename-delete" rel="noreferrer">Delete (keep local)</a> documentation blurb. </p>
1,109,356
WWW or not WWW, what to choose as primary site name?
<p>From technical perspective the only issue is traffic and incoming links (one of them should redirect to another). </p> <p>Now I need to choose which one should be primary. Some sites have www (google, microsoft, ruby-lang) and some without www (stackoverflow, github). Seems to me the newer do not use WWW.</p> <p>What to choose?</p> <p>Please with some explanations.</p> <p>UPDATE: This is programming related question. Actually site is for programmers, so I expect to see what techy people think.</p> <p>UPDATE: Site without WWW is clear winner. Thank you guys!</p>
1,109,362
14
4
null
2009-07-10 12:55:09.54 UTC
34
2013-04-22 06:42:28.607 UTC
2009-07-10 13:19:20.207 UTC
null
38,975
null
38,975
null
1
88
domain-name
24,316
<p>It doesn't matter which you choose but you should pick one and be consistent. It is more a matter of style but it is important to note that search engines consider these two URLs to be different sites:</p> <blockquote> <p><code>http://www.example.com</code><br> <code>http://example.com</code></p> </blockquote> <p>So whichever you choose for aesthetic reasons should be consistently used for SEO reasons.</p> <p><strong>Edit:</strong> My personal opinion is to forgo the <code>www</code> as it feels archaic to me. I also like shorter URLs. If it were up to me I would redirect all traffic from <code>www.example.com</code> to <code>example.com</code>.</p>
320,929
Currency formatting in Python
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
320,951
15
2
null
2008-11-26 14:43:33.123 UTC
40
2022-08-29 16:02:01.72 UTC
2016-09-27 16:28:59.143 UTC
null
2,301,450
Eef
30,786
null
1
195
python|formatting|currency
243,898
<p>See the <a href="https://docs.python.org/3/library/locale.html" rel="noreferrer">locale</a> module.</p> <p>This does currency (and date) formatting.</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale( locale.LC_ALL, '' ) 'English_United States.1252' &gt;&gt;&gt; locale.currency( 188518982.18 ) '$188518982.18' &gt;&gt;&gt; locale.currency( 188518982.18, grouping=True ) '$188,518,982.18' </code></pre>
7,913
How do I make Subversion (SVN) send email on checkins?
<p>I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit?</p> <p>I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though.</p>
7,924
16
0
null
2008-08-11 16:27:55.703 UTC
15
2016-09-17 15:35:48.633 UTC
2016-09-17 15:33:10.143 UTC
null
63,550
null
1,031
null
1
52
svn|hook|post-commit|post-commit-hook
77,598
<p>You use the <a href="http://svnbook.red-bean.com/en/1.7/svn.reposadmin.create.html#svn.reposadmin.create.hooks" rel="noreferrer">post-commit hooks</a>. Here's a <a href="http://builddeploy.blogspot.com/2008/01/implementing-subversion-post-commit.html" rel="noreferrer">guide</a>.</p> <p>Here's a sample Ruby script that sends an email after each commit: <a href="http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/commit-email.rb" rel="noreferrer">commit-email.rb</a></p>
610,839
How can I programmatically create a new cron job?
<p>I want to be able to programatically add a new cron job, what is the best way to do this?</p> <p>From <a href="http://drupal.org/node/175106" rel="noreferrer">my research</a>, it seems I could dump the current crontab and then append a new one, piping that back into crontab:</p> <pre><code>(crontab -l ; echo "0 * * * * wget -O - -q http://www.example.com/cron.php") | crontab - </code></pre> <p>Is there a better way?</p>
610,860
19
5
null
2009-03-04 14:34:08.373 UTC
47
2020-12-05 21:08:39.79 UTC
null
null
null
DavidM
2,183
null
1
150
linux|unix|cron
83,023
<p>The best way if you're running as root, is to drop a file into /etc/cron.d</p> <p>if you use a package manager to package your software, you can simply lay down files in that directory and they are interpreted as if they were crontabs, but with an extra field for the username, e.g.:</p> <p>Filename: <code>/etc/cron.d/per_minute</code></p> <p>Content: <code>* * * * * root /bin/sh /home/root/script.sh</code></p>
421,860
Capture characters from standard input without waiting for enter to be pressed
<p>I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).</p> <p>Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.</p>
421,871
21
2
null
2009-01-07 20:04:16.75 UTC
109
2022-04-15 21:58:48.367 UTC
2014-09-20 07:44:41.903 UTC
null
608,639
Adam
1,366
null
1
224
c++|c|inputstream
265,342
<p>That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with <code>stdin</code> (they are usually line buffered). You can, however use a library for that:</p> <ol> <li><p>conio available with Windows compilers. Use the <code>_getch()</code> function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <code>&lt;conio.h&gt;</code> and use it. See <a href="http://en.wikipedia.org/wiki/Conio.h" rel="noreferrer"><code>conio.h</code></a> at Wikipedia. It lists <code>getch()</code>, which is declared deprecated in Visual C++. </p></li> <li><p>curses available for Linux. Compatible curses implementations are available for Windows too. It has also a <code>getch()</code> function. (try <code>man getch</code> to view its manpage). See <a href="http://en.wikipedia.org/wiki/Curses_%28programming_library%29" rel="noreferrer">Curses</a> at Wikipedia. </p></li> </ol> <p>I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into <code>man stty</code>). Curses would handle that for you in a portable manner, if I'm not mistaken. </p>
340,888
Navigation in django
<p>I've just done my first little webapp in django and I love it. I'm about to start on converting an old production PHP site into django and as part its template, there is a navigation bar.</p> <p>In PHP, I check each nav option's URL against the current URL, in the template code and apply a CSS class if they line up. It's horrendously messy.</p> <p>Is there something better for django or a good way of handling the code in the template?</p> <p>To start, how would I go about getting the current URL?</p>
341,748
30
3
null
2008-12-04 15:06:42.53 UTC
79
2020-11-22 21:51:40.563 UTC
2009-01-29 17:32:33.797 UTC
null
12,870
Oli
12,870
null
1
115
django|navigation
101,656
<p>I use template inheritance to customize navigation. For example:</p> <p>base.html</p> <pre><code>&lt;html&gt; &lt;head&gt;...&lt;/head&gt; &lt;body&gt; ... {% block nav %} &lt;ul id=&quot;nav&quot;&gt; &lt;li&gt;{% block nav-home %}&lt;a href=&quot;{% url 'home' %}&quot;&gt;Home&lt;/a&gt;{% endblock %}&lt;/li&gt; &lt;li&gt;{% block nav-about %}&lt;a href=&quot;{% url 'about' %}&quot;&gt;About&lt;/a&gt;{% endblock %}&lt;/li&gt; &lt;li&gt;{% block nav-contact %}&lt;a href=&quot;{% url 'contact' %}&quot;&gt;Contact&lt;/a&gt;{% endblock %}&lt;/li&gt; &lt;/ul&gt; {% endblock %} ... &lt;/body&gt; &lt;/html&gt; </code></pre> <p>about.html</p> <pre><code>{% extends &quot;base.html&quot; %} {% block nav-about %}&lt;strong class=&quot;nav-active&quot;&gt;About&lt;/strong&gt;{% endblock %} </code></pre>
918,886
How do I split a string on a delimiter in Bash?
<p>I have this string stored in a variable:</p> <pre><code>IN="[email protected];[email protected]" </code></pre> <p>Now I would like to split the strings by <code>;</code> delimiter so that I have:</p> <pre><code>ADDR1="[email protected]" ADDR2="[email protected]" </code></pre> <p>I don't necessarily need the <code>ADDR1</code> and <code>ADDR2</code> variables. If they are elements of an array that's even better.</p> <hr> <p>After suggestions from the answers below, I ended up with the following which is what I was after:</p> <pre><code>#!/usr/bin/env bash IN="[email protected];[email protected]" mails=$(echo $IN | tr ";" "\n") for addr in $mails do echo "&gt; [$addr]" done </code></pre> <p>Output:</p> <pre><code>&gt; [[email protected]] &gt; [[email protected]] </code></pre> <p>There was a solution involving setting <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">Internal_field_separator</a> (IFS) to <code>;</code>. I am not sure what happened with that answer, how do you reset <code>IFS</code> back to default?</p> <p>RE: <code>IFS</code> solution, I tried this and it works, I keep the old <code>IFS</code> and then restore it:</p> <pre><code>IN="[email protected];[email protected]" OIFS=$IFS IFS=';' mails2=$IN for x in $mails2 do echo "&gt; [$x]" done IFS=$OIFS </code></pre> <p>BTW, when I tried </p> <pre><code>mails2=($IN) </code></pre> <p>I only got the first string when printing it in loop, without brackets around <code>$IN</code> it works.</p>
918,931
34
9
null
2009-05-28 02:03:43.983 UTC
712
2022-08-15 07:14:28.127 UTC
2018-10-22 21:20:54.567 UTC
null
6,862,601
null
45,654
null
1
2,632
bash|shell|split|scripting
3,045,558
<p>You can set the <a href="http://en.wikipedia.org/wiki/Internal_field_separator" rel="noreferrer">internal field separator</a> (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to <code>IFS</code> only takes place to that single command's environment (to <code>read</code> ). It then parses the input according to the <code>IFS</code> variable value into an array, which we can then iterate over.</p> <p>This example will parse one line of items separated by <code>;</code>, pushing it into an array:</p> <pre><code>IFS=';' read -ra ADDR &lt;&lt;&lt; &quot;$IN&quot; for i in &quot;${ADDR[@]}&quot;; do # process &quot;$i&quot; done </code></pre> <p>This other example is for processing the whole content of <code>$IN</code>, each time one line of input separated by <code>;</code>:</p> <pre><code>while IFS=';' read -ra ADDR; do for i in &quot;${ADDR[@]}&quot;; do # process &quot;$i&quot; done done &lt;&lt;&lt; &quot;$IN&quot; </code></pre>