Is there any strategy for the Fidgeting Writer storyline?

Question: Using a Tale of Terror you can start an object-based storyline: at every step, you trade one object for the next one, risking a failure and go back to start, or yield and get a reward.
The chances of success at every step seem to be ~60-70%, so since the steps are many, there aren't really many chances to complete all the storyline – I'm not sure how many steps there are, I'm currently at Deal with a Devil.
So, my question is: am I missing something and there is some way to increase the odds, or the only way to do that is to try again and again until you are lucky enough to get all successes till the end?
Answer: The chances of success decrease the further you get into the storyline; the further you go, the more failures you'll get. Each individual action is purely luck-based, and there is nothing you can do to improve it.
On a side note, if you're only in the Fidgeting Writer for profit (i.e., you have an unholy number of Tales of Terror, Brilliant Souls, etc., and you want Echoes), the best Echoes-per-action rate comes when you go all the way to the end of the chain. Several people have spent an inordinate amount of time and sanity on this storyline. Here's the data: https://docs.google.com/spreadsheet/pub?key=0AlbwjlynOB13dDQtelhZdm9LQlpJQ1JXa0FnMlFPamc&single=true&gid=6&output=html
Comment: There are seven steps in the chain; if we assume 50% success rate (it's a little better than that, of course), then it'll take an average of 128 iterations to get to the end. Here's the discussion thread on the math, for money-obsessed characters: http://community.failbettergames.com/topic376-the-fidgeting-writer--doing-the-maths-spoilers.aspx
Comment: I was on it just for the story, actually, but now I realise the odd of making it to the end might be incredibly small – though I'll have to calculate them, maybe.
Answer: Latter, it seems. It's a purely luck-based storyline.


EB CLI only works as sudo; else gives 'DistributionNotFound'

Question: When I run eb --version it errors out with a DistributionNotFound.
(my-venv) MBP-2:folder username$ eb --version

The traceback is:
    Traceback (most recent call last):
      File "/usr/local/bin/eb", line 5, in <module>
        from pkg_resources import load_entry_point
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 2697, in <module>
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 669, in require
      File "build/bdist.macosx-10.9-intel/egg/pkg_resources.py", line 572, in resolve
    pkg_resources.DistributionNotFound: docker-py>=1.1.0,<1.2

Looking at this question, I tried the following, to no avail:

updated awsebcli: pip3 install awsebcli --upgrade
updated setuptools: pip3 install setuptools --upgrade
updated docker-py: pip3 install docker-py --upgrade

The problem still persists. But when I use sudo, it works correctly:
(my-venv) MBP-2:folder username$ sudo eb --version
EB CLI 3.15.2 (Python 3.6.1)

I think this was caused by a time-consuming homebrew auto-update. How do I fix this?
Edit:
These are my python versions in my virtual env.
(my-venv) MBP-2:folder username$ which python
/Users/username/my-venv/bin/python

(my-venv) MBP-2:folder username$ head -1 $(which eb)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ head -1 $(which pip)
#!/Users/username/my-venv/bin/python3

(my-venv) MBP-2:folder username$ python --version
Python 3.6.1

(my-venv) MBP-2:folder username$ python3 --version
Python 3.6.1

Comment: what's the output of `python --version` and `sudo python --version`?
Comment: both "Python 3.6.1"
Comment: related: https://stackoverflow.com/q/42598399
Answer: So far as I can tell, ebcli does not have a dependency on docker-py, but rather just the docker package. So this suggests to me that there may be some wires getting crossed in which packages are being installed.
What I'd recommend trying is recreating this virtualenv and only installing ebcli without the other packages. That may sort out the errors that you're seeing.


java not running in any browser

Question: I have two versions of Java installed on my computer:

I have allowed java to run in the browser:

Java is running in command line:

This is the error I get:

I have also enabled scripting in the browser settings. I have restarted the computer and I have also tried uninstalling all Java and reinstalling it. I am not sure what else I can do?
Comment: http://superuser.com/q/748306/169038
Comment: @SurajRao:  Almost all modern browsers disable Java in the web plugin.
Comment: oh ok thanks for the info
Comment: @Makoto My coworker has the same browser and same java versions and it works for them.
Comment: Which browser are you using to run the 'uninstall' applet? What version of that browser? Certain browsers like Chrome or Edge don't even support Java applets.
Answer: Could you check the below settings(as shown in screenshot) is enables in your java control panel.

Comment: I have added the image to the question now.
Comment: As per your latest screenshot, both versions are enabled. Enable only the version which is to be active.
Comment: I have enabled now only java 8, restarted my browser, tested the page and it still says java is disabled/not installed.
Comment: I would like to suggest you to uninstall the lower version of java, make the browser to run properly. After that figure out the actual problem then install the lower version of java once again if required.
Comment: I have tried this already. I unsitalled everything. Installed Java 8. Ran the browser to see if it is detected but it was not.
Comment: Yes., some other user have already commented. some of the modern/latest browsers wont support java to run in browser. So Which browser are you using and which is of the version? Try once in internet explorer.
Answer: I have solved it. Even though I am using a 64 bit machine, if I install a 64 bit version of Java it will not work. I installed a 32 bit of Java and now it works.

java not running in any browser


Paddle switch Pass and Seymor model RCD38

Question: I have the following model paddle switch/receptacle  Pass and Seymor  Legrand Radiant Model RCD38
Can I configure this switch paddle/receptacle  so that the switch controls the outlet only ?
Answer: Nothing easier.  Attach 2 wires (+ground).

Attach the neutral wire to the silver screw on the receptacle side.
Attach the always-hot wire to one of the brass (traveler) screws on the 3-way switch side.
Don't break off the tab.

If you don't like which throw is "on", move the always-hot wire to the other traveler screw.
Comment: Ok thanks for your quick response  I will give it a try.
Comment: that's it worked like a charm thanks again for your help .


Ubuntu 16.04 does not wake up from sleep on ASUS Laptop

Question: I'm running 16.04.1 LTS on an asus laptop. The laptop does not wake up after being suspended(sleep). But the hibernate mode works.
When lightdm service is stopped, sleep mode works normally. However, I can not restart Lightdm.
Ubuntu kernel version: 4.4.0-57-generic
Custom computer specs:

Laptop model: ASUS A556UQ
CPU: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
VGA: Intel Corporation Device 5916 (rev 02) / GM108M [GeForce 940MX]
Comment: I have installed drivers for graphics (nvidia and intel).
I had resume test on my laptop. I found that console mode works after suspend. because able to use ssh to connect to my laptop from another PC. Please tell me how to solve this problem.
Answer: Maybe this will work: shutdown your laptop from the ubuntu gui. It worked for me.
Source: https://bbs.archlinux.org/viewtopic.php?id=221224


Find gaps in time not covered by records with start date and end date

Question: I have a table of fee records (f_fee_item) as follows:
Fee_Item_ID    int
Fee_Basis_ID   int
Start_Date     date
End_Date       date

(irrelevant columns removed)
Assume that records for the same Fee_Basis_ID won't overlap.
I need to find the Start_Date and End_Date of each gap in the fee records for each Fee_Basis_ID between a supplied @Query_Start_Date and @Query_End_Date. I need this data to calculate fee accruals for all periods where fees have not been charged.
I also need the query to return a record if there are no fee records at all for a given Fee_Basis_ID (Fee_Basis_ID is a foreign key to D_Fee_Basis.Fee_Basis_ID if that helps).
For example:
@Query_Start_Date = '2011-01-01'
@Query_Start_Date = '2011-09-30'

D_Fee_Basis:
F_Fee_Item
1
2
3

F_Fee_Item:
Fee_Item_ID  Fee_Basis_ID  Start_Date  End_Date
1            1             2011-01-01  2011-03-31
2            1             2011-04-01  2011-06-30
3            2             2011-01-01  2011-03-31
4            2             2011-05-01  2011-06-30

Required Results:
Fee_Basis_ID   Start_Date  End_Date
1              2011-07-01  2011-09-30
2              2011-04-01  2011-04-30
2              2011-07-01  2011-09-30
3              2011-01-01  2011-09-30

I've bee trying different self-joins for days trying to get it working but with no luck.
Please help!!
Comment: How many records has `F_Fee_Item` table ?
Comment: Expected to remain under 5 figures for the lifetime of the system
Answer: Here is a solution:
declare @Query_Start_Date date= '2011-01-01'
declare @Query_End_Date date = '2011-09-30'

declare @D_Fee_Basis table(F_Fee_Item int)
insert @D_Fee_Basis values(1)
insert @D_Fee_Basis values(2)
insert @D_Fee_Basis values(3)

declare @F_Fee_Item table(Fee_Item_ID int, Fee_Basis_ID int,Start_Date date,End_Date date)
insert @F_Fee_Item values(1,1,'2011-01-01','2011-03-31')
insert @F_Fee_Item values(2,1,'2011-04-01','2011-06-30')
insert @F_Fee_Item values(3,2,'2011-01-01','2011-03-31')
insert @F_Fee_Item values(4,2,'2011-05-01','2011-06-30')

;with a as
(-- find all days between Start_Date and End_Date
select @Query_Start_Date d
union all
select dateadd(day, 1, d)
from a
where d <  @Query_end_Date
), b as
(--find all unused days
select a.d, F_Fee_Item Fee
from a, @D_Fee_Basis Fee
where not exists(select 1 from @F_Fee_Item where a.d between Start_Date and End_Date and Fee.F_Fee_Item = Fee_Basis_ID)
),
c as
(--find all start dates
select d, Fee, rn = row_number() over (order by fee, d) from b
where not exists (select 1 from b b2 where dateadd(day,1, b2.d) = b.d and b2.Fee= b.Fee)
),
e as
(--find all end dates
select d, Fee, rn = row_number() over (order by fee, d) from b
where not exists (select 1 from b b2 where dateadd(day,-1, b2.d) = b.d and b2.Fee= b.Fee)
)
--join start dates with end dates
select c.Fee Fee_Basis_ID, c.d Start_Date, e.d End_Date from c join e on c.Fee = e.Fee and c.rn = e.rn
option (maxrecursion 0)

Link for result:
https://data.stackexchange.com/stackoverflow/q/114193/
Comment: Perfect. Thanks for the help. I really need to learn CTEs properly.


Hose bib below grade, yard hydrants

Question: Does UPC 2015 allow hose connections below grade (e.g. in an underground valve box)? Is a regular vacuum breaker sufficient in this situation or is a double check valve needed (typical for sprinklers)?

603.5.17 Potable Water Outlets And Valves. Potable water outlets, freeze-proof yard hydrants, combination stop-and-waste valves, or
  other fixtures that incorporate a stop and waste feature that drains
  into the ground shall not be installed underground.
  A vacuum breaker is not considered a "stop and waste feature" correct?

Related question regarding yard hydrants, which would be an alternative if I can't put a hose connection under ground. Per Table 603.2 "Freeze resistant sanitary yard hydrants" "Such devices are not for use under continuous pressure conditions."
Does this mean a valve is required a before a yard hydrant? i.e. when you close the valve on a hose bib "hose connection vacuum breaker" is no longer subject to operating pressure, however the "freeze resistant sanitary yard hydrant" assembly as a whole technically remains under pressure when you shut off the yard hydrant.
Comment: What yard hydrant are you referring to?
Comment: This is a [freeze resistant sanitary yard hydrant](https://www.plumbingsupply.com/sanitaryyardhydrants.html) which doesn't have any openings underground. UPC 603.5.17 is prohibiting [hydrants like these](https://www.homedepot.com/p/Everbilt-2-ft-Bury-Depth-Frost-Proof-Yard-Hydrant-EBYH02NL/205031731) that have fitting at the bottom (below ground) which drains water out of the riser pipe to prevent freezing.
Comment: I put in a couple low hose bibbs off the sprinkler system . They were inconvenient , I plugged one and raised the other to about one foot . above the ground.
Answer: You'd probably need a double check valve like a sprinkler system to put a garden hose connection underground.
For the yard hydrant:
Your link says "Frost Proof" which is different than "Freeze resistant".  Further your referenced code says " that incorporate a stop and waste feature that drains into the ground".  The description for the yard hydrant you have linked says "Unlike conventional hydrants which drain the water into the ground, these use a reservoir below the frost line to contain the water".
I'd argue that either point makes this portion of the code inapplicable but certainly the 2nd portion where it doesn't drain into the ground at all.
Comment: Code uses the term "freeze resistant" and as far as I can tell "frost proof" and "freezeless" are colloquial terms for the same. Can you explain the difference? Also I updated the original question, I'm really asking two separate questions there.
Comment: I'd disagree.  There is a big difference between water resistant and water proof and a similar difference between freeze resistant and freeze proof.
Comment: Waterproof? Do you mean like ISO standards for watches? IP Codes for electrical equipment? Something else? With respect to yard hydrants "freeze resistant" is used consistently in Universal Plumbing Code and the underlying ASSE 1057 standard which describes different mechanisms for achieving "freeze resistance". Freeze proof/freezeless/etc. are just marketing terms applied liberally, I wouldn't try to extract fine details where none were put.

Hose bib below grade, yard hydrants


Netplan error in network definition bonding

Question: Copied the example on netplans site and have issues with the interfaces not defined. Below is my config that i'm using. I no longer have internet access on that machine. This was working but rebooted and now it's broken again.
network:
  version: 2
  renderer: networkd
  bonds:
    bond0:
      dhcp4: yes
      interfaces:
        -  enp0s25
        -  enp8s0
      parameters:
        mode: active-backup
        primary: enp0s25

Thanks!
GD
Answer: Netplan will refuse to use physical devices which are not defined at all in the config, and will consider it an error.
A correct config would look like:
network:
  version: 2
  renderer: networkd
  ethernets:
    enp0s25: {}
    enp8s0: {}
  bonds:
    bond0:
      dhcp4: yes
      interfaces:
        - enp0s25
        - enp8s0
      parameters:
        mode: active-backup
        primary: enp0s25

Comment: That did the trick. I do get another error saying that the bond0: bond already has a primary slave:  I removed the primary: part of the code and it applied the config. I'm not sure if i need that 100% or not but i have access to the internet again on that machine. So a step in the right direction. Thank you for your assistance.


WCF over HTTPS and Signing the body

Question: I've got a SOAP service I want to connect to. It needs to be accessed trough https and it needs to have it's body signed by a certificate.
I've tried the following code:
<basicHttpBinding>
    <binding name="P4Binding" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
        <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
            maxBytesPerRead="4096" maxNameTableCharCount="16384" />
        <security mode="TransportWithMessageCredential">
        <transport clientCredentialType="None" proxyCredentialType="None"
            realm="" />
        <message clientCredentialType="Certificate" algorithmSuite="Default" />
        </security>
    </binding>
</basicHttpBinding>

Setup up my client as follows:
P4_ServiceReference.P4PortTypeClient client = new P4_ServiceReference.P4PortTypeClient();

client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
client.ClientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(@"[..].cer");
client.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(@"[..]", "somepass");

Even changed my Reference.cs to include the ProtectionLevel=ProtectionLevel.Sign on the ServiceContractAttribute and the OperationContractAttribute.
What happens is that the wse:security header is created, but the body is not being signed. The service returns Element http://schemas.xmlsoap.org/soap/envelope/Body must be signed.
What am I missing so that the body gets signed properly?
Answer: Fixed it using this customBinding instead of the basicHttpBinding.
        //Setup custom binding with HTTPS + Body Signing + Soap1.1
        CustomBinding binding = new CustomBinding();

        //HTTPS Transport
        HttpsTransportBindingElement transport = new HttpsTransportBindingElement();

        //Body signing
        AsymmetricSecurityBindingElement asec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
        asec.SetKeyDerivation(false);
        asec.AllowInsecureTransport = true;
        asec.IncludeTimestamp = true;

        //Setup for SOAP 11 and UTF8 Encoding
        TextMessageEncodingBindingElement textMessageEncoding = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);

        //Bind in order (Security layer, message layer, transport layer)
        binding.Elements.Add(asec);
        binding.Elements.Add(textMessageEncoding);
        binding.Elements.Add(transport);

It seems that TransportWithMessageCredential only uses the Transport for security and ignores everything else.
Comment: I tried signing the body only, but using the AsymmetricSecurityBindingElement still encrypts it (the service doesn't use https). I have a question here: http://stackoverflow.com/questions/20349062/wcf-client-binding-to-sign-the-body-of-a-request-to-a-java-web-service
Comment: @MrShoubs apply the following attribute to your service interface and encryption won't happen anymore, `[ServiceContractAttribute(ProtectionLevel = ProtectionLevel.Sign, ...)] public interface MyService { ... }`. Note that this could be performed from code too with something like `myService.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign`.

WCF over HTTPS and Signing the body


About the integral bounds of Jacobian

Question: Given D={(x,y)|x⩾0,y⩾0,x+y⩽1}, find the value of $\iint _{D} e^{x+y} dxdy$
Method 1:
\begin{array}{l}
\iint _{D} e^{x+y} dxdy=\int _{0}^{1}\int _{0}^{1-y} e^{x+y} dxdy\\
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ =\int _{0}^{1} e^{y}\left( e^{1-y} -1\right) dy\\
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ =1
\end{array}
Then I tried to solve this question by Jacobian
\begin{array}{l}
Let\ u=x+y,\ v=x,\ 0\leqslant v\leqslant u\leqslant 1\\
\begin{cases}
x=v\\
y=u-v
\end{cases}\\
J=\begin{vmatrix}
x_{u} & y_{u}\\
x_{v} & y_{v}
\end{vmatrix} =\begin{vmatrix}
0 & 1\\
1 & -1
\end{vmatrix} =-1
\end{array}
The different results that came out from the different integral bounds confused me.
\begin{cases}
\int _{0}^{1}\int _{0}^{u} e^{u} |J|dvdu=1\\
\int _{0}^{1}\int _{0}^{1} e^{u} |J|dvdu=e-1
\end{cases}
The integral bounds of Jacobian should be constants, but the result isn't the same as the one in method 1.
And I tried to change the integral bounds from $\int _{0}^{1}\int _{0}^{1} dvdu$ to $\int _{0}^{1}\int _{0}^{u} dvdu$. The results are the same, but the integral bounds of Jacobian aren't like that.

Please help. Thanks in advance.
Comment: Bounds have not Jacobian, but integration area. When you fixed area, then result will be unambiguous.
Comment: @zkutch Thanks for your hint. So, for this question, the correct integral bound should be $\int _{0}^{1}\int _{0}^{1} dvdu\ $
Answer: The bounds are not required to be constants.  They are just preferred to be nice to work with.
$$\begin{align}\iint_D \mathrm e^{x+y}\,\mathrm d x\,\mathrm d y&=\iint_{0\leqslant x\leqslant x+y\leqslant 1}\mathrm e^{x+y}\,\mathrm d x\,\mathrm d y\\&= \iint_{0\leq v\leqslant u\leqslant 1} \mathrm e^u\,\lVert\mathbf J_{v,u}^{v,u-v}\rVert\,\mathrm d v\,\mathrm d u\\&=\int_0^1\mathrm e^u\int_0^\color{crimson}u 1\,\mathrm d v\,\mathrm d u\\&=1\end{align}$$

About the integral bounds of Jacobian


Why am I getting this error when I try to install RSpec?

Question: I have used RSpec before and this is the first time I get this error when I try to run:
rails generate rspec:install

It results in this error:
/Users/ldco2016/Projects/workout_app/config/application.rb:11:in `require': cannot load such file -- action_cable/engine (LoadError)
    from /Users/ldco2016/Projects/workout_app/config/application.rb:11:in `<top (required)>'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:82:in `require'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:82:in `preload'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:143:in `serve'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:131:in `block in run'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:125:in `loop'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application.rb:125:in `run'
    from /Users/ldco2016/.rvm/gems/ruby-2.2.5/gems/spring-2.0.0/lib/spring/application/boot.rb:19:in `<top (required)>'
    from /Users/ldco2016/.rvm/rubies/ruby-2.2.5/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Users/ldco2016/.rvm/rubies/ruby-2.2.5/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from -e:1:in `'

This is my gemfile:
source 'https://rubygems.org'
git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 4.2.0'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'rspec-rails', '3.2.3'
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'capybara', '2.4.4'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

This is my config/application.rb:
require_relative 'boot'

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module WorkoutApp
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.
  end
end

Answer: This issue is not related to RSpec. You're trying to load action_cable in a Rails 4 application (according to your Gemfile), and that's a built in feature for Rails 5. Just remove this line from your application.rb.
require "action_cable/engine"

If you don't really need to load Rails modules independently, just replace all the requires by:
require 'rails/all'

Comment: Is there a way to correct this without creating a new rails app? I ask because I am removing all the Rails 5 features and then hit another roadblock such as this: undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
Comment: Are you trying to go back to Rails 4 from a Rails 5 app?
Answer: In app/application.rb, comment "require "action_cable/engine"
Comment: I decided to just blow it away since it was a skeleton app and I saw another SO documentation saying to start rails  new my_app and so that's what I did.


Closed form expression for the expected Euclidean distance between $2$ randomly chosen lattice points among $N$ points in a rectangular region

Question: In relation to a research project I'm in, an interesting question came up:

Given a classroom of a certain size, with a certain number of students in it for a certain amount of time, what is the average distance between them.

I'm ignoring the time aspect of the problem and only focusing on the other parts.
I tried modeling the room as simply a rectangular region in a Cartesian plane with $N$ students occupying some randomly chosen group of points with integer coordinates i.e lattice points.
Each configuration of $N$ students is equally probable. No 2 students can occupy the same point.
I came up with this formula for the expected value of the Euclidean distance between any $2$ students:
$$\mathbb{E}[d(s_i, s_j)] = \dfrac{1}{2N(N-1)} \dfrac{WH-2 \choose N-2}{WH \choose N} \sum_{x_i = 0}^{W} \sum_{y_i = 0}^{H} \sum_{x_j = 0}^{W} \sum_{y_j = 0}^{H} \sqrt{(x_i - x_j)^2 + (y_i - y_j)^2}$$
Where $W$ is the unit width of the room, $H$ the unit height, and $N$ the number of students. Each student $s_i$ is defined by a unique point $(x_i, y_i)$. The term $\dfrac{WH-2 \choose N-2}{WH \choose N}$ represents the probability that a given configuration of the class has those 2 points occupied by a student and $\dfrac{1}{N(N-1)} = P(s_i)P(s_i | s_j)$ represents the probability that those 2 students are picked (the 2 is because of double counting). These are constant so I just moved them to the outside.
Similar questions have been answered before (1,2,3,4,5) for any points within a region rather than just lattice points.
The closest thing to that question is (Average shortest distance between some random points in a box) but I would like to know how it scales for any general rectangular region. In addition, that answer simply simulated the points and said the problem can be approximated as the "any 2 random points in a unit square" problem, but that only works for low values of $N$ and for a unit square. It also doesn't provide a proof.
My main questions are:

Is there a closed form expression for the sum above?
If not, is there a way to approximate the problem above?
Is simply simulating the above problem the best course?
Comment: Can two students occupy the same lattice point?
Comment: There is certainly a logical problem here. Computing the prefactor you will obtain $\frac1{2WH(WH-1)}$, the value independent of $N$. This is not what one intuitively expect for the dependence (the more students - the shorter mean distance).
Comment: True. Maybe one of the factors is unnecessary, but if so then I would maybe have to some over elements of a sets rather than coordinates in a range which makes things more complicated. I'm wondering where my intuition went wrong.
Comment: Maybe you are correct, but the problem is ill-stated. Could it be that you are in fact interested in the mean value of the *shortest* distance instead?
Comment: The problem isn't about mean shortest distance, it's about mean distance alone. Also, I believe that $P(s_i)P(s_i | s_j)$ could equal N/WH * N/WH as the probability a point $(x_i, y_i)$ is occupied is N/WH and same for $(x_j, y_j)$. as we also include $(x_i, y_i)$ = $(x_j, y_j)$. I think that should be the real term out front but I'm not sure. It could also be just N(N-1)/WH(WH-1) as when the 2 points are equal they're just zero. What it implies is that 1/2N(N-1) is redundant.
Comment: I can imagine that the "mean distance" is independent of $N$ and no probability is involved into problem.
Answer: You couch the sum in terms of placing $N$ students randomly on $WH$ lattice points and then choosing two of the $N$ students at random.
But this is just a fancy way of picking two lattice points.
And by the symmetries of the two operations by which you do this,
no pair of points is more likely to be chosen than another.
Hence it is not surprising if you get an answer that is independent of $N.$
In fact there are $\binom{WH}{2}$ ways to choose the pair of points,
and as each is equally likely, the probability weight on each point in your sum
should be
$$\frac{1}{\binom{WH}{2}} = \frac{2}{WH(WH-1)}.$$
Taking into account that a summation like the one you are using will visit each pair of points twice, we can instead give each term the weight
$$\frac{1}{WH(WH-1)}.$$
You almost got this, except that while you were worried about double-counting the points you forgot about double-counting the pairs of students when you wrote $N(N-1).$
In fact there are $\binom N2 = \frac12N(N-1)$ ways of choosing two students out of $N,$ and this $\frac12$ cancels the factor of $2$ that you wanted to put in the denominator.
There are some other inconsistencies in your summation, however. One of these is a "fencepost" problem: you seem to have difficulty deciding whether your room of dimensions $W \times H$ has $H$ rows of lattice points with $W$ points in each row
or $H+1$ rows of lattice points with $W+1$ points in each row.
The claim that there are $\binom{WH}{N}$ ways to place $N$ students says that you are thinking of $H$ rows with $W$ points in each row, but a summation of the form
$$
\sum_{x_i = 0}^{W} \sum_{y_i = 0}^{H}
$$
creates $(W+1)(H+1)$ terms corresponding to $H+1$ rows with $W+1$ points in each row.
If you really want $H$ rows with $W$ points in each row,
a possible summation is
$$
\sum_{x_1 = 0}^{W-1} \sum_{y_1 = 0}^{H-1} \sum_{x_2 = 0}^{W-1} \sum_{y_2 = 0}^{H-1}
 \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}.
$$
By stopping at $W-1$ you ensure that you only count $W$ rows.
Alternatively, you can let the coordinates run from $1$ to $W$ and $1$ to $H.$
If you really want coordinates from $0$ to $W$ and $0$ to $H$
then you must account for $(W+1)(H+1)$ lattice points, and the factor out front becomes
$$\frac{1}{2\binom{(W+1)(H+1)}{2}} = \frac{1}{(W+1)(H+1)(WH + W + H)}.$$

By the way, in general when summing over pairs of distinct points in a rectangular grid I would have written the last summation as something like
$$
\sum_{\substack{0 \leq y_2 \leq H - 1\\(x_2,y_2)\neq(x_1,y_1)}},
$$
but I realize that in this particular summation, the terms where
$(x_2,y_2)=(x_1,y_1)$ come out to zero and have no effect on the result.


On solvability of a null-divergence problem

Question: Recently, I've been working with a colleage on the numerical solution of some problems in fluid mechanics via the Van-Kan algorithm.
In the case we're studying these days, we've come across the following problem:
$$\left\lbrace
\begin{array}{l}
\partial_x G_1+ \partial_y G_2 = 0, \quad \text{in } \Omega\\
G_1(0,y) = y(2-y), \quad y \in [0,2], \\
G_1(x,y) = 0, \quad \text{in } \partial \Omega \setminus \{x = 0\}, \\
G_2(x,y) = 0, \quad \text{in } \partial \Omega,
\end{array}
\right.$$
where $G = (G_1,G_2) \colon \mathbb{R}^2 \to \mathbb{R}^2$ and $\Omega = [0,10] \times [0,2]$.
We are stuck in deciding whether if the upper problem has solution or not. We've notice that, if the solution exists, it must not be compatible with the Divergence/Green theorem (as the given boundary conditions do not integrate to $0$ on $\partial \Omega$). Any advice on the (non-)existence of solutions?
Thank you in advance.
Comment: It seems you are addressing "flow in a pipe" problems... If you have a fixed inflow with no outflow, the fluid cannot be incompressible.
Comment: My intuition is exactly the same. Is there any way to prove this mathematically?
Answer: There is no solution, as the divergence theorem can be extended to Sobolev spaces:
Michel Willem - Functional Analysis (Fundamentals and Applications) - Birkhäuser Basel (2013). Theorem 6.3.4.


Unique identifier and long int comparison as primary key

Question: I have seen two data types unique identifier and long int as primary keys of data table many times. Which one is better? Please share your opinions. Advantages and disadvantages over each other of both of them.
Answer: if you don't have a specific reason to use GUIDs, use INTs.

ADVANTAGEOUS OF GUID:

unique identifier is better because guaranteed to always return a
unique value across space and time
I don't know the full mechanics of creating a GUID, but I seem to
remember that it has something to do with the MAC address on your
network card and the system time.
This comes in handy if you're consolidating records from multiple
SQL Servers into one table, as in a data warehousing situation.
GUIDs are also used heavily by SQL Server replication to keep track of rows when they're spread out among multiple SQL Servers.
DISADVANTAGEOUS OF GUID:
There is no way to determine the sequence in which uniqueidentifier
values were generated. They are not suited for existing applications
that depend on incrementing key values serially
The main disadvantage to using GUIDs as key values is that they are
BIG.  Indexes built on GUIDs are going to be larger and slower than
indexes built on IDENTITY columns
GUIDs are problematic as clustered keys because of the high
randomness
Comment: There are 2 main problems with Guids as PKs. Their size, which you can't do anything about, and their randomness, which causes index fragmentatation and page splitting; you can avoid the latter problem by using newsequentialid() rather than newid() to get an ordered sequence of ids. If you need to generate Guids on the middle tier or client, look into the concept of "Comb". This is designed to solve the same problems as newsequentialid().


Persist Joda-time's DateTime via Hibernate

Question: I'm using Jodatime in my Play app, but currently having to do a bunch of converting back and forth  from/to java.util.Date and java.sql.Time.
Since jodatime is included in the Play distribution, I'm thinking there's probably a better way to do this. Is there any way I can make my Model fields DateTimes instead of java.util.Date and java.sql.Time so the conversion is done automatically?  Is there another way of streamlining this?
Answer: For Hibernate 3 add the following annotation to your date field:
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")

Hibernate will now do the dirty work for you.
(Make sure you have joda-time-hibernate.jar in your classpath)
UPDATE:
For Hibernate 4 and 5 add the following annotation:
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")

(Make sure you have jadira-usertype-core.jar in your classpath)
Comment: I added that and imported `org.hibernate.annotations.Type` but got "Could not determine type for: org.joda.time.contrib.hibernate.PersistentLocalDate`". Anything else I need to set up?  Or maybe it's a problem with Play only using Hibernate via JPA rather than directly?
Comment: You should include the joda-time-hibernate jar in your classpath.
Comment: @KeesdeKooter , the question asked for a JPA solution. Your answer uses @Type(...). I guess by this you mean org.hibernate.annotations.Type . Using this annotation creates a dependency on Hibernate. Do you know of a solution that uses the more general JPA instead of Hibernate?
Comment: dropped the jar in `framework/lib`, restarted, and was able to get it working. Their website did trick me at first, the big 'get latest version' link is for joda-time, not joda-time-hibernate.
Comment: Is there some reason not to use `org.joda.time.contrib.hibernate.PersistentDateTime`, since that is the data type that was being asked for? If you use this, it's also possible to get the field working with fixtures, since there is a binder for `DateTime` but not `LocalDate`.
Comment: Thanks @russellhoff. I added this to the answer.
Comment: FYI, the CRUD module doesn't seem to support JodaTime as of now - https://play.lighthouseapp.com/projects/57987-play-framework/tickets/1268-crud-module-doesnt-support-jodatime
Comment: Yes that would be a more accurate answer. Thanks for pointing that out. Will edit my answer.
Comment: @James and Abdull: true. This is a Hibernate only solution. But apparently good enough for the OP to accept the answer. Maybe we should rephrase the question as there is no out of the box solution for JPA as far as I can tell.
Comment: @James I corrected the answer in line with the edited question.
Comment: If you are in another timezone than UTC, be sure to specify this as a parameter to the `@Type`-annotation. I just got burned by this, with the times being persisted in the database being 2 hours earlier than they should have been, and appeared in the application.
Comment: While this is good for persistence and reading joda datetime fields, it still throws errors when trying to sort the results by that datetime field in JPA named queries. Do you or anyone know of a way around that?
Comment: You should turn to using jadira framework in case your Hibernate version is 4.x.
Comment: For anyone trying the above while using Java 7: Jadira usertype-core version 6 is only supported on Java 8 and higher. This results in a rather weird error (some class not found, similar to not having the dependency at all). Therefore you'll have to use verion 5 of the library with Java 7.
Answer:
Joda recommends to use the UserType libraries with Hibernate 4.0, the version of Hibernate bundled with Play 1.2.x (see: http://joda-time.sourceforge.net/contrib/hibernate/index.html).
The proper way to handle the dependency is using the dependencies.yml file, including a line like this:
- org.jadira.usertype -> usertype.jodatime 2.0.1

Comment: I would suggest that you open a new question for this.
Answer: Instead of putting the @Type annotation at each of your Joda properties you can add this in your jpa properties
#Hibernate config
jadira.usertype.autoRegisterUserTypes=true

and it should work just fine.
ps. jadira-usertype-core.jar should be in your classpath.
Comment: This solution provides less reliance on Hibernate-specifc annotations. Nice!
Answer: We should enable two jars in Hibernate 4 project:

compile("joda-time:joda-time:2.8")
compile("org.jadira.usertype:usertype.jodatime:2.0.1")


On displaying QImage, my application window expands

Question: On displaying a picture using QImage, my application window expands, and all the QWidgets gets scattered up and down.
I want the Image to Shrink-fit into a specific square or rectangle so that my window widgets stay intact.
<code>    #Student Image
    self.StudentImage = QImage()
    self.StudentImage.load("C:\Users\DELL\Pictures\ABC.JPG")
    self.StudentImageLabel = QLabel()
    self.StudentImageLabel.setPixmap(QPixmap.fromImage(self.StudentImage))

    #in the QGridLayout
    self.StudentAdmissionLayout.addWidget(self.StudentImageLabel,0,2,4,4)
</code>
Answer: Use this method to scaled your image;
<code>QLabel.setScaledContents (self, bool)
</code>
Reference : http://pyqt.sourceforge.net/Docs/PyQt4/qlabel.html#setScaledContents

Example;
<code>#Student Image
self.StudentImage = QImage()
self.StudentImage.load("C:\Users\DELL\Pictures\ABC.JPG")
self.StudentImageLabel = QLabel()
self.StudentImageLabel.setPixmap(QPixmap.fromImage(self.StudentImage))
self.StudentImageLabel.setScaledContents(True)
#in the QGridLayout
self.StudentAdmissionLayout.addWidget(self.StudentImageLabel,0,2,4,4)
</code>

Regards,


Fast file copier with Samba support?

Question: I'm looking for a fast file manager for Ubuntu.
I need to copy a lot of files to Windows machine via Samba. Nautilus is so slow, that when I click on the directory I need to copy the screen just dims and takes forever to list the files.
Any recommendations, except compiling mc from source? Maybe some terminal command?
Comment: It sounds like you have network issues... at least with samba. Nautilus is only as slow as the protocol it's trying to execute on, it'll be just as slow through anything else.
Comment: @Martin It is slow on local drive.
Answer: Mount the windows shares using smbfs (for instructions check http://www.debian-administration.org/articles/165), then just copy from the terminal using rsync.

Fast file copier with Samba support?


JHipster JWT authentication across browser tabs

Question: I'm getting started with jHipster.. I have configured to use JWT for authentication.
When signed in using one tab and try to open secured page in other tab, I'm not authenticated in the new tab
Is this the default behavior of JHipster? Is it possible to configure token sharing across multiple browser tabs?
I tested more and below is my observation. When using HTTP session based authentication and OAuth2 based JWT authentication, I'm authenticated across different tabs. But when I use JWT based authentication, when logged in one tab, I'm not authenticated in a new tab. I tested this using production configuration too.. It has the same behavior.
I'm not sure if this is the default behavior of JHipster.. but i feel the behavior is inconsistent between different authentication methods...
One observation is OAuth2 uses browser localstorage and plain JWT uses sessionstorage.. When using session storage, the tokens are not visible between the tabs... This explains the behavior.
Is this the default behavior of JHipster?
Comment: First, Auth0 is not an authentication type of JHipster. Where to store JWT has been discussed several times in JHipster github issues with no real conclusion like here https://github.com/jhipster/generator-jhipster/issues/3405 . Third option is http-only secure cookies.
Comment: It was supposed to be OAuth2. I have updated in question. Still the question remains unanswered
Comment: Yes that's my point, there's currently no definitive answer yet. Work is being done on auth2 refresh tokens and the http-only secure cookie storage has been chosen. See https://github.com/jhipster/generator-jhipster/pull/5812
Comment: If you prefer localstorage over sesionstorage, just switch to it in the angular code, it's easy to do.
Comment: Possible duplicate of [JWT: how to handle GET requests when user opens a new tab?](https://stackoverflow.com/questions/30061307/jwt-how-to-handle-get-requests-when-user-opens-a-new-tab)
Answer: Try to click "Remember me" button.
So, it will remember you accross tabs.
Comment: Thank you show much.. this solution is working for me


Should we go for AFCI when we have Circuit breaker

Question: I know circuit breaker trips the electric supply when there's overcurrent such as short circuit.
ARC Fault leads to overcurrent so IMO circuit breakers are enough and AFCI(Arc Fault Circuit interrupter) is not needed.
Can someone clarify if this is right ?
Comment: AFC will detect and shut down you circuit before the big one
Comment: But why , Circuit breaker does the same job right ?
Comment: CB only reacts when you have full current flow, 20 Amp or 30 or 50 and so on. AFC reacts to any small arching. Full current can be damaging.
Comment: So when there's ARC wouldn't it draw higher current like 20 Amp or more ? and also can you explain me how full current can be damaging .. I mean would it damage the wire ? or other connected appliance at home ?
Comment: you are confusing a short circuit with arc. it draws way more current until the cb reacts. arching is the beginning of the short circuit. Regular cb is a mechanical device (with resistance heat element. afc is a electronic curcuit that prevents short circuit
Comment: I get it now , thanks
Comment: If you have seen seen/used welders, that is an arc.  Those welders are on a circuit breaker, some as small as 20 amps, same size as a house circuit.  An AFCI prevents that arc.
Comment: Oh is it ? Good to know thanks
Comment: Actually you should go ahead and have CAFCI ( Combined Arc Fault Circuit Interrupt ) rather than AFCI because AFCI can stop only parallel arcs but CAFCI can stop Parrallel and Serial ARCs.
Answer: Arc faults can be just from a loose connection.
A plain breaker will happy supply power to a loose connection, even as it is heating and burning.  The breaker will only trip if a hot wire touches ground or neutral wire.
AFCI breakers sense small arcs and will trip fast.
Comment: I think you are thinking of ground faults.  An AFCI senses arcs or what you would call sparks.  Sparks between a hot wire and a hot/live screw will not be an over current, but can cause a build up of heat.  When the outlet burns up and the hot comes in contact with ground/neutral the plain breaker might trip, but you will not care since you are busy trying to put out the fire.
Comment: Won't the breaker trip when there is over current ?  I mean ARC fault should cause over current right ?
Comment: This makes sense
Comment: AFCI, GFCI, and standard over-current breaker. All these are different things.
Answer:
ARC Fault leads to overcurrent

That opinion is incorrect.
Two of the types of arc fault are series arcing.  In this case the arcing is in series with the load, add resistance, and thus current is less than normal.
And in certain cases, a parallel arc can have current less than the rating of the breaker - the heat damage is considerable but they are not drawing enough current to trip hte breaker.

so IMO circuit breakers are enough and AFCI(Arc Fault Circuit interrupter) is not needed.

The NFPA certainly understands the topic better than you do.  If they were not needed, they would not be specified.  A lot of people think NEC is written by dumb New York lawyers. Not at all: it's a consensus process among design engineers and the industry.


Use trained neural network with images showing broader surrounding context

Question: Model has been trained, it reliably recognises dogs from cats in tiny pictures like the following:

All these pictures are pretty much always centered on the cat/dog, and the cat/dog occupies almost all the image frame. There is little to none additional surrounding context, which allows the network to train very efficiently.
The next step is, how to make sure that the same model will effectively tell that in the picture below, there happens to be a cat, similar to the ones used to train the model, but surrounded by a broader environment?

Are there some specific steps to take when the model is supposed to be used in production with images showing a broader context than in training? Or is the model able to detect it automagically?
Answer: It decreasing order of effectiveness, the steps you can take are:

Use more training data, with images having larger borders.
Augment existing training images with borders, maybe through random or mirrored padding.
Try cropping out the borders during inference, creating multiple images with different borders. Pick the run with the best result.
Comment: Yes, in that case using networks for localization would work.
Comment: Would using a selection algorithm (the kind that draws bounding boxes around cats) help? I'm referring to this question: https://stackoverflow.com/questions/43402760/object-detection-with-r-cnn/43406468#43406468
Comment: RCNN, YOLO etc. are state-of-the-art architectures. These networks are overkill for your application. It's like using a 8-core processor on a phone that only makes calls - it can get the job done, but you end up wasting resources.
Comment: I see. My example however was a toy example to avoid getting into too many details. A closer illustration of what I'm trying to do is to classify between cats having a striped pattern and cats having a plain furr. If I train the network on plain/striped cats shown in context, the network doesn't pick any difference. It does if I crop the picture on the cat, but then I'm wondering how to get to best recall when the actual, production-like pictures feature a broad environment with one cat somewhere. Hence my suggestion of using a box-detection first, to help center on the cat. Makes sense?


Conditional probability with Bernoulli and Normal

Question: Let $X$ be a normal variable with mean $0$ and variance $1$. Let $Y$ be Bernoulli with $p = \frac{1}{2}$, and suppose that $X$ and $Y$ are independent. Let $Z = (Y + 1)X$. Find the conditional probability that $Y = 1$ given that $Z = 3$.
I know I need to find $P(Y = 1 | Z = 3) = \frac{P(Y = 1 \cap Z = 3)}{P(Z = 3)}$.
Attempt:
For the numerator, $P(Y = 1 \cap Z = 3) = P(Y = 1 \cap (Y + 1)X = 3) = P(2X = 3) = P(X = \frac{3}{2})$. Since $X$ is standard normal, $P(X = \frac{3}{2}) \approx 0.130$
As for the denominator, $P(Z = 3) = $?
I can't figure this out.
Any assistance is much appreciated.
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match many users' quality standards, so it may attract downvotes, or closed. To prevent that, please edit the question. This will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: @KaviRamaMurthy How about now?
Comment: $\mathsf P(Y=1\cap (Y+1)X=3)~=~\mathsf P(Y=1)\,\mathsf P(X=3/2)$   [Though these would equal $0$ since $X$ is continuous]
Comment: @GrahamKemp And the denominator?
Comment: $P(Z=3)=0$ so the conditional probability does not exist.
Comment: @KaviRamaMurthy Why does it equal $0$?
Comment: Use Total Probability.  $\mathsf P(Z=3)=\mathsf P(Y=1\cap Z=3)+\mathsf P(Y=0\cap Z=3)$  (Though actually you should use probability *density* functions, since $X$ is a continuous random variable)
Answer: $$P(Z=3)=P(X=3,Y=0)+P(X=\frac  3 2, Y=1)$$ $$=P(X=3,P(Y=0)+P(X=\frac  3 2)P(Y=1)=0+0=0$$ since $X$ is a continuous random variable.  [$P(X=a)=0$ for every real number $a$].
Comment: Isn't it $\frac{3}{2}$ for $X$?
Comment: Does it still not exist when $X$ is standard normal?
Answer: $\{Y=1\cap (Y+1)X=3\}=\{Y=1\cap X=3/2\}$ and $\{Y=0\cap (Y+1)X=3\}=\{Y=0\cap X=3\}$.
However these are null events, since $X$ is continuous.  So the expression needs to use the appropriate probability density functions.
$$\mathsf P(Y=1\mid Z=3) =\dfrac{f_{X}(3/2)\,\mathsf P(Y=1)}{f_{X}(3/2)\,\mathsf P(Y=1)+f_{X}(3)\,\mathsf P(Y=0)}$$
Comment: I am surprised since somebody said that such a standard normal and bernoulli random variable would surely exists. That's interesting.
Comment: Also, does it still not exist when $X$ is standard normal?


Re-use circuit breaker handle tie?

Question: I have a double pole 30 amp breaker controlling a 230 volt load that I need to replace.  I cannot obtain one at this moment; perhaps tomorrow but maybe next week.
Either way, I have two good used 30 amp breakers that I could put in place of the 30 amp double pole.
Will it be okay for me to do this if I take the tie bar off of the old breaker and re-use it?
I have already pulled the tie bar off and have the two breakers ready to go.  Hoping that this will be okay!
Answer: Okay, a few caveats first.
The two single phase circuit breakers are to be identical in the following aspects:

Manufacturer
Ampacity (30A, 40A, etc)
Approximate age
Known good
Same size on all faces

Furthermore, I believe the following should be observed:

The circuit breakers being joined must not be adjacent to empty slots (the tie bar may try to slip / fall out) in the breaker panel.
Similarly, if this temporary repair cannot be made with absolute certainty that the breakers will not be allowed to separate during installation/ removal or during their temporary installation than this temporary repair should not be made.  I was able to securely join my breakers together with electrical tape thus prohibiting any separation.

Finally, the following must be understood clearly:

This is a temporary repair. It is likely not code compliant and may result in loss of life, property or severe injury if not done correctly.
This repair is made in lieu of simply installing two breakers with matching ampacity because of the need to simultaneous disconnection of both phases on 230 / 240 volt equipment.  Leaving one phase energized on a 230 / 240 volt circuit can be dangerous to life and property!
Always verify disconnection of service to any breaker before attempting to replace it.  Failure to do so may result in injury or death!
This is a temporary repair!!! A suitable replacement two pole breaker must be installed at the next available opportunity!

Now to answer my question...
Yes, if done carefully this is suitable temporary repair... if the above criteria are met.
While there is an internal mechanical linkage tying together a two pole breaker (see below)

preliminary results indicate that the tie bar will indeed sufficiently disengage (not trip!) the second breaker thus having the effect of simultaneously disconnecting both phases to the load.
My only concern is that 'sufficiently disengaged' may not preclude current passing by arcing.  I am sure that is the reason for the internal linkage on a two pole breaker.  However, this repair is being made on the service for the heat pump which will likely not go long after tripping before being noticed and reset / disconnected.
Answer: Why would you even bother? Handle ties are just a convenience item. They will not turn
two single-pole breakers into a common-trip double pole breaker. Stick a piece of tape
over the two breakers, to make it clear where they are, for the short period of time
until you get a proper 2-pole breaker.
Comment: Because I am replacing a 230 volt breaker.  I will add that to my question, thanks.
Comment: I hope that the need for a tie bar will be obvious now?
Comment: With all due respect, I do not agree.  What you say about them not them being the same is true (beyond the obvious even).  I drilled out the two brads mechanically linking the bad two pole breaker and can see the internal trip linkage.  However, setting the (1/2 two pole) breaker to tripped using that linkage and then setting one single phase breaker to the same "throw angle" results in the disconnection of the single 30 amp (infinite resistance on ohm setting).  So, I am going to go ahead with the tie bar.  Knowing both phases will disconnect will help me sleep tonight.
Answer: For this to work, the two single breakers must pull power off each bus leg to give you 240VAC. If they pull off the same leg, you only get 120VAC (parallel feed). Check to make sure they use alternate bus connections when they're side-by-side.
If the breaker handles have a hole, I've seen a cut nail used to link them. They must be linked so both legs shut off for the obvious reason.
Comment: Yes, this is an important distinction.  My panel is designed with alternating legs.  This is a double pole relay designed for 230 volt loads.  My desire to re-use the tie bar from the 2 pole relay is exactly for the purpose of not having to use a different less suitable connector (a nail).  Not saying a nail won't work but it seems more likely to fail.
Comment: As long as the circuit details (one pulls off L1 and the other pulls off L2) are taken care of and the tie bar stays securely in place when installed AND disengages the other breaker on trip, you should be home free.

Re-use circuit breaker handle tie?


Can't get Django to work on my Mac

Question: I'm having difficulty getting Django to work on my Mac. I pip installed it, as well as downloading it on PyCharm. I have a feeling it will work on PyCharm if I knew what I'm doing. I dont. haha. It's my first time. I am trying to work off the tutorial that they provide on their site. Here is where I run into trouble.
In terminal I type:
python -m django --version

and I get:
/usr/bin/python: No module named django

but when I type:
pip install Django

I get:
Requirement already satisfied (use --upgrade to upgrade): Django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

The tutorial wants me to type:
django-admin startproject mysite

and I get this:
-bash: django-admin: command not found

So to my question. What is going on here? I'm thinking my path to it is different than what is expected, though I'm not fully sure. If you know the startproject mysite could you give it to me? Meaning, if you know the folders and content I think I could get it running on PyCharm. My PyCharm says it's been downloaded, so I think this would be a great way to go into it.
Many thanks.
Comment: Looks like a virtual environment problem. Without going into the extreme details of your environment settings, try the following: make and navigate to an empty directory, type `pyvenv-3.5 ./Env`, then `source ./Env/bin/activate`, next `pip install django`, and finally `python -m django --version`.  This virtual environment should work and be less prone to other odd PATH problems.
Comment: If you want to type this into a solution I'll check it as a working solution! thank you for your quick response, Liam! I must have, in fact, had issues with my virtual environment.
Comment: No problem, glad I could help. I'll add the solution.
Answer: From Comments
Looks like a virtual environment problem. Without going into the extreme details of your environment settings, try the following: make and navigate to an empty directory, type pyvenv-3.5 ./Env, then source ./Env/bin/activate, next pip install django, and finally python -m django --version. This virtual environment should work and be less prone to other odd PATH problems.
Additional Info
You will need to run the command source ./Env/bin/activate when you open up a new shell or run a bash script in order to active this environment.
Also, you can now manage your pip packages (including django) by using pip freeze > ./requirements.txt to create a lists of your packages w/ version numbers and 'pip install -r ./requirements.txt` to install the packages.
Answer: Seems to me that pip is not configured with the python that you are using. From the output you posted, pip is installing Django for the python executable residing in here:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

what is the output of ls -l $(which python) ?
This will tell you where the python you are using is. If it's different than the path above, pip is installing packages on another python executable.
You have 2 quick options.

Put a softlink to the python residing in  /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages inside your /usr/bin/ or wherever is imported before the path that which python shows.
ln -s {target-filename} {symbolic-filename}

which is probably
ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /usr/bin/python

Use a Virtual Environment.
pyenv ./env
source ./env/bin/activate

Now you are working on a virtual environment, which has its own pip and python so you should be fine to do anything you'd want !
Hope it helps

Can't get Django to work on my Mac


Why are my "nav" align and background color not working?

Question: I have 2 CSS stylings for my nav for a background and to align the nav items to center of the navigation bar; however, for whatever reason the alignment and background color only show when I remove the closing brace for the "nav" CSS.

nav {
  text-align: center;
  background-color: gray;
}

.navbar {
  font-family: Helvetica, Sans-Serif;
  font-weight: bold;
  font-size: 1em;
  text-align: center;
}

.navbar a {
  text-decoration: none;
  text-align: left;
  float: left;
  border-bottom: 2px solid;
  padding: .25em 4em 0em 1em;
  color: black;
}

.navbar a:hover {
  cursor: pointer;
  background-color: black;
  color: white;
  border-bottom: 2px black solid;
  transition: background-color .25s linear, color .25s linear;
}

.navbar .current {
  background-color: black;
  border-bottom: 2px black solid;
  color: #ff2c7b;
  position: relative;
}

.current::before {
  content: "";
  display: block;
  width: 0;
  border: 10px solid black;
  border-color: black transparent transparent transparent;
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -10px;
}

  Home
  Articles
  Team Reports
  Team Compendium
  Resources
  Events

Sample text goes here.

I'm still currently learning HTML and CSS, but I figured trying to recreate websites as close as I could would help me learn the skills to then create my own.
Comment: Can you explain better you desired result?
Comment: So, I'm wanting the entire navigation bar to have a background color of gray prior to the CSS styling of the hover and the active. Also, I'm wanting my nav options to be centered within the full navigation bar. Currently it's defaulted to the left-align.
Answer: Your nav element contains floated elements which by default will not be included in the parent's space on the page automatically, i.e. nav will vertically not be extended to cover them and therefore will have a height of 0 because it only contains floated elements. To avoid that, add overflow: auto; to nav .

nav {
  text-align: center;
  background-color: gray;
  overflow: auto;
}

.navbar {
  font-family: Helvetica, Sans-Serif;
  font-weight: bold;
  font-size: 1em;
  text-align: center;
}

.navbar a {
  text-decoration: none;
  text-align: left;
  float: left;
  border-bottom: 2px solid;
  padding: .25em 4em 0em 1em;
  color: black;
}

.navbar a:hover {
  cursor: pointer;
  background-color: black;
  color: white;
  border-bottom: 2px black solid;
  transition: background-color .25s linear, color .25s linear;
}

.navbar .current {
  background-color: black;
  border-bottom: 2px black solid;
  color: #ff2c7b;
  position: relative;
}

.current::before {
  content: "";
  display: block;
  width: 0;
  border: 10px solid black;
  border-color: black transparent transparent transparent;
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -10px;
}

  Home
  Articles
  Team Reports
  Team Compendium
  Resources
  Events

Sample text goes here.

Answer: Add overflow: hidden to your nav rules :
nav {
  text-align: center;
  background-color: gray;
  overflow: hidden;
}

Comment: Add an _explanation_ as to why that is necessary to your answer ;-)


The number of coin tosses needed if the proportion of heads is to lie within 0.05 of p with probability at least 0.9?

Question: There's a question I'm not really sure if I did it right or even understand what its trying to say.
There is a coin which produces heads with an unknown probability p. How many times should we throw this coin if the proportion of heads is to lie within 0.05 of p with probability at least 0.9? Hint: Answer is not complete if it relies on p and do not worry about continuity correction.
This question comes from a chapter about binomial normal approximation.
So far I know I have a B~(n,p) and I need to find the number of n so that P ( c/n <= 0.05*p) >=0.9 with c as the number of heads? I'm not sure if this is right.
In turn P( c <= 0.05pn ) >=0.9
So I'll normalize the binomal such that
P( Z <= [(0.05pn - n*p)/(np(1-p)] +0.5 ) >=0.9
with 0.5 as the continuity correction.
Am I on the right track? I thought about using confidence intervals but we haven't discussed about that in the chapter or lecture.
Comment: You want $P[|c/n - p| \leq 0.05] \geq 0.9$
Comment: Thanks I had trouble trying to understand what the question wants.
Answer: I believe you are expected to use the normal distribution approximation.  From the normal distribution table, $1.645$ standard deviations around the mean include (just over) $0.9$ of the area.  For $N$ flips the standard deviation in the number of heads is $\sqrt{Np(1-p)}$, which is largest at $p=\frac 12$, so $\sigma \leq\frac 12 \sqrt N$.  We want $1.645\sigma \le\frac 121.645\sqrt N\lt 0.05N$, so $N \gt 16.45^2\approx 270.6$  Take $N=271$
Comment: Yeah the topic is about Large Sample theory Normal Approximation. However why is 1.645sigma less that 0.05N?
Comment: The allowable error is $0.05N$ from the problem statement.  The argument before shows why (at the $90\%$ confidence level) we expect to be within $1.645 \sigma$
Comment: I think I understand? I'm just having a bit of trouble conceptualizing it.
Comment: Conceptualizing is not a mathematical word.  This is a sketch of a proof-what particular step is the problem?  We don't really go back to the fundamentals each time-we try to make a statement that the audience will accept.  Just like the proofs in your book, you should look at each step and see if you accept it.  If not, ask another question until you do.
Comment: I think I do understand, Thanks for your time.


ValidationError: RFDeviceId: Path `RFDeviceId` is required

Question: I'm new here and know only baiscs of nodejs and mongodb so please help me to learn.
I'm getting this error
Error creating the dataset: ValidationError: RFDeviceId: Path RFDeviceId is required., coordinates: Path coordinates is required., CoordinatesTime: Path CoordinatesTime is required., speed: Path speed is required., sat_tracked: Path sat_tracked is required., gps_fix_type: Path gps_fix_type is required., temperatureata: Path temperatureata is required., humidity: Path humidity is required., bat_v: Path bat_v is required., bat_p: Path bat_p is required.
and my datasets.js in model is like that
var mongoose = require("mongoose");

// Declare schema
var datasetSchema = new mongoose.Schema({
    owner_name: {type: String, required: true},
    RFDeviceId: {type: String, required: true, index: {unique: true}},
    coordinates: {type: Number, required: true},
    CoordinatesTime: {type: String, required: true},
    speed: {type: String, required: true},
    sat_tracked: {type: Number, required: true},
    gps_fix_type: {type: Number, required: true},
    temperatureata: {type: Number, required: true},
    humidity: {type: Number, required: true},
    bat_v: {type: Number, required: true},
    bat_p: {type: Number, required: true}
});

// Export schema
mongoose.model("Dataset", datasetSchema);```

and my datasets.js in routes
/* CRUD API */
// POST new dataset request
router.post("/", helper.authenticate, function(req, res) {
    // Used to set the dataset owner
    var sessionUser = req.session.user.name;
    // Get values from the post request
    var RFDeviceId = req.body.RFDeviceId;
    var coordinates = req.body.coordinates;
    var CoordinatesTime = req.body.CoordinatesTime;
    var speed = req.body.speed;
    var sat_tracked = req.body.sat_tracked;
    var gps_fix_type = req.body.gps_fix_type;
    var temperatureata = req.body.temperatureata;
    var humidity = req.body.humidity;
    var bat_v = req.body.bat_v;
    var bat_p = req.body.bat_p;
    // Delete the values from the request body so that we only keep information about the variables
    delete req.body.RFDeviceId;
    delete req.body.coordinates;
    delete req.body.CoordinatesTime;
    delete req.body.speed;
    delete req.body.sat_tracked;
    delete req.body.gps_fix_type;
    delete req.body.temperatureata;
    delete req.body.humidity;
    delete req.body.bat_v;
    delete req.body.bat_p;
    `

    // This is so that we can loop through the object in reverse order
    // We do that so that the fields are saved in the right order on the db
    // (this way it will appear in the right order on the 'edit' view)
    var propertiesList = [];
    for (var property in req.body) {
        if (req.body.hasOwnProperty(property)) {
            propertiesList.push(property);
        }
    }
    propertiesList.reverse();

    var variablesFields = {};
    for (var i in propertiesList) {
        console.log(propertiesList[i])
        variablesFields[propertiesList[i]] = {name:req.body[propertiesList[i]],
                                    values: Array};
    }

    // Create dataset
    Dataset.create({
        RFDeviceId: RFDeviceId,
        coordinates: coordinates,
        CoordinatesTime: CoordinatesTime,
        speed: speed,
        sat_tracked: sat_tracked,
        gps_fix_type: gps_fix_type,
        temperatureata: temperatureata,
        humidity: humidity,
        bat_v: bat_v,
        bat_p: bat_p,
        owner_name: sessionUser
    }, function(err, dataset) {
        if (err) {
            console.log("Error creating the dataset: " + err);
            req.session.error = "A problem occured when creating the dataset. Please try again.";
        } else {
            console.log("New dataset created with id: " + dataset._id);
            req.session.success = "Dataset " + "name" + " created successfully.";
        }
        res.redirect("/index");
    });
});

// PUT request to update dataset
router.put("/:id/", helper.authenticate, function(req, res) {
    // Get values from the POST request
    var RFDeviceId = req.body.RFDeviceId;
    var coordinates = req.body.coordinates;
    var CoordinatesTime = req.body.CoordinatesTime;
    var speed = req.body.speed;
    var sat_tracked = req.body.sat_tracked;
    var gps_fix_type = req.body.gps_fix_type;
    var temperatureata = req.body.temperatureata;
    var humidity = req.body.humidity;
    var bat_v = req.body.bat_v;
    var bat_p = req.body.bat_p;
    // Delete the values from the request body so that we only keep information about the variables
    delete req.body.RFDeviceId;
    delete req.body.coordinates;
    delete req.body.CoordinatesTime;
    delete req.body.speed;
    delete req.body.sat_tracked;
    delete req.body.gps_fix_type;
    delete req.body.temperatureata;
    delete req.body.humidity;
    delete req.body.bat_v;
    delete req.body.bat_p;

    var setList = {};
    var unsetList = {};
    var updateQuery = {};

    // Find dataset by id
    Dataset.findById(req.params.id, function(err, dataset) {
        updateQuery = {
            RFDeviceId: RFDeviceId,
            coordinates: coordinates,
            CoordinatesTime: CoordinatesTime,
            speed: speed,
            sat_tracked: sat_tracked,
            gps_fix_type: gps_fix_type,
            temperatureata: temperatureata,
            humidity: humidity,
            bat_v: bat_v,
            bat_p: bat_p,
        }
        // If variable in request body and not in dataset, add to setList (or if no variable at all in dataset)
        for (var property in req.body) {
            if (!dataset.data||(req.body.hasOwnProperty(property)&!dataset.data.hasOwnProperty(property))) {
                console.log(property)
                console.log(req.body[property])
                setList["data."+ property] = {name:req.body[property],
                                                values: Array};
            }
        }

        // If variable in dataset but not in request body, add to unsetList
        for (var property in dataset.data) {
            if (dataset.data&&dataset.data.hasOwnProperty(property)&!req.body.hasOwnProperty(property))
            {
                unsetList["data."+property] = true;
            }
        }

        // If setList or unsetList non-empty, add to updateQuery
        if (Object.keys(setList).length) {
            updateQuery["$set"] = setList;
        }
        if (Object.keys(unsetList).length) {
            updateQuery["$unset"] = unsetList;
        }

        // Update dataset
        dataset.update(updateQuery, function(err, response) {
            if (err) {
                console.log("Error updating dataset: " + err);
                req.session.error = "Update failed, please try again.";
            } else {
                console.log("Update on dataset: " + dataset._id);
                req.session.success = "Update successul.";
            }
            res.redirect("/index");
        });
    });
});

if I set required: false expect with owner_name then first data send time it send MongoError: E11000 duplicate key error collection: test.datasets index: index_1 dup key: { : null }
output screenshot https://ibb.co/pyVXD01
Please help it great pleasure to all.
Comment: Hi, can you explain by giving a sample document, and the expected output?
Comment: Please update your question with that info
Comment: can you please help me to where I'm doing mistake. It's my great pleasure @SuleymanSah
Answer: As you make all the fields required in your model. So whenever you make any dataset, you need to give all your required field's data.
And in your create dataset query API, you first directly assign req.body.[filed-value] to a new variable which also copy the reference of that origin variable.
And when you delete the original variable, your copied variable also lost their values and set to undefined.read ES Documentation
Now your Create query looks like :
// POST new dataset request
router.post("/", helper.authenticate, function(req, res) {
    // Used to set the dataset owner
    var sessionUser = req.session.user.name;
    // Get values from the post request
    var RFDeviceId = req.body.RFDeviceId;
    var coordinates = req.body.coordinates;
    var CoordinatesTime = req.body.CoordinatesTime;
    var speed = req.body.speed;
    var sat_tracked = req.body.sat_tracked;
    var gps_fix_type = req.body.gps_fix_type;
    var temperatureata = req.body.temperatureata;
    var humidity = req.body.humidity;
    var bat_v = req.body.bat_v;
    var bat_p = req.body.bat_p;

    // This is so that we can loop through the object in reverse order
    // We do that so that the fields are saved in the right order on the db
    // (this way it will appear in the right order on the 'edit' view)
    var propertiesList = [];
    for (var property in req.body) {
        if (req.body.hasOwnProperty(property)) {
            propertiesList.push(property);
        }
    }
    propertiesList.reverse();

    var variablesFields = {};
    for (var i in propertiesList) {
        console.log(propertiesList[i])
        variablesFields[propertiesList[i]] = {name:req.body[propertiesList[i]],
                                    values: Array};
    }

    // Create dataset
    Dataset.create({
        RFDeviceId: RFDeviceId,
        coordinates: coordinates,
        CoordinatesTime: CoordinatesTime,
        speed: speed,
        sat_tracked: sat_tracked,
        gps_fix_type: gps_fix_type,
        temperatureata: temperatureata,
        humidity: humidity,
        bat_v: bat_v,
        bat_p: bat_p,
        owner_name: sessionUser
    }, function(err, dataset) {
        if (err) {
            console.log("Error creating the dataset: " + err);
            req.session.error = "A problem occured when creating the dataset. Please try again.";
        } else {
            console.log("New dataset created with id: " + dataset._id);
            req.session.success = "Dataset " + "name" + " created successfully.";
        }
        res.redirect("/index");
    });
});

I hope you got the idea of doing it correctly.
[DO VOTE TO THIS ANSWER, IF ITS HELPFUL TO YOU]
Comment: I appreciate you answer my question but I already check this situation and error is same.if you have any better idea then please help.


Could not find artifact commons-codec:commons-codec:zip:1.10 in grailsCentral (https://repo.grails.org/grails/plugins)

Question: I am newbie to grails/groovy. In my grails app, i added a new dependency to BuildConfig.groovy as below
compile 'commons-codec:commons-codec:1.10'

When I try to start my app, i get the below error

| Error Resolve error obtaining dependencies: Could not find artifact
  commons-codec:commons-codec:zip:1.10 in grailsCentral
  (https://repo.grails.org/grails/plugins)

Please help.
Comment: Did you add that in the `plugins` or `dependencies` section of `BuildConfig.groovy`? You should have added it into the `dependencies` section.
Comment: Your suggestion helped and it solved. I added it in Plugins by mistake instead of dependencies.
Comment: Added it as an answer then.
Answer: Based on the error it would appear you have added this into the plugins section of your BuildConfig.groovy when you should add it into the dependencies section. Doing so will resolve this issue.


Melee in Star Wars Battlefront II

Question: I've just started playing Star Wars Battlefront II, and there are a lot of differences between this game and the 2015 game, especially the melee. In Star Wars Battlefront 2015 the melee did 50 damage and was very slow. In the sequel the melees are much quicker and seem to do much less damage. I was wondering how much damage it does and if it differs by class, for instance it would make sense if assault and heavy do more damage than officer and specialist.
Comment: It probably does less melee damage because there's a Star Card for more melee damage. To keep things "balanced", you know?
Comment: Its not that the melee does less damage than it did before, 50 points. Its that many classes have more than 100 health, so it takes more than 2 to bring them down.
Answer: From what I've gathered all melee attacks deal a standard amount of damage, unless improved by a star card. I usually run a build that lets me punch people much harder than they are able to hit me.

Melee in Star Wars Battlefront II


Is there any research on the effectiveness of Google One tap sign up and sign in implementation for sites/apps?

Question: I'm having a hard time finding anything related to if Google's One tap sign up and sign (https://developers.google.com/identity/gsi/web) in really helps or drives sign-in/up. Not even finding much anecdotal evidence.
Maybe it's worth A|B testing for a short time.
Comment: Did you see this case study? Is this helpful? https://developers.google.com/identity/casestudies/pinterest-casestudy.pdf
Comment: Thanks, I must of missed that. A CS published by Google isn't exactly neutral. I guess I'll just have to implement the feature, and run some tests against internal business goals. I'll report back here my findings as an answer.
Comment: I think it is worth clarifying or understanding the problem that you are trying to address or understand here. It would be good to point out a specific part of the feature that you think causes user experience issues.
Answer: I would have to say that only Google would have the answer to the question, and that no doubt they would be testing this feature for the purpose of improving sign up and the sign in experience. And since it is hard to know the neutrality of Google's published research, and that they cover such a wide range of audience and user's, I think that it is difficult to get an objective answer to this question.
Even case studies that are written about this feature can also be biased, because they might be people who are trying to help people implement this feature, or just don't like Google's way of doing this. I guess you'll just have to make a best guess judgement for yourself and your users.


Dot product in the line integral of a vector field

Question: Why does the integrand of a line integral consist of a dot product between the vector filed $\vec F$ and the unit tangent vector $\hat T$( or normal $\hat n$ )? Does this follow from physical examples( Work done, for an example ) or is there a particular reason behind considering the dot product?
Answer: Higher dimensions always present the difficulty of how to adapt tools to the new situations. The integral is one of those tools, and the generalization is not unique: actually, there are two kind of extensions. Multiple integration (usually carried on with measure theory) and vector calculus (generalized by the calculus on differential forms). Lets focus on the second one. How to generalize the integral from a scalar function on an interval to a vector valued function on a curve? The definition comes up naturally from some considerations:
Lets start with the easy possibility: straight lines. To fix the ideas, we will consider an axis (parametrized resp, the x one: it is natural to consider the line integral as $\int_{\mathbb{R}}F_x$
The passage from one axis to a general line is easy: the geometrical meaning stays the same (projection onto the line) and thus the calculation.
Now, in order to generalize to curves, we can split up in two steps:

Considering the arc parametrization, the definition is quite natural: you are only restricting yourself to the component of the function "near" to the curve (in mathematical terms, tangent).
We have now reached an important result: the integral is now extended to vector-valued functions on curves arc-parametrized. The geometrical ideas, though, stays the same even if the parametrization is changed: what is relevant is the substain. Thus, we would like the integral to be parametrization-invariant: from easy computation, we see that the definition of line-integral is what we are looking for

Just to have a very vague idea, the fundamental theorem of calculus is generalized in two ways, depending on the integral:
With the lebesgue one,we have the so called "Lebesgue differentiation theorem"
$\begin{equation}
\lim_{\mu(B_x)\to 0}\frac{1}{\mu(B_x)}\int_{B}f(y)\ d\mu(y)\to_{a.e.}f(x)
\end{equation}$
While with the one we defined, we have the "Fundamental theorem for line integrals" (generalized by Stokes-Cartan theorem)
$\begin{equation}
\int_\gamma \nabla f=f(\gamma(b))-f(\gamma(a))\ \ \ \ \ \Bigg(\int_Md\omega=\int_{\partial M}\omega\Bigg)
\end{equation}$
Obviously the line integral, as a lot of mathematical tools, is very useful in physics
Answer: Assume you have ahomogeneous, i.e. constant, vector field ${\bf v}$ and a segment path $$\sigma:\quad t\mapsto(1-t){\bf a}+t{\bf b}\qquad(0\leq t\leq 1)\ .$$
In such a case you might be interested in the scalar quantity $q:={\bf v}\cdot({\bf b}-{\bf a})$, or in the vector quantity ${\bf F}:={\bf v}\times({\bf b}-{\bf a})$, or in the quantity ${\bf M}:={\bf v}\,|{\bf b}-{\bf a}|$. Other such primitive paradigmatic cases can be cooked up.
When the vector field ${\bf v}$ is not constant and the curve is not a simple segment the above more or less bilinear concepts morphe to integrals of a characteristic appearence. The first becomes the line integral used to calculate work done. It is not so that we "always" have a dot product in  integrals created in this way.
Comment: What do you mean with "always"? (And to which integral are you referring to? Surface's one or something else?)


Grep function not stopping with head pipe

Question: So i'm currently trying to grep a single result from a random file in a specific directory. The grepping works just fine and the expected output file is populated as expected, but for some reason, even after the output file has already been filled, the process won't stop. This is the grep command where the program seems to be getting stuck.
searchFILE(){
case $2 in
pref)
    echo "Populating output file: $3-$1.data.out"
    dataOutputFile="$3-$1.data.out"
    zgrep -a "\"someParameter\"\:\"$1\"" /folder/anotherFolder/filetemplate.log.* | zgrep -a "\"parameter2\"\:\"$3\"" | head -1 > $dataOutputFile
;;
*)
    echo "Unrecognized command"
;;
esac
echo "Query finished"
}

What is currently happening is that the output file is being populated as expected with the head pipe, but for some reason I'm not getting the "Query finished" message, and the process seems not to stop at all.
Comment: The pipeline will not instantly stop when a single line has been produced. Can you check whether `zgrep` is still running and trying to find further matches?
Comment: My guess is the data is large and matches are rare. `zgrep` will run until the input is exhausted or it tries to write another match and gets SIGPIPE.
Comment: Well, the data is actually very large, but I'm interested only in one result. Shouldn't the head -1 stop the grep once one match has been found? I mean, I know for a fact that the expected result has already been found since the file is being filled as expected, but for some reason the grep doesn't seem to stop at all.
Answer: grep does not know that head -n1 is no longer reading from the pipe until it attempts to write to the pipe, which it will only do if another match is found. There is no direct communication between the processes. It will eventually stop, but only once all the data is read, a second match is found and write fails with EPIPE, or some other error occurs.
You can watch this happen in a simple pipeline like this:
cat /dev/urandom | grep -ao "12[0-9]" | head -n1

With a sufficiently rare pattern, you will observe a delay between output and exit.
One solution is to change your stop condition. Instead of waiting for SIGPIPE as your pipeline does, wait for grep to match once using the -m1 option:
cat /dev/urandom | grep -ao -m1 "12[0-9]"

Answer: The first difference you need to try is pipe with | head -z --lines=1
The reason is null terminated lines instead of newlines (just in case).
My example script below worked (drop the case statement to make it more simple).  If I hold onto $1 $2 inside functions things go wrong. I use parameter $names and only use the $1 $2 $@ once, because it also goes wrong for me if I don't and in any case you can then shift over $@ and catch arguments.  The $@ in the script itself are not the same as arguments in bash functions.
grep searching for 2 or multiple parameters in any order means using grep twice; in your case zgrep | grep.  The second grep is a normal grep!  You only need the first grep to be zgrep to do the unzip.  Your question is simpler if you drop the case statement as bash case scares off people: bash was always an ugly lady that works good for short scripts.
zgrep searches text or compressed text, but newlines in LINUX style vs WINDOWS are not the same. So use dos2unix to convert files so that newlines work.  I use compressed file simply because it is strange and rare to see zgrep, so it is demonstrated in a shell script with a compressed file!  It works for me.  I changed a few things, like >> and "sort -u" but you can obviously change them back.
#!/usr/bin/env bash
# Search for egA AND egB  using option go
# COMMAND LINE: ./zgrp egA go egB
A="$1"
cOPT="$2" # expecting case go
B="$3"
LOG="./filetemplate.log" # use parameters for long names.

# Generate some data with gzip and delete the temporary file.
echo "\"pramA\":\"$A\"  \"pramB\":\"$B\"" >> $B$A.tmp
rm -f ${LOG}.A; tar czf ${LOG}.A $B$A.tmp
rm -f $B$A.tmp
# Use paramaterise $names not $1 etc because you may want to do shift etc
searchFILE()
{
    outFile="$B-$A.data.out"
    case $cOPT in
        go) # This is zgrep | grep   NOT zgrep | zgrep
            zgrep -a "\"pramA\":\"$A\"" ${LOG}.* | grep -a "\"pramB\":\"$B\"" | head -z --lines=1 >> $outFile
            sort -u $outFile > ${outFile}.sorted  # sort unique on your output.
            ;;
        *) echo -e "ERROR second argument must be go.\n Usage: ./zgrp egA go egB"
            exit 9
            ;;
    esac

    echo -e "\n ============ Done: $0 $@      Fin. ============="
}
searchFILE "$@"

cat ${outFile}.sorted

Answer: I saw better performance results with zcat myZippedFile | grep whatever paradigm...


Multivariate (?) Probability Generating Function

Question: We have variables $X_1,X_2,X_3..$ which are i.i.d Bernoulli RVs with parameter $p$. Also, $N \sim Po(\lambda)$.
With this given, how can I find the PGF of $ Z = \sum_{i=1}^{N}X_i$?
Using rules of PGF, I worked the math out and I have
$G_z(s)=E(s^z)=E(s^{x_1+x_2+..+x_N})$
Then,
$E(s^{x_1+x_2+..+x_N}) = \prod_{k=1}^{N}E(s^{X_k})$
From this, we now see
$G_{X_1}(s) * G_{X_2}(s) * ... * G_{X_N}(s) = [G_X(s)]^N$
Solving this, I obtain $[G_X(s)]^N$, where $G_X(s)$ is a PDF of bernoulli.
I guess my question is, I'm not quite sure how to incorporate the fact that N is a poisson random variable. Obviously the exponent $N$ is dependent on poission... then "should" the exponent be $\lambda$ since our expected value for a poission RV is its parameter $\lambda$?
Also with this, then I think that $Z$ is a binomial random variable, but I'm not quite sure if $N$ makes any difference.
Thanks so much in advance!
Comment: Your essential mistake is the equality $E(s^{X_1+\cdots+X_N})=\prod_{k=1}^NE(s^{X_k})$. It is wrong because $N$ is a random variable, and not a constant. On LHS you find an expectation (which is just some real number, or function is $s$ if you like) and on RHS you find a random variable. That does not match. It is comparable with (wrongly) saying that $\mathbb EXY=X\mathbb EY$ where $X$ and $Y$ both denote random variables.
Answer: $$\mathbb Es^Z=\sum_{n=0}^{\infty}\mathbb E(s^Z\mid N=n)P(N=n)=\sum_{n=0}^{\infty}\mathbb E(s^{X_1+\cdots+X_n})P(N=n)=$$$$\sum_{n=0}^{\infty}G_X(s)^nP(N=n)=\mathbb E\left[G_X(s)^N\right]$$where $X\sim\mathsf{Bernoulli}(p)$ and $N\sim\mathsf{Po}(\lambda)$.
The second equality is based on independence of $N$ wrt the $X_i$. and the third on independence of the $X_i$.
Can you find $G_X(s)$ and  $\mathbb E\left[G_X(s)^N\right]$ yourself?
Comment: I worked out $G_X(s)$ and I have $G_X(s) = 1-p+2p$. I don't really follow why I need to find $E[G_X(s)^N]$ and not $[G_X(s)]^N$ as I have suggested above
Comment: You are asked to find the PGF of $Z$ which is a function. Not a random function.
Comment: The correct expression for $G_X(s)$ is $\mathbb Es^X=s^1P(X=1)+s^0P(X=0)=sp+1-p$. I hope that the $2$ in your comment is a typo. There are $4$ equalities in my answer. Do you understand (and agree with) all of them? If not then let me know which one you do not understand.
Comment: Yes, my 2 was a typo - I meant $1-p+sp$ as you have suggested. I follow your explanations and equalities, but the results do not seem to match with the way I worked it out - I'll edit my answer to fully show my thought process.


ComboBox not updating when ObservableCollection is modified in another View

Question: I am working on a little MVVM WPF project for practicing purposes and I have two windows with one view for each, one for displaying employees (MainWindow) and one for adding employees (AddPersonWindow).
In my MainWindow, there is a  ComboBox bound to an ObservableCollection and I can open the AddPersonWindow from a button in my MainWindow. However, if I add an employee to the ObservableCollection from the AddPersonWindow by clicking on the save button and executing the AddPerson() function, the ComboBox in the MainWindow is not updating. If I execute the very same AddPerson() function from the MainWindow, everything is fine and the ComboBox shows the new entry. What am I missing here?
Code:
Person.cs
class Person
{
    public string Surname { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
    public string HouseNumber { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string PhoneAreaCode { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
    public string FullName { get { return String.Format("{0}, {1}", Name, Surname); } }
}

PersonViewModel.cs
class PersonViewModel : INotifyPropertyChanged
{

    public CommandHandler ButtonClick { get; set; }

    public PersonViewModel()
    {
        CreatePerson();
    }

    //Combobox SelectedItem
    private Person _selectedPerson;
    public Person SelectedPerson
    {
        get { return _selectedPerson; }

        set
        {
            _selectedPerson = value;
            OnPropertyChanged("SelectedPerson");
        }
    }

    public ObservableCollection<Person> PersonList { get; set; } = new ObservableCollection<Person>();

    public void CreatePerson()
    {

        foreach (string line in File.ReadLines(@"C:\some_file.csv", Encoding.GetEncoding("iso-8859-1")))
        {
            string[] substrings = line.Split(',');
            Person person = new Person {
                Surname = substrings[0],
                Name = substrings[1],
                Street = substrings[2],
                HouseNumber = substrings[3],
                PostalCode = substrings[4],
                City = substrings[5],
                PhoneAreaCode = substrings[6],
                PhoneNumber = substrings[7],
                Email = substrings[8] };
                PersonList.Add(person);
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }

}

AddPersonViewModel.cs
class AddPersonViewModel : PersonViewModel
{

    public AddPersonViewModel()
    {
        ButtonClick = new CommandHandler(AddPerson);
    }

    public string EnteredSurname { get; set; }
    public string EnteredName { get; set; }
    public string EnteredStreet { get; set; }
    public string EnteredHouseNumber { get; set; }
    public string EnteredPostalCode { get; set; }
    public string EnteredCity { get; set; }
    public string EnteredPhoneAreaCode { get; set; }
    public string EnteredPhoneNumber { get; set; }
    public string EnteredEmail { get; set; }

    public void AddPerson()
    {

        Person person = new Person
        {
            Surname = EnteredSurname,
            Name = EnteredName,
            Street = EnteredStreet,
            HouseNumber = EnteredHouseNumber,
            PostalCode = EnteredPostalCode,
            City = EnteredCity,
            PhoneAreaCode = EnteredPhoneAreaCode,
            PhoneNumber = EnteredPhoneNumber,
            Email = EnteredEmail
        };
        PersonList.Add(person);

    }
}

CommandHandler.cs
class CommandHandler : ICommand
{

    Action ExecuteHandler;

    public CommandHandler(Action executeHandler)
    {
        ExecuteHandler = executeHandler;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public void Execute(object parameter)
    {
        ExecuteHandler();
    }

}

MainWindow.xaml.cs:
 public MainWindow()
    {
        InitializeComponent();
        DataContext = new PersonViewModel();
    }

AddPersonWindow.xaml.cs:
 public AddPersonWindow()
    {
        InitializeComponent();
        DataContext = new AddPersonViewModel();
    }

ComboBox in MainWindow.xaml:
<ComboBox Width="325" HorizontalAlignment="Left" Margin="7" Grid.Column="1" ItemsSource="{Binding PersonList}" DisplayMemberPath="FullName" SelectedItem="{Binding SelectedPerson}" IsTextSearchEnabled="True" TextSearch.TextPath="FullName" IsEditable="True" />

Button in AddPersonWindow.xaml:
<Button Width="100" Height="30" Margin="15" Grid.Row="3" Grid.Column="2" HorizontalAlignment="Right" IsEnabled="True" Command="{Binding ButtonClick}">Speichern</Button>

Comment: Are they using the same instance of `PersonViewModel`? Asuming that you are creating multiple `PersonViewModel/AddPersonViewModel` so you have multiple instances of `PersonList`. You should create one `AddPersonViewModel` and pass the instance to the other pages/windows. _(via constructor)_
Comment: I think you brought me on the right track. Must be because I create a `PersonViewModel` and an `AddPersonViewModel` in the code-behind (I added both code-behind files in the original post) and thus two separate `PersonList` instances are created.
Though I still haven't found a solution how to deal with this - will keep trying!
Comment: Yep, they don't share their `PersonList` thats why it doesn't work.
Answer: I didn't manage to share one PersonList instance to be shared between the tow view models, so I have decided to edit the underlying CSV file directly in the AddPersonViewModel:
 class AddPersonViewModel
{

    public CommandHandler ButtonClick { get; set; }

    public AddPersonViewModel()
    {
        ButtonClick = new CommandHandler(AddPerson);
    }

    public string EnteredSurname { get; set; }
    public string EnteredName { get; set; }
    public string EnteredStreet { get; set; }
    public string EnteredHouseNumber { get; set; }
    public string EnteredPostalCode { get; set; }
    public string EnteredCity { get; set; }
    public string EnteredPhoneAreaCode { get; set; }
    public string EnteredPhoneNumber { get; set; }
    public string EnteredEmail { get; set; }

    void AddPerson()
    {

        File.AppendAllText(@"C:\some_file.csv", "\r\n" +
            EnteredSurname + "," +
            EnteredName + "," +
            EnteredStreet + "," +
            EnteredHouseNumber + "," +
            EnteredPostalCode + "," +
            EnteredCity + "," +
            EnteredPhoneAreaCode + "," +
            EnteredPhoneNumber + "," +
            EnteredEmail,
            Encoding.GetEncoding("iso-8859-1")
            );

    }
}
}

To refresh the ComboBox in the view of the PersonViewModel class after a person was added in the other view, I implemented a method that can be executed by clicking on a button. For this, I use the follwoing method:
public void RefreshPersons()
    {

        PersonList.Clear();
        foreach (string line in File.ReadLines(@"C:\Users\c.philipp\Downloads\adressbuch.csv", Encoding.GetEncoding("iso-8859-1")))
        {
            string[] substrings = line.Split(',');
            Person person = new Person
            {
                Surname = substrings[0],
                Name = substrings[1],
                Street = substrings[2],
                HouseNumber = substrings[3],
                PostalCode = substrings[4],
                City = substrings[5],
                PhoneAreaCode = substrings[6],
                PhoneNumber = substrings[7],
                Email = substrings[8]
            };
            PersonList.Add(person);
        }

    }