Monte Carlo computation of probability of a subset of samples

Question: I would like to compute the probability for some subset $\omega \subset \Omega$  of events to occur, i.e. $P(\omega) = \sum_{x \in \omega} P(x)$ where I know $P(x)$ for all $x \in \Omega$, which are exponentially large sets.
For what it's worth, I already have Markov Chain Monte Carlo simulation set up for events within $\omega$, but computing $P(\omega)$ boils down to computing the normalization constant of that Markov Chain which is far from straightforward.
I am thinking that being able to generate all probabilities $P(x)$ should simplify this problem significantly. It seems to be a problem that must be quite ubiquitous but could not find any references. The most naive solution would be just to uniformly sample points $x_i$ in $\Omega$ and then sum $\sum_{i:x_i \in \omega} P(x_i)$. But this is clearly always $< P(\omega)$ and only converges to the exact value if all of $\Omega$ is sampled. I am having a hard time mapping this problem to usual MC problems because we are not strictly computing an expectation value here (i.e. we are not taking a mean of with respect to some distribution). Would appreciate any insights. Thank you!
EDIT: For clarification, in my problem I have bitstrings of a certain length $n$ (they constitute $\Omega$), and with each string we associate a certain probability $p$ which can be computed at low cost. So I can uniformly sample the space of all bitstrings $\Omega$ and associated probabilities. And I have constructed a Markov chain for events in $\omega$ alone. How do I compute $P(\omega)$?
Comment: You refer to a need to sample all of $\Omega$ in the naive approach to compute $P(\omega),$ but it's only $\omega$ that needs to be sampled; e.g. see [this posting](https://stats.stackexchange.com/a/257707/8030), which can be adapted to this case.
Comment: Yes. And 2) is what is called importance sampling in the literature, in case you need more material
Comment: A probability is the mean of an indicator function, so it is the usual MC problems...
Comment: Maybe I am being daft, but I do not see how this helps here? Sure, I can sample the uniform distribution over $\Omega$ and compute the mean of the indicator function which gives $P(\omega)$ if alle events in $\Omega$ where equally likely. But here each event has different probabilities?
Comment: In what manner is $P(x)$ known for all $x\in\Omega$? A formula?
Comment: Essentially, yes. Some function that is relatively inexpensive to compute (i.e. polynomial in $N$, whereas  $\Omega$ scales exponentially with $N$)
Comment: @r.e.s., thanks a lot for your suggestions. I have added an answer relying on your comments. Does this correspond to what you had in mind?
Comment: @Gâteau-Gallois Thanks for your help. Does 1) in my answer correspond to what you had in mind?
Answer: For future reference, here are two approaches based on the comments that seem to work both. Note that (2) seems much more efficient.

Build a Markov Chain for all events in $\Omega$ and then compute the expectation value  $\langle I_\omega \rangle$ of the indicator function $I_\omega(X) = 1$ if $X \in \omega$, and $=0$ else. Disadvantage of this is that it takes a long time to converge because we need to sample all of $\Omega$, and we are not making use of the fact that we already know the normalized probabilities.

I had actually looked into this earlier, but must have implemented this wrong in the first try -- we can use sampling only over $\omega$:
$$ P(\omega) = \sum_{x \in \omega} P(x) = \sum_{x\in \omega} \frac{P(x)}{Q(x)} Q(x) \equiv \langle \frac{P(x)}{Q(x)} \rangle_Q $$
where $Q(x)$ is some other probability distribution on $\omega$. Because it is cheap for me to uniformly sample $\omega$, I can pick $Q(x) \equiv 1/|\omega|$. Ideally I would like to use a more optimal $Q(x)$ (ideally $Q(x) \approx P(x)$) but I think the only way to sample from this $Q(x)$ directly is to use a Markov Chain algorithm, which however does not give me access to Q(x).


Perl matrix to hash conversion

Question: I'm trying to convert a big matrix (a tab separated file with different number of elements in each column) into a hash of arrays. In the first step, I succesfully load the file and using Test::CSV convert the columns of the data into lists, but in doing so, I noted that the length of each list is the number of elements corresponding to the larger column, i.e. for those columns with fewer elements, a blank space is present. This is my code so far:
#!/usr/bin/perl
use warnings;
use strict;
use Text::CSV;

my $csv = Text::CSV->new({
    sep_char => "\t",
});

open( LIST, "<", "testfile" ) or die "No esta el archivo\n";

while (<LIST>) {
     if ($csv->parse($_)) {
    my   @columns = $csv->fields();
        print "$columns[0]\t$columns[1]\t$columns[2]","\n";
    } else {
        my $err = $csv->error_input;
    }
}
close(LIST);

The input matrix has 20 columns and between 4500-8500 rows plus a header row (which ideally I would like to use as keys in the hash). For simplicity I build a "testfile" with three columns, no header and different number of elements (in the same format as the original input file). Here is the content of testfile:
1 1 2
2 2
  3 4
5 6
6 7
7 8 8
8 9

This is the output. I presume that the "Use of uninitializated value..." is related to the blank spaces.
1  1  2
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 3.
2  2
  3  4
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 5.
5  6
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 6.
6  7
7  8  8
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 8.
8  9
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 9.
Use of uninitialized value in concatenation (.) or string at blast.cruce.especies.pl line 16, <LIST> line 9.

Answer: The reason you're seeing those errors is you're pulling in lines similar to:
\t\t1

Which parses to the list:
( undef, undef, 1 )

Since you're pulling in a 0 width character to the field. The problem isn't the parsing, it's the printing. If you want to examine the contents after parsing use Data::Printer or Data::Dumper to format the line for output, which won't give you the errors where the undef values are interpolated.
Edit: Your code is correct:
#!/usr/bin/perl
use warnings;
use strict;
use Text::CSV;

my $csv = Text::CSV->new({
  sep_char => ",",
  });

while (<DATA>) {
        if ($csv->parse($_)) {
    my   @columns = $csv->fields();
          print "$columns[0]\t$columns[1]\t$columns[2]","\n";
          } else {
        my $err = $csv->error_input;
    }
}

__DATA__
1,1,2
2,2,
,3,4
5,6,
6,7,
7,8,8
8,9,

prints:
C:\>perl testcsv.pl
1       1       2
2       2
        3       4
5       6
6       7
7       8       8
8       9

(The changes are only to read from the DATA handle instead of a file.)
Comment: Hi Oesor. Im still dont try the Data::Printer or Dumper, but I change the tab separator in testfile for commas and change the sep_char to "," and now I cant print the matrix equal to the input.
Comment: I edited my post to show that your code does work properly with comma separators.
Comment: Nice edit. Just for reference, you have to make sure you have a comma at the end of the lines such as `6,7,`. Otherwise `@columns` will only have 2 elements and `$columns[2]` will be undefined and you'll get the same error..
Comment: Thanks Oesor for your help. Your mention to the \t\t1 pulling open my eyes.
Answer: here again with some issues. I simplify the above code to this:
#!/usr/bin/perl
use warnings;
use strict;
use Text::CSV;
use Data::Dumper;
$Data::Dumper::Indent=0;

my @columns;
my %matrixhash;
my $csv = Text::CSV->new( { sep_char => "," } );

open( LIST, "<", "testfile.csv" ) or die "No esta el archivo\n";

while (<LIST>) {
    if ( $csv->parse($_) ) {
        @columns = $csv->fields();

%matrixhash=(
    a=>$columns[0],
    b=>$columns[1],
    c=>$columns[2]
);
}
        print Dumper \@columns;
        print "\n";

}
print "Printing Hash: ",Dumper \%matrixhash;
close(LIST);

The output is:
$VAR1 = ['1','1','2'];
$VAR1 = ['2','2',''];
$VAR1 = ['','3','4'];
$VAR1 = ['5','6',''];
$VAR1 = ['6','7',''];
$VAR1 = ['7','8','8'];
$VAR1 = ['8','9',''];
$VAR1 = {'c' => '','a' => '8','b' => '9'};

which correspond to the lines of my matrix and the hash indeed is the last line. In order to continue my donwstream analysis I need a collection of hashes which contain the column header as keys and the columns information from the matrix as values and of course without the blanks. For example, for the first column of the matrix, the hash will be: a=> {1,2,5,6,7,8). So, my second thought was, what happens if I transpose the matrix?:
$VAR1 = ['1','2','','5','6','7','8'];
$VAR1 = ['1','2','3','6','7','8','9'];
$VAR1 = ['2','','4','','','8',''];
Printing Hash: $VAR1 = {'c' => '4','a' => '2','b' => ''}

This is more close to my need, but still have the hash problem. And of course probably I will need transpose the matrix previous in the code (the example was handly transposed).
Again, all help is welcome.
Christian.
Comment: You should ask a new question as a new question, not the answer to the previous one. You're looking for something along the lines of `if (defined $columns[0]) { push @{$matrixhash{a}}, $columns[0] }`, though, which will create a hash value containing an arrayref similar to {a => [1, 2, 5, 6, 7, 8] }
Comment: Oh. I dont see the question as new question, because the initial problem ("I'm trying to convert a big matrix (a tab separated file with different number of elements in each column into a hash of arrays") is still present. But your rigth, from script perspective is a new question. My mistake. I will follow your indication and also publish as new question. Thanks.

Perl matrix to hash conversion


Dynamically adding a website with an HTTPS binding pointing to a dynamically generated self-signed certificate

Question: I'm currently attempting to dynamically add a new website using the Microsoft.Web.Administration library provided by IIS7+. This is going to be a part of an installation process in which a self-signed certificate needs to be added and bound to the HTTPS binding of this website.
My research took me to this post on StackOverflow which makes use of the BouncyCastle API: Generate self signed certificate on the fly. I have tried to replicate the functionality provided by IIS administration tool for creating such a certificate by making slight alterations to the code. I have modified the signature algorithm in both methods from SHA256WithRSA to SHA1WithRSA. I am also passing the SubjectName and IssuerName as the local machine's name using Dns.GetHostEntry("127.0.0.1").HostName. I'm also setting the FriendlyName property of the X509Certificate2 object. The final modification involved passing the sl parameter of the addCertToStore method as StoreLocation.LocalMachine.
The following is a snippet of the code for dynamically creating the website and adding an HTTPS binding passing the cert.GetCertHash() data as a parameter to the Site.Bindings.Add(...) method which takes in the Binding Information, Certificate Hash and the Certificate Store Name (see MSDN documentation):
using (ServerManager iisManager = new ServerManager())
{
    Site testSite = iisManager.Sites.Add(siteName, targetDir, sitePortNumber);
    testSite.Bindings.Add("*:" + sitePortNumber + ":", certificateHash, "MY");
    iisManager.CommitChanges();
}

The issue is that when attempting to commit the changes in IIS I get the following COMException:

A specified logon session does not exist. It may already have been terminated. (Exception from HRESULT: 0x80070520)

Checking what happened in IIS it seems that the certificate is present but it is not being mapped correctly:

In the image linked above, the topmost certificate is the one being added dynamically i.e. the one mentioned in my post. The last one is a sample self-signed certificate created through the IIS administration tool.

The image linked above shows that the mapping between the HTTPS binding and the newly created SSL certificate failed.

Personal Certificates under Local Computer -> Personal:
This image contains a list of personal certificates which are present in certificate manager under the Local Computer section. The top one is the dynamically generated one whilst the bottom one was created using the IIS administration tool.

Above are the certificate details of the self-signed certificates created using the IIS administration tool (left hand side) and the dynamically generated one (right hand side).
Some of the most notable differences between the two of them are:

Missing Key Usage and Enhanced Key Usage details in the dynamically generated one.
The certificate status and the icon indicating that there is something wrong with it.

So the question is what is wrong with the code involving the creation of the self-signed certificate which is causing the mapping to the new IIS website to fail?
Thanks
Answer: Moved the SSL certificate from current user to local machine and it worked.
Here is my code to add the certificate.
I also noticed X509KeyStorageFlags.MachineKeySet was the only flag that did not produce the error.
string certPath = "c:/test2/certName.p12";
string certPass = "TestPassword";

// Create a collection object and populate it using the PFX file
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.MachineKeySet);

foreach (X509Certificate2 cert in collection)
{

    if(cert.Subject.Equals("CN=TestServer, O=Test"))
    {
        X509Store store1 = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        store1.Open(OpenFlags.ReadWrite);
        store1.Add(cert);
        store1.Close();
    }

    if (cert.Subject.Equals("CN=TestClient, OU=Applications, O=Test"))
    {
        X509Store store1 = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store1.Open(OpenFlags.ReadWrite);
        store1.Add(cert);
        store1.Close();
    }
}

And here is my code to create the binding
ServerManager serverManager = new ServerManager();
var site = serverManager.Sites["Default Web Site"];
site.Bindings.Add("*:443:TestClient", certificate[0].GetCertHash(), "MY");
//  site.Bindings.Add("*:443:TestClient", "https");
serverManager.CommitChanges();

Comment: `X509KeyStorageFlags.MachineKeySet` was the solution for me, thanks!


Cross-domain request to subdomain

Question: I have front-end part (js) on http://example.com and back-end (REST API) on http://api.example.com. Is it possible to make requests to back-end without OPTIONS request before each GET/POST etc request?
Comment: Possible duplicate of http://stackoverflow.com/questions/6277926/javascript-access-from-parent-domain-to-subdomain
Comment: It is not duplicate. CORS already configured and working properly. But it adds some lag for each request, because it sends OPTIONS request before each request. So now I'm looking for a way to get rid of CORS.
Comment: For `CORS` request `OPTIONS` is mandatory. The time for `OPTIONS` is cosmetic. I mean won't take much time.
Comment: It takes 250ms on each OPTIONS request in my case (server physically pretty far from client).
Answer: You cannot get rid of the OPTIONS request unleess you don't send any data, and don't send custom headers.
According to Why am I getting an OPTIONS request instead of a GET request?
The OPTIONS request will be made if you send data with Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain.
Also, as stated there, the OPTIONS request will be made if you send custom headers.
So in order to avoide the preflight, you'll be forced to NOT do any of those things.
This is all because the idea is to first check if it the CORS will be allowed or not and you don't send any data to a server that you don't want to send.
Comment: Can I found somewhere a list of "non-custom" headers? For example, I'm using `WWW-Authenticate`, is it counts like custom?
Comment: That is not a custom header. You could check here https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Comment: Could you give me a tip, what is wrong with my GET request? https://gist.github.com/Crabar/25308f5b9e283c65b258d2402757a9da
Comment: What type of request are you making? `POST` with body?
Comment: GET without body. Don't look at ContentType I added it just to check if this change something.
Comment: I found [this doc](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). There are small list of supported headers. It doesn't contain `Authenticate` for example.

Cross-domain request to subdomain


How to update softlinks when folder is updated?

Question: I have two directories 'original' and 'soft'.
I have soft links on all the files of the original directory.
ln -s original/* soft/

However, on the regular basis files are getting copied and deleted daily basis. However new links are not getting added as well as links of on the deleted files are not getting deleted.
How can I ensure that all the links get deleted when the file is deleted? and links get added when files are added.
PS: I don't want to achieve this with something like this ln -s original/ soft
Answer: If you don't want to have soft itself be a symbolic link to original, then the most straightforward approach is to have a cron job that deletes all of the symbolic links in soft, and recreate the symbolic links based on what is in original.  Depending on the frequency of the updates, you could run that cron job every minute, every hour, every day, ...
Hope this helps.
Comment: It would help to add some detail, like how would you delete all the symbolic links, and what would the cron job look like? For the former, I'm thinking something like `find /path/to/original -type l -delete`.


For each $\epsilon>0$ there is such $\delta>0$, s.t. $|x-x_0|<\epsilon$ $\Rightarrow$ $|f(x)-f(x_0)|<\delta$. What does it mean?

Question: We know  that $\lim_\limits{x\to x_0}f(x)=f(x_0)$ means that: for each $\epsilon>0$ there is such $\delta>0$, s.t. $0<|x-x_0|<\delta$ $\Rightarrow$ $|f(x)-f(x_0)|<\epsilon$.
what does the following expression mean?
for each $\epsilon>0$ there is such $\delta>0$, s.t. $|x-x_0|<\epsilon$ $\Rightarrow$ $|f(x)-f(x_0)|<\delta$.

Is $f$ continuous at $x_0$?
What quality of $f$ does the above-mentioned definition describe?

The lecturer gave is this new definition and told us to think about it, is that some kind of introduction to Uniform Continuity?
Comment: By continuous at $a$, do you mean $x_0?$
Comment: Between the two statements, $\epsilon$ and $\delta$ are permuted. Is it on purpose?
Comment: yes! its on purpose. and I corrected the $a$.
Comment: @FirasAliAbdelGhani I apologize for my earlier response. The comment was true. This is not the definition of absolute continuity; $\epsilon$ and $\delta$ are reversed.
Answer: What it states is that for all $\epsilon > 0$ there exists $\delta > 0$ such that the value of $f$ on the interval $]x_0 - \epsilon, x_0 + \epsilon[$ is in the interval $]f(x_0) - \delta, f(x_0) + \delta[$.
The answer is that $f$ does not have to be continuous at $x_0$. Can you see why?
Comment: are you implying that it still can be not continuous and has like a value which is not on the graph put jumping a little bit higher but still this value inside the intercal $[f(x_0)-\delta, f(x_0)+\delta]$ ?
Comment: For example. $f$ could or could not be continuous. Really the values can be anything as long as they are on the interval $]f(x_0) - \delta, f(x_0) + \delta[$, so there is no reason to expect continuity.
Answer: There are many exercises based on randomly modifying the $\epsilon$-$\delta$ definition of limit to see what properties of a function they define.  This is one of them.
The modification here is that the roles of $\epsilon$ and $\delta$ are reversed.  The condition is stronger for larger $\epsilon$.   It is saying that $f$ is bounded on larger and larger intervals surrounding $x_0$, and in fact is bounded on every finite interval.  Two things to notice are that this property is weaker than being bounded on $\mathbb{R}$ and that it does not depend on $x_0$ although the definition was stated with $x_0$.
Nobody would express boundedness on finite intervals in this way deliberately, it is only for purposes of exercise on the definition of limit.
Answer: $f$ might not be continuous.
Take the example of the function defined as $$f(x)=\begin{cases}
0 & \text{ if } x= 0\\
\sin \frac{1}{x} & \text{ else}
\end{cases}$$
$f$ satisfies your criteria at $0$ (with $\delta=2$ for all $\epsilon$).
$f$ is always locally bounded at $x_0$.
Comment: It is not a local property, although it looks like that at first.
Comment: @zyx I don't understand your comment. $x_0$ seems to be fixed and $f$ is bounded in the neightborhood of $x_0$.
Comment: In arbitrarily large neighborhoods of x_0, so not dependent on x_0.
Answer: For the sake of defining limits, suppose $|f(x_0)|< \infty.$
Now consider all $x$ within some vicinity ($\epsilon$) of $x_0.$ The condition states that for these $x,$ the values of $f(x)$ differ from $f(x_0)$ by at most $\delta.$ Now $\epsilon$ can be any positive number, so this means $f$ cannot be "infinite distance" from $f(x_0),$ if that makes sense, except when $|x|=\infty$. In other words, $f$ is bounded near $x_0$ (near meaning within finite distance from it). So basically, the statement implies $|f(x)|<\infty$ when $|x|<\infty.$
Also, this does not imply $f$ is continuous. Consider, for example,
$$f(x) = \begin{cases} 0 &\mbox{if } x \leq x_0 \\1 &\mbox{otherwise} \end{cases}.$$ Clearly, $f(x)$ is locally bounded (in fact, globally bounded), but isn't continuous.
Comment: I think nothing is said about $f$, except that epsilon delta implication.
Comment: Well the epsilon delta implication also implies {$B(x_0,\epsilon) \Rightarrow B(f(x_0),\delta)$} which means $|f(x)|$ cannot be $\infty$ for all $x\in B(x_0,\epsilon).$ But now epsilon is any positive number, so that means $|f(x)|$ cannot be $\infty$ for all $x$ that is within finite distance from $x_0.$
Comment: I would agree that $f$ having finite values makes life easier, because assigning a meaningful value for $\lvert f(x) - f(x_0)\rvert$ for something like $f(x) = -\infty$ or dismissing it, is problematic. I would not go so far to say that such an $f$ is excluded.


GWT uiBinder.createAndBindUi(this) help

Question: I am new to Java GWT plugins.
In our code, we are using code like below,
In test1.java
public class RowResults extends Composite
{

   @UiField VerticalPanel vpnlWidgets;

   public RowResults()
   {

 uiBinder.createAndBindUi(this));
 getRows();
   }

   private void getRows()
   {

      for(RowDetails obj: RowDetailsArray)
      {
         RowWidget row= new RowWidget(obj);
      vpnlWidgets.add(row);
      }
   }
}

In test2.java
public RowWidget(RowDetails rowObj)
{

       uiBinder.createAndBindUi(this);
       this.Row = rowObj;
}

I have posted here some necessary code. In this code, if I have 10 elements in RowDetailsArray, then for each elements createAndBindUi is called. It seems somewhat slow also.
Is there any way to call uiBinder.createAndBindUi(this); function one time and use that for all the 10 elements.
Also, what will happen while calling createAndBindUi(this). Whether it convert ui.xml file to class file or some thing else.
Pls Correct me if I am wrong.,
Thanks in Advance.
Answer: I guess it depends on how complicated your RowWidget is. If it has no special styling, I would suggest to use a FlexTable instead and just insert rows in it. It is quite optimized.
Answer: Use This Code Format.
public class RowResults extends Composite{
    private static RowResultsUiBinder uiBinder = GWT.create(RowResultsUiBinder.class);
interface RowResultsUiBinder  extends UiBinder<Widget, RowResults> {}
    public RowResults(){
        initWidget( uiBinder.createAndBindUi( this ) );
        // put all your code here if you do not have any other constructor if you have put
        //the above line in that constructor in the begning.
}

GWT uiBinder.createAndBindUi(this) help


Java Swing JFileChooser append files to a JTextArea

Question: I have a browse button which opens a dialog where the user can view directories and files. I am having some trouble appending the files the user selects to a JTextArea. I am trying to do this so the user can select multiple files at a time. The files eventually will be submitted to an Oracle database.
The code I have used for the filechooser is here:
final JFileChooser fc = new JFileChooser();
        JList list = new JList();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
        File file = fc.getSelectedFile();

Can you please show me how to append the files to a JTextArea?
Thanks.
Edit:
I have added the following:
JButton btnBrowse = new JButton("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                final JFileChooser fc = new JFileChooser();
                fc.setMultiSelectionEnabled(true);
                JList list = new JList();
                fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
                     File file = fc.getSelectedFile();
                }
                for (File file : fc.getSelectedFiles()) {
                       log.append(file.getPath());
                    }
            }
        });

But when selecting browse and choosing multiple files and then selecting open the files are not being displayed within the text area.
Full Code:
package com.example.android.apis.appwidget;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.awt.Color;
import javax.swing.UIManager;

public class VFSTool extends JFrame {

    private JPanel contentPane;
      static private final String newline = "\n";
        JButton openButton, saveButton;
        JTextArea log;
        JFileChooser fc;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    VFSTool frame = new VFSTool();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Tool() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 499, 423);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JLabel lblVfsLoaderTool = new JLabel("Tool");
        lblVfsLoaderTool.setBackground(new Color(255, 255, 153));
        lblVfsLoaderTool.setForeground(UIManager.getColor("Button.darkShadow"));
        lblVfsLoaderTool.setFont(new Font("Copperplate Gothic Light", Font.BOLD, 25));
        lblVfsLoaderTool.setHorizontalAlignment(SwingConstants.CENTER);
        contentPane.add(lblVfsLoaderTool, BorderLayout.NORTH);

        JPanel panel = new JPanel();
        panel.setBackground(UIManager.getColor("Button.darkShadow"));
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(null);

        JButton btnBrowse = new JButton("Browse");
        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                final JFileChooser fc = new JFileChooser();
                fc.setMultiSelectionEnabled(true);
                JList list = new JList();
                fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
                     File file = fc.getSelectedFile();
                }
                for (File file : fc.getSelectedFiles()) {
                    log.append(file.getPath() + System.getProperty("line.separator"));
                    }
            }
        });
        btnBrowse.setBounds(107, 185, 97, 25);
        panel.add(btnBrowse);

        JLabel lblCategory = new JLabel("label1");
        lblCategory.setForeground(UIManager.getColor("Button.background"));
        lblCategory.setBounds(12, 13, 82, 25);
        panel.add(lblCategory);

        JComboBox comboBox = new JComboBox();
        comboBox.setForeground(UIManager.getColor("Button.background"));
        comboBox.setBounds(91, 13, 113, 24);
        panel.add(comboBox);

        JLabel lblNewLabel = new JLabel("label2");
        lblNewLabel.setForeground(UIManager.getColor("Button.background"));
        lblNewLabel.setBounds(12, 50, 77, 25);
        panel.add(lblNewLabel);

        JComboBox comboBox_1 = new JComboBox();
        comboBox_1.setBounds(91, 50, 113, 25);
        panel.add(comboBox_1);

        JLabel lblLanguage = new JLabel("label3");
        lblLanguage.setForeground(UIManager.getColor("Button.background"));
        lblLanguage.setBounds(12, 114, 56, 16);
        panel.add(lblLanguage);

        JComboBox comboBox_2 = new JComboBox();
        comboBox_2.setBounds(91, 110, 113, 25);
        panel.add(comboBox_2);

        JCheckBox chckbxIncludeExt = new JCheckBox("include");
        chckbxIncludeExt.setForeground(UIManager.getColor("Button.background"));
        chckbxIncludeExt.setBackground(UIManager.getColor("Button.darkShadow"));
        chckbxIncludeExt.setBounds(12, 219, 113, 25);
        panel.add(chckbxIncludeExt);

        JButton btnSubmit = new JButton("Submit");
        btnSubmit.setBounds(107, 264, 97, 25);
        panel.add(btnSubmit);

        JTextArea textArea = new JTextArea();
        textArea.setBounds(240, 14, 219, 220);
        panel.add(textArea);
    }
}

Comment: `package com.example.android..`  Android?
Answer: Enable multi-file selection using JFileChooser#setMultiSelectionEnabled, then iterate through all files returned from getSelectedFiles, appending the output of getPath to your JTextArea
if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(list)) {
    for (File file : fc.getSelectedFiles()) {
       myTextArea.append(file.getPath() + System.getProperty("line.separator"));
    }
}

Edit:
You should be getting a stacktrace like this
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at swing9.VFSTool$2.actionPerformed(VFSTool.java:81)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)

This is telling you that something is not initialized, i.e. your JTextArea log
Not only has this not been initialized but hasnt been added to the frame. You probably want the text displayed in textArea instead. This is only available in the scope of the constructor so will need to declared as a class member variable.
private JTextArea textArea;

Comment: Thanks this has worked I think, but it doesn't actually show the files that have been opened in the text area.
Comment: Without seeing the code we cant diagnose the problem here - post a [Short, Self Contained, Correct (Compilable), Example](http://sscce.org/)
Comment: The problem is in the code youre not showing us - Please post complete code


Reference all table boxes to their individual rows and column as formula

Question: For example I have a huge table of rows and columns.
I need to write a formula for the table such that the values of each box belongs to their particular row and column value.
 A | B | C |D  | E | F | G | H | I | J | K | L | M |N ...
 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |10 | 11| 12|13...
 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 ...
 2 | 2 | 4 | 8 | 16| 32| 64|...
 3 | 3 |
 4 |
 5 |
.
.
.

For example, B3 has the formula 'A3^B1' giving it a value of 3, C3 has the formula 'A3^C1'. But how do i copy the formula into the rest of the boxes? For now I have to manually key in the formulas for the boxes but that is too inefficient.
Is there a way for to compute the value just by referencing all the boxes formula to their individual column value and row value?
Comment: You won't have to extend that very far to hit a stack overflow (i.e a **#NUM!** error)!
Comment: Is there a way for me to avoid that error?
Comment: No! 64-bit Excel may delay it but it will still happen.
Comment: Could it be some thing to do with the format of the cells? I have like a 200x200 table of values to compute.
Answer: Try this formula in B2 and then copy it to the other cells: =$A1^B$1.
The $ before a column and/or row will fix the column/row when copying the formula to other cells!
Pro tip: when editing/entering the formula, press F4 to toggle between the multiple $ states!
And as an alternative - you can even remove the first row and column, and simply place this formula in A1: =ROW()^COLUMN() and you'll get the same result matrix!
Comment: Well it works. But I got a `#NUM!` error. Could it be that the result is too large for excel to handle? Or something else?


What bitrate can I expect with MPEG?

Question: What bit-rate (approximately) can I expect MPEG encoders to produce for 160x120 "ok-quality" webcam stream?
How much CPU-demanding will the encoding be? The decoding?
Are there any better encoding formats for that purpose? (In terms of bit-rate or CPU)
Answer: 256 KBps is enough for QSIF (160x120, 25 fps) in MPEG2.
Any modern CPU (since Pentium IV) can encode and decode it in realtime.
There are hardware solutions (like Compro VideoMate H900 and E800 series), which cost about 100$ and up to 8 boards can be installed per PC.
Using them, you can get 8 full-size streams at once, to say nothing of QSIF.
MPEG4 can probably yield better results in terms of bandwidth, but it's more sensitive to the packet drops in the channel.
As for the sound, if you need telephony quality, you can use aLaw or uLaw codec, which require 64 kbps per channel and are not a problem even for a Casio calculator.

What bitrate can I expect with MPEG?


my django website says "We're sorry, but something went wrong" in production

Question: my django website was working in debuging mode but when I put it on the server and turned it to production mode, my website shows me the error:

We're sorry, but something went wrong. The issue has been logged for
  investigation. Please try again later.

I have checked out my settings, my passenger_wsgi.py file and I wrote it it this line
from myproject.wsgi import application

and also run the followed commands
python manage.py collectstatic
python manage.py migrate
python manage.py makemigrations

cpanel Error log says
[ E 2019-05-09 08:11:44.4868 967877/T1m age/Cor/App/Implementation.cpp:221 ]: Could not spawn process for application /home/muntadar/creepy-surprise: The application process exited prematurely.
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 63, in check_sqlite_version
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 66, in <module>
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/utils.py", line 201, in __getitem__
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/options.py", line 204, in contribute_to_class
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 117, in __new__
 App 978910 output:
   File "/home/muntadar/creepy-surprise/levels/models.py", line 3, in <module>
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
 App 978910 output:
   File "/home/muntadar/creepy-surprise/creepy_surprise/wsgi.py", line 7, in <module>
 App 978910 output:
   File "/home/muntadar/creepy-surprise/passenger_wsgi.py", line 1, in <module>
 App 978910 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/imp.py", line 171, in load_source
 [ E 2019-05-08 20:20:46.4873 828707/T1r age/Cor/App/Implementation.cpp:221 ]: Could not spawn process for application /home/muntadar/creepy-surprise: The application process exited prematurely.
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 63, in check_sqlite_version
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 66, in <module>
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/utils.py", line 110, in load_backend
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/utils.py", line 201, in __getitem__
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/options.py", line 204, in contribute_to_class
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 117, in __new__
 App 885800 output:
   File "/home/muntadar/creepy-surprise/levels/models.py", line 3, in <module>
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/importlib/__init__.py", line 127, in import_module
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
 App 885800 output:
   File "/home/muntadar/creepy-surprise/creepy_surprise/wsgi.py", line 7, in <module>
 App 885800 output:
   File "/home/muntadar/creepy-surprise/passenger_wsgi.py", line 1, in <module>
 App 885800 output:
   File "/home/muntadar/virtualenv/creepy-surprise/3.7/lib64/python3.7/imp.py", line 171, in load_source

and the problem still exist
what else can I do?
.
Comment: What does the error log say?
Comment: review the question
Comment: Please use a code block for ascii text output such as a logfile. Quoted text is unreadable for output like this.
Comment: Does it work in production mode with the development server?
Comment: What is line 3 of levels/models.py?
Comment: yes it's working in production mode with development server
Comment: line3 of levels/models.py : class Story(models.Model):
Answer: i got same problem:
-- first check is you pass dubug to False in production
-- try send your passenger_wsgi.py configuration file here, check if it point django settings correctly
-- verify your different admin file, check if u use correct syntax to register a model. That's was my error, and i didn't know why, my server send me that course of that


Calculating $\int_0^{\pi/2} \frac{\ln(\sin x+\cos x)}{\sin x\cos x}\, dx$

Question: How would you evaluate the following integral:
$$\int_0^{\pi/2} \frac{\ln(\sin x+\cos x)}{\sin x\cos x}\, dx$$
I can't see any helpful by parts or substitution ideas, e.g. $u=\sec x$ or $u=\csc x$ since the other integral that comes out of by parts don't evaluate nicely, so any help would be much appreciated. The integral should come out nicely as it's part of a problem (at roughly first year undergraduate level) that says show a particular integral comes to something nice, which I've simplified to this.
Comment: Where does this problem come form?  Do you have any reason to believe that it evaluates to something "nice"?  Have you actually tried integration by parts?  or a substitution?  If so, where did you get stuck?  At what level are you encountering this problem (the solution given to a student studying integral calculus for the first time will look different than the solution given to someone that finds this integral as an auxiliary step in solving a differential equation, for example)?  Your question requires additional context.
Answer: Rewrite the integral as: $$\int_0^\frac{\pi}{2}\frac{2\ln(\sin x+\cos x)}{2\sin x\cos x}dx=\int_0^\frac{\pi}{2}\frac{\ln(1+\sin (2x))}{\sin (2x)}dx=\int_0^\frac{\pi}{2}\frac{\ln (1+\sin x)}{\sin x}dx =\frac{\pi^2}{8}$$ For the last integral look here and take $a=1$.
Comment: Double angle formulae for sine on bottom and using log rules to move the inside to square sinx +cosx gives the first equality
Comment: @DineshShankar as OP said I have used the fact that $a \ln b = \ln(b^a)$. $(\sin x+ \cos x)^2= \sin^2 x+\cos ^2 x +2\sin x\cos x= 1+\sin (2x)$
Comment: Sorry if I'm missing something obvious but how did 2x suddenly become x
Comment: Sorry but how did you know that $$\int_0^\frac{\pi}{2}\frac{2\ln(\sin x+\cos x)}{2\sin x\cos x}dx=\int_0^\frac{\pi}{2}\frac{\ln(1+\sin (2x))}{\sin (2x)}dx?$$
Comment: @GinnyMothballWong by letting $2x=t$ one gets $$\frac12 \int_0^\pi \frac{\ln(1+ \sin x)}{\sin x}dx$$ now split it from $0 \to \frac{\pi}{2} \to \pi$ and  in the second part ($\frac{\pi}{2} \to \pi$)  put $x-\frac{\pi}{2}=t$ to get $$\frac12 \int_0^\frac{\pi}{2} \frac{\ln(1+ \cos t)}{\cos t}dt$$ finally let $\frac{\pi}{2}-t =x$ to show that the second part of the integral is equal to the integral from $0$ to $\frac{\pi}{2}$. You could also look at the sine graph after you substituted $2x=t$.
Answer: I do not know if this hint is conclusive, but this is what I got:
\begin{align*}
\frac{\ln(\sin(x)+\cos(x))}{\sin(x)\cos(x)} & = \frac{\ln[\left(\tan(x) + 1\right)\cos(x)]}{\cos^{2}(x)\tan(x)}\\
& = \frac{\ln(\tan(x)+1)\times\sec^{2}(x)}{\tan(x)} + \frac{\ln(\cos(x))\times\sec^{2}(x)}{\tan(x)}
\end{align*}
On the one hand, the substitution $u = \tan(x) + 1$ results into
\begin{align*}
\int\frac{\ln(\tan(x)+1)\times\sec^{2}(x)}{\tan(x)}\mathrm{d}x = \int\frac{\ln(u)}{u-1}\mathrm{d}u
\end{align*}
On the other hand, since $\sec^{2}(x) = 1 + \tan^{2}(x)$, the same substitution results into
\begin{align*}
\int\frac{\ln(\cos(x))\times\sec^{2}(x)}{\tan(x)}\mathrm{d}x = \int\frac{\ln(2 - 2u + u^{2})^{-1/2}}{u - 1}\mathrm{d}u = \frac{1}{2}\int\frac{\ln(2-2u+u^{2})^{-1}}{u-1}\mathrm{d}u
\end{align*}
Thus the problem to be solved is equivalent to
\begin{align*}
\int_{0}^{\pi/2}\frac{\ln(\sin(x)+\cos(x))}{\sin(x)\cos(x)}\mathrm{d}x =
\frac{1}{2}\int_{1}^{+\infty}\ln\left(\frac{u^{2}}{2-2u+u^{2}}\right)\frac{\mathrm{d}u}{1-u}
\end{align*}
Answer: Note that if you use Weierstrass substitution you get:
$$I=2\int_0^1\frac{(1+t^2)(\ln(1+2t-t^2)-\ln(1+t^2))}{2t(1-t^2)}dt$$
This may work
EDIT
note:
$$\sin(x)+\cos(x)=\sqrt{2}\sin\left(x+\frac{\pi}{4}\right)$$
also, we know the rule:
$$\int_a^bf(x)dx=\int_a^bf(a+b-x)dx$$
but when applied to the original integral it does not help us.
Writing our integral as:
$$I=\int_0^{\pi/2}\frac{\ln\left(\sqrt{2}\sin\left(x+\frac{\pi}{4}\right)\right)}{\sin(x)\cos(x)}dx$$
we can now apply the substitution:
$$u=x+\frac{\pi}{4}$$
to obtain:
$$I=2\int\limits_{\pi/4}^{3\pi/4}\frac{\ln\left(\sqrt{2}\sin(u)\right)}{(\sin u+\cos u)(\sin u-\cos u)}du=2\int\limits_{\pi/4}^{3\pi/4}\frac{\ln\left(\sqrt{2}\sin(u)\right)}{\sin^2(u)-\cos^2(u)}du$$
now we would like to substitute with the $\sqrt{2}\sin(u)$ but this doesn't work with the limits. So we are going to try using the substitution $v=\sqrt{2}\sin(u)$ and split the integral up into two parts.
$$I_1=2\int\limits_{\pi/4}^{\pi/2}\frac{\ln(\sqrt{2}\sin(u)}{\sin^2(u)-\cos^2(u)}du=\sqrt{2}\int_1^\sqrt{2}\frac{\ln(v)}{\frac{v^2}{2}-\frac{2-v^2}{2}}dv=\sqrt{2}\int_1^\sqrt{2}\frac{\ln(v)}{v^2-1}dv$$$$
=\sqrt{2}\int_1^\sqrt{2}\frac{\ln(v)}{2(v-1)}-\frac{\ln(v)}{2(v+1)}dv$$
and the same can be done for the second part.


Dial passcode from bridge conference call using objc

Question: I need to dial passcode automatically after dialing conference number from an iPhone app. I tried to make the call and the call gets connected. How can I dial the passcode automatically after the call get connected?
Answer: You can include the character 'p' to introduce a 1 second delay. Digits after the first pause will be sent as post-dial digits using DTMF.
So if your conference access number was 1800123456 and the access code was 987654 then you would specify something like.
<code>Tel://1800123456pp987654
</code>
You may need to add more p characters - it can be a bit trial and error.
See RFC2806


android checkbox is not checked for custom listview when listview is in scrollview

Question: i have implemented custom list view with check box and textviews.  It is working fine when list view is not in scroll but if the rows are increased then listviews is in scroll view  that time when i click on check box the checked mark is not staying. here is my code, Please suggest me if anything wrong in that code
public class ArchivedAdapter extends ArrayAdapter<MessageBean> {
final ArrayList<MessageBean> updatedList = new ArrayList<MessageBean>();
private List<MessageBean> list;
private TextView officenameView, sentOnView, messageView;
public final static String MY_ACTION = "com.android.threeptalk.broadcast";
private boolean isDeleted = false;
int count = 0;
HashMap<Integer, CheckBox> checkList = new HashMap<Integer, CheckBox>();

public ArchivedAdapter(Context context, int resourseID,
        List<MessageBean> list) {
    super(context, resourseID, list);
    this.list = list;

}

@Override
public int getCount() {
    return list.size();
}

@Override
public MessageBean getItem(int arg0) {
    return list.get(arg0);
}

@Override
public long getItemId(int arg0) {
    return arg0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    View row = convertView;
    LayoutInflater inflater = (LayoutInflater) this.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    row = inflater.inflate(R.layout.archievedmsgrow, parent, false);
    row.setId(position);
    Object obj = getItem(position);
    if (obj instanceof MessageBean) {
        final MessageBean message = (MessageBean) obj;
        CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
        officenameView = (TextView) row.findViewById(R.id.officename);
        sentOnView = (TextView) row.findViewById(R.id.time);
        messageView = (TextView) row.findViewById(R.id.message);
        officenameView.setText(message.getOfficeName());
        checkList.put(position, checkBox);
        checkBox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                CheckBox c = (CheckBox) v;
                if (c.isChecked()) {
                    c.setChecked(true);
                    count++;
                    updatedList.add(message);

                } else {
                    c.setChecked(false);
                    count--;
                    updatedList.remove(message);
                    updatedList.size());
                }
                checkedCount(count, updatedList);
            }
        });

        row.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                rowclicked(message, position);

            }
        });
        sentOnView.setText(Common.getAppropriateTimeUsingTimeZone(message
                .getmDate()));
        if (message.getMessage() != null) {

            messageView.setText((message.getMessage()));

        } else {
            if (message.getMessageType().equals("OPTION")) {
                if (message.getOptions() != null
                        && message.getOptions().size() > 0) {
                    String data = message.getOptions().get(0);
                    if (data != null && !data.equals("")) {

                        messageView.setText(data);
                    }
                }
            }
        }

    }
    return row;
}

protected void messageSelected() {

}

protected void rowclicked(MessageBean message, int position) {
    // TODO Auto-generated method stub

}

protected void checkedCount(int count2, ArrayList<MessageBean> updatedList) {

}
}

`
Comment: Refer this site:http://lalit3686.blogspot.in/2012/06/today-i-am-going-to-show-how-to-deal.html
Answer: Try this example ListView with CheckBox Scrolling Issue
Answer: Seems like you are checking the check status of checkbox inside its onClickListener().
First define an Hashmap or SparseBooleanArray to save your selections.
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();

Then add the following code to your getView() method.
 CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
    checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            mSelection.put(position, isChecked);
        }
    });

    if (mSelection.get(position) != null) {
        if (mSelection.get(position))
            checkBox.setChecked(true);
        else
            checkBox.setChecked(false);
    }

Comment: Thanku puru.. my problem was resolved.. but now how can i call the checked count method. this method i am overriding in my activity class for displaying how many check boxes are checked.
Comment: Since the checkedCount method is defined inside your adaper, you can call it from your activity by using instance of your adapter . eg. mAdapter.checkedCount(). But if you want to return the number of checked values then you need to change the return type of that mathod to int and do actually return the size of your hashmap that you are using to store the selections.
Comment: when i am cliking the checkbox, if that is checked then i am increasing int value else i am decreasing, i am accesing this count in activity and displaying the count above the listview like 2 items are selected. when i unselected then 1 item is selected.
Comment: I couldnt understand your problem properly.But AFAIK, you shouldn't be using this 'counter' approach. I suggest you to implement a hashmap or better than that a SparseBooleanArray to store the selections as I've posted it in my answer.
Comment: If the answer helped you to solve your problem, please do accept or/and upvote the answer.
Answer: Try this, Assuming that you are using the Custom Adapter for your ListView, you will be able to set Tag for each Item inside your Adapter's getView(),
    public View getView(int position, View convertView, ViewGroup parent) {
    EvenViewHolder holdereven;
        if (convertView == null) {
            convertView = mInfaltor.inflate(R.layout.schedule_adapter_view,
                    null);
            holdereven = new EvenViewHolder();
            holdereven.time = (TextView) convertView
                    .findViewById(R.id.time);
            holdereven.title = (TextView) convertView
                    .findViewById(R.id.title);
            holdereven.des = (TextView) convertView.findViewById(R.id.des);
            convertView.setTag(holdereven);

        } else {
            holdereven = (EvenViewHolder) convertView.getTag();
        }

 static class EvenViewHolder {
    TextView time, title, des;

}
  }

Comment: Thanks for the suggestion, but what is that EvenViewHolder
Comment: Evenholder is class you can declare your custom layout view here. And use that object in your getvoew


how to map samba server drive to some local drive in C# using net use?

Question: how to map samba server drive to some local drive in C# using net use ?
And how to display them in Windows explorer like window ?
Any code snippet is highly appreciated.
Thanks in Advance.
Comment: Any body can help me on this ? pls...
Answer: I would recommend creating a batch file which contains the command you want to execute and then call this batch file from your C# application. This ensures if you need to change the net use command it is well encapsulated.
myBatchFile.cmd
net use z: \\server\resource

Application code
Process.Start(@"C:\myBatchFile.cmd");

You will need to add this using to your application.
using System.Diagnostics;

See here for more information on Process.Start:
Can you expand on "And how to display them in Windows explorer like window ?"


Dead end in pipes and legionella risk

Question: Today a plumber removed a sink from my house and sealed the two corresponding pipes at the location where they branch from the rest of the system. I expressly asked him to do this because I wanted to avoid having a dead run of pipe in my walls where bacteria could develop and cause serious health risks.
This is the end result. I marked in red where the dead leg starts for each of the pipes that got cut.

I've been reading online about the risk of bacteria such as legionella developing in the system and the recommendation seems to be that the dead leg's maximum length should be at most 1.5 times the diameter of the pipe itself. The dead legs shown in the picture are about 4 times the diameter.
I would like to understand whether this poses a health risk and whether I ought to ask the plumber to come and shorten the pipes.
Comment: Are you on a city water supply or well water? If in city water I would not be concerned at all. If on well water I would be worried about other things well before legionella, prior to 1976 this had not been discovered, how often do you actually hear about it? I am sure there will be some that say this is horrible, what about snow birds that don't use any water for months at a time you don't hear about them getting sick regularly. I see this as an opinion based question.
Comment: The water is treated and has a residual chlorine content that kills bacteria. I would not be concerned in the slightest.
Comment: Thanks. I am indeed on a city water supply. Are there additives in the water that prevent growth?
Answer: I would not be overly concerned about this unless it was the highest point in your plumbing or if you had low water pressure from the water supply (or if you are on well water).
These couple of inches extra should be flushed with water at all times and recycled with the rest of the water supply.    There is no reason to believe that the water in these small sections would remain stagnant, as they are just way too small to have "standing" water.
If you are concerned I would have the plumber not cap these at all, take out the nearest T and change it for a right angle.
Now there are a TON of benefits to block framing (from the materials I am guessing France or Italy) but plumbing and rerouting the plumbing... no.   We simply don't have many instances in the US like this because the plumbing is easily modified inside 2x construction.
Comment: Close, Netherlands :) but this is at a pretty high point in the plumbing. In the photo the pipes go into the ceiling and then route through the house. Does that create an extra concern?
Comment: Pretty high point or near/at the highest point?    Or level with highest point?
Comment: I'd say about 20 cm (7.8 inches) away from the highest point (I can't see how far the pipes go into the ceiling before they level off, but I assume not that far).
Comment: If it isn't on the highest end and you have a city water source that is pressurized you don't have an issue.     If you are that worried about it just have those two Ts replaced.   It is not easy taking off a wet T though and your plumber may have issues - so you are introducing two possible points of leaking in the future.

Dead end in pipes and legionella risk


ordering by match accuracy in t-sql using multiple where-like statements

Question: I am building a query such as this:
SELECT * FROM mytable
WHERE field like '%a%'
OR field like '%b%'
OR field like '%c'

I'd like to tag on an ORDER BY clause that orders by the amount of matches found--something along the lines of making some extra column in the result set that increments if a, b or c was found in the field and then order by that number.
is this possible without creating some kind of temp table?
Answer: You probably want to look into full text indexing if this table is at all large but a query without.
SELECT *
FROM   mytable
WHERE  field like '%a%'
        OR field like '%b%'
        OR field like '%c'
ORDER  BY CASE
            WHEN field like '%a%' THEN 1
            ELSE 0
          END + CASE
                  WHEN field like '%b%' THEN 1
                  ELSE 0
                END + CASE
                        WHEN field like '%c%' THEN 1
                        ELSE 0
                      END


JVM crash suddenly

Question: I have a simple javaFx application that worked a month ago perfectly.
Today i tried to run it and after a second the app crash and the windows say the Java has stopped, when i open the debugger it show me this message:
<code>Unhandled exception at 0x00007FFEC849349D (CompPkgSup.dll) in javaw.exe: 0xC0000005: Access violation reading location 0x0000000000000000.
</code>
I tried to reboot my computer and update the JDK but without any success, also run the eclipse with administrator privileges also without success.
Computer details: windows 10 64 bit, JDK jdk1.8.0_121 64 bit (tried also with jdk1.8.0_91 64 bit), eclipse neon.1 64 bit version.
Comment: That's a windows media player file. Have you checked for recent windows updates which might have changed this file?
Comment: Also, look at this: https://answers.microsoft.com/en-us/windows/forum/windows_10-performance/windows-media-player-exception-fails-with-code/ec3f0c51-309f-4fe3-8c52-c95b4f40d978 Might be related
Answer: This is not a Java issue, since the error is coming from a DLL.
Apparently at least Windows 10 has had issues due to a bad update related to codecs: https://www.reddit.com/r/sysadmin/comments/5zw5r3/heads_up_windows_10_kb4013429_makes_applications/
I'd imagine it's related, even if you're not on Win10.

JVM crash suddenly


How does Daisy track the monster?

Question: Daisy is a pet that Maggie gets in involve, and one of her main draws is that she's able to track the monster. However, I'm not sure exactly how she tracks the monster, which is an important detail for both hunters and monsters to know. I found this Reddit thread which states she just runs towards the newest footprint (including invisible sneaking ones) within 100m, but that's from when the game is still in beta, so I'm not sure if it's been changed.
How does Daisy's tracking work, and is there anything I can do to avoid being tracked (like running through water)?
Comment: I think it's still the same to be honest. Whenever you follow daisy there are footprints visible in front of her.
Answer: I've been the monster thousands of times and I can say out right: nothing I do as Goliath or Kraken stops Daisy from following me to one side and another. I use stealth, I run, I avoid birds, everything but she always follows me and can make a game very frustrating and out right boring.
So to be honest, I don't think Daisy has any sort of tracking skill like foot prints, smell or sound. She just follows the monster wherever it goes, which is why most players just depend on Daisy.
Answer: Daisy received a complete overhaul in stage 2, and the changes are listed below (source):

Daisy AI Overhaul

Always tracks the Monster directly, choosing the quickest path to the    Monster's current location. Will no longer follow tracks.
Within a certain distance of the Monster, she'll go into head-down mode and slow down to start sniffing around for the  Monster.
Daisy will point once she's honed in on the location of the Monster, signalling to the Hunters that the Monster is close and able
  to be captured inside a Dome.

How does Daisy track the monster?


How to reset Git LFS bandwidth?

Question: I have pushed files of size 876MB to git lfs, which showed me total 0.9 of free storage and bandwidth respectively, but, then I made few changes like deleted the old repo and uninstalled git lfs, since I reduced image size from 900MB to 800MB and then pushed back to my newly created git repo. When I saw the billing of lfs it showed 0/1GB (which was to be updated to 0.8) of storage but 1.7/1GB bandwidth and after Github disabled my 'git lfs' account. I actually want to remove the bandwidth storage i.e reset it to previous state. Is there any solution? Any suggestion highly appreciated
Comment: @Pranav, I contacted the GitHub support team and they refreshed my account to reset the limits as the quota limits didn't automatically reset after a month
Comment: Wait until the bandwidth limit resets - I think in 30 days. Or pay for Github Pro.
Comment: https://help.github.com/en/github/managing-large-files/about-storage-and-bandwidth-usage
Comment: Ok so I need to wait for 1 month?
Comment: @Pranav, Probably not, based on the image you have provided, ```Bandwidth quota resets in 0 days```
Comment: @SaurabhPBhandari did you mean 30 days?
Comment: OK was there any condition?
Comment: @SaurabhPBhandari Same situation here, the bandwidth won't reset automatically. Who did you contact exactly, and how long did the reset take for you?
Answer: Update  Sept. 2021, on the radmap (not yet delivered):

"Git LFS moves to metered billing"
LFS billing will switch from prepaid data packs to metered (pay for what you use).
The free entitlements (for example, 1GB storage and 1GB bandwidth) will be unchanged.
Customers will not be billed for LFS storage that occurred prior to the start of metering.
Intended Outcome
This change brings LFS billing in line with how Packages and Actions bill.
Instead of prepaying for a quota, you'll only be charged for what your repositories use.
How will it work?
We'll calculate how much storage is used and measure how much outbound bandwidth is used.
Each month, you'll be charged per-unit for each of these resources.

Original answer: Dec. 20219:
"About storage and bandwidth usage" from GitHub does mention:

When you download a file tracked with Git LFS, the total file size is counted against the repository owner's bandwidth limit.
Git LFS uploads do not count against the bandwidth limit.

So you can not remove or reset a bandwidth: it is already taken by your past downloads.

For example:

If you push a 500 MB file to Git LFS, you'll use 500 MB of your allotted storage and none of your bandwidth. If you make a 1 byte change and push the file again, you'll use another 500 MB of storage and no bandwidth, bringing your total usage for these two pushes to 1 GB of storage and zero bandwidth.
If you download a 500 MB file that's tracked with LFS, you'll use 500 MB of the repository owner's allotted bandwidth. If a collaborator pushes a change to the file and you pull the new version to your local repository, you'll use another 500 MB of bandwidth, bringing the total usage for these two downloads to 1 GB of bandwidth.

Plus:

Forking and pulling a repository counts against the parent repository's bandwidth limit.

So if your repository was forked, you don't even have to do anything for your bandwidth to be used.
Comment: So can I upload images to newly created repo or I have to wait 30 days for auto reset?
Comment: @Pranav as I mention in the answer, bandwidth is only about download. But I suspect since one of the two Git LFS limits was reached, that might affect your account for the month indeed.
Comment: @VonC Thank you. This is what I had in mind and ended up doing this way. There will be problems when rebasing due to commit hashes but anyway. Nothing else comes to my mind as a temporary solution. I was just trying to find an "error-proof" out-of-box solution
Comment: @Pranav upload yes, but not much. Download no: the limits are per GitHub account, not per repository.
Comment: What is download about? Well if I upload it what about bandwidth? As github has disabled my git lfs account
Comment: @Pranav Was your repository forked by others?
Comment: 1 GB bandwidth is like saying don't edit and push any file that is over 1KB. I mean even their 5GB bandwidth is nothing. How the hell they came up with such a low limits. Imagine you edit 500 MB file in 10 commits and boom you are out of bandwidth. This is literally saying we created LFS just for fun
Comment: @Farid I suspect this was initially to avoid DDoS and service abuse. The [billing](https://docs.github.com/en/billing/managing-billing-for-git-large-file-storage/about-billing-for-git-large-file-storage) would limit the use of LFS to motivated users only. You also [have releases](https://docs.github.com/en/repositories/working-with-files/managing-large-files/about-large-files-on-github#distributing-large-binaries=)
Comment: @VonC That is great that they have it. But what if you want to use LFS for, let's say, screenshot testing? We have lots of screenshots on different screen resolutions and we are trying to keep source screenshots outside the repository. Since we are talking about large files, this can be use case example for LFS too. I have been trying to work around these limits with `git annex` but CI fails because major git services doesn't support it, anyway this was outside scope
Comment: @Farid You need to store those screenshot in another external referential (like an S3 bucket, like the [addpowerpoint screenshot service does](https://www.addpowerpoint.com/save-screenshots-to-aws-s3-bucket). And your pipeline would need to connect to that external referential to retrieve them (no native integration with a Git repository in that case, but a good workaround nonetheless).
Comment: Sorry I missed one word and it changed gist of my question :) . I meant screenshots for screenshot testing (Android). Since screens can change from one commit to other we need them to be stored in VCS backed storage
Comment: @Farid The gist of my comment remains. You need to control your external referential yourself. You can store those screenshots in a folder named after a Git commit, allowing you to retrieve the right version of those screenshots based on your Git commit. That would essentially emulate what Git LFS does for you.
Comment: @Farid True, rebase need to be addressed: a rebase could generate new commits entry to S3, but with as "content" the reference of the old commit rebased. That way, by indirection, you can retrieve the artifacts.

How to reset Git LFS bandwidth?


Rails Has and Belongs To Many Associations

Question: My question has to do with Associations.  Forgive me as I am just learning this.
I have two tables (parent & child).  I have set up the associations where the parent table is set to has_many children and the child table has one parent with foriegn id set to parent_id.  This is working fine.
My question is that I want to create a family view that shows both parents and children together and associated with each other.  So it would look like this:
Parent Name

Child Name
Child Name

I am pretty sure I need to create a family table and do a has_and_belongs_to_many association but not sure how to show the two together like above
Hope this makes sense.
Comment: I think something went wrong with your association if you define in your child model child has one parent then child_id should be foreign key in your parents table .
Answer: If you just want to show parents and their children at view you don't need to create new table, just do as below:
In your Parents controller's index action( I am considering that you want to show all the parents with their children so I am using index action ) :
def index
  @parents= Parent.all.includes(:children)
end

Then on your index.html.erb view :
<% @parents.each do |parent| %>
  <%= parent.name%>

  <% parent.children.each do |child| %>
    <%= child.name%>

  <% end %>
<% end %>

Considering that you have define association between you Parent an Child model
Answer: class Parent
 has_many :children
end

class Child
 belongs_to :parent
end

In controller
@parent = Parent.find(params[:id]).includes(:children)

In view
<% @parent.children.each do |child| %>
  <%= child.name %>
<% end %>

Comment: Considering the N + 1 queries problem, you could include children while fetching the parent like this: `@parent = Parent.includes(:children).find(params[:id])`


Wiring an inverter into an RV using an contactor (AC Relay)

Question: I am working on installing a DC to AC inverter (Victron Energy Phoenix 800VA) in my little teardrop RV such that the Inverter powers ALL the AC ports when it is turned on.  The objective is to have it feed the AC panel when on.  The concern is getting the AC-DC battery charger to be automatically shut off when I turn on the Inverter.
The setup is pretty simple:
Today:  Shore power > AC panel > AC-DC battery charger > 12v battery & 12v panel
With Inverter installed: 12v battery > DC to AC inverter > AC panel
There is no problem as long as the Inverter stays off, but once the inverter is turned on, the AC-DC charger will try to charge the battery from the Inverter.  I have seen the solution is to put a contractor (AC relay) between the AC Panel and AC-DC charger that is switched by power coming from the Inverter.  I totally get the concept, I have some implementation questions:

What contractor should I be using?  Shore power is 110v @ 30 amp, the AC-DC charger is nowhere near that power draw and the Inverter is only about 800 watts.  I know the contractor needs to have an "Open" unless it is charged (by the Inverter) so that the default mode is shore power will run to the AC-DC battery charger.

How do I wire it to the inverter exactly?  Will both hot & neutral go through the contractor or only the hot like a relay?

I would LOVE to get one of the Victron Energy Multiplus unit's, but there are some big problems with that:
Multiplus size:  I am only installing Victron Energy Phoenix 800VA, which means if I were to use the Multiplus, I would install the 800VA unit. The problem comes from the fact I am NOT expecting to run the high current items off this inverter:  A/C, build it electric heater, and Microwave.  I will only use those when connected to shore power.  From everything I can tell about the Multiplus 800VA is that when connected to shore power it won't allow more than the 650Watts through to the panel, preventing me from ever using the high current items.
There are reasons I am NOT looking at a larger Multiplus:  From everything I understand about the larger Multiplus units, I would have to hook up a big battery bank, somewhere between 300~500Ah.  The teardrop does not hav=e the space and I do not want to spend the money on batteries I don't NEED.
All in all, it seems the best solution is a custom system that allows the full 30 amps when connected to shore power to get to the panel but correctly switching it when offshore power to allow the Victron Energy Phoenix 800VA to power the panel without feedback.
Comment: it's so simple, it's actually quite complicated, given the AC and backfeeding in play here. I would replace the switch that turns the inverter on with a DPDT and use the other half to disconnect the charger when the inverter is activated.
Answer: There's an easier and more passive way to do that thing.  And it won't have any vampire draw on the battery.
Note that as an RV, you must comply with your territory's electrical code, such as NEC in the US and central America. This is AC power. There's no "wing-dinging" this together with non-listed components from Mouser or worse, Amazon.
Fortunately, there'll be no trouble putting this together with approved AC power equipment.
What you need is a stock thing: an interlock.
This sits in an AC breaker panel and interlocks 2 breakers so they can't be on at once. Such as an Eaton CHML, Square D QO2DTI or Siemens ECSBPK02.
I recommend using an additional 4-space service panel/load center.  This will use common off-the-shelf 2-pole breakers and interlock to switch both hot and neutral to your RV's regular service panel.  This way, when on utility, the inverter's neutral-ground bond is disconnected from the house.
This will do something else cool for us: allow us to run the battery charger while on inverter, as long as utility power is present.  That means you don't need to think about turning it on.  It just does.

How to build it.
Use a 4-space/8-circuit micro-panel.  Into it go two 2-pole breakers: one of them 30A (for the utility side) and the other is probably 15A (or whatever is appropriate for the inverter).  Between the two breakers goes a "rocking interlock" that prevents both breakers from being on at once.
The breakers are "back-fed" (fed from the output side) to the common bus on the panel.  That is then sent onward to the RV's existing AC panel.
Why do you need an interlock?
At the very least, the interlock is to keep your inverter from inadvertently backfeeding the power grid, if you bungled a switchover during an outage. Backfeeding can kill linemen repairing the lines.
But another big problem is neutral switching. It needs to be done.  On utility, you have neutral and ground separated.  On inverter, the inverter bonds neutral and ground, and this isn't disconnected by a normal switch.  So the RV is bonding neutral and ground from the house.
The problem is, external failures (in the house) could cause loads outside the RV to path their return current via your RV (inverter's) neutral-ground bond.  This can be far more amps that it was ever designed for.  This is why we only bond neutral and ground in one place.
Doing it all with 1 panel
Since this is a 120V-only RV, you could actually make it happen in a single panel, by putting the branch circuits in the same panel as the interlock.  However, since the panel is using its 2-pole functionality to switch neutral, all the branch circuit breakers will need to be 2-pole also - so they can tap neutral.  This will gobble up breaker spaces at twice the rate.
Fortunately on these compact panels, you can usually use tandem (or in this case quadplex breakers).   I would avoid small GE panels here*.
The switched neutral also makes GFCI and AFCI breakers out of the question, but you can always put them at the first receptacle.

8 spaces for clarity. Pick any panel size you want. Grounds omitted for clarity.  Note how every circuit taps neutral. Also note "outer/inner" way you tap a quadplex.  Not illustrated: outer handle-ties on the quadplex.
Branch circuit wire colors for clarity; feel free to use black/white.
As long as you wire your grounds, and have 1 (temporary?) receptacle on each circuit, you can use a common 3-light tester to make sure you didn't accidentally exchange hot and neutral on the breaker.
All the breakers must be common-trip.  Why? Because you can't abide a situation where neutral trips, but hot does not trip. The circuit would be inoperative, and seem dead, but would be live.

*  unless you're very clear on how GE's double-stuff (thin/narrow) 2-pole breakers work - they're not like quads at all). With small panels, you'll find you can't support as many 2-pole breakers as you thought you could!
Comment: That looks simple enough :)  Now to find a really small subpanel to put the interlock into and find a place to put it in my little teardrop RV.
Comment: @SamCarleton Well I'm having you use a separate 4-space panel, but you could do it in one panel. See my upcoming edit.
Comment: Oh, I am so sorry, I wasn't real clear.  I am adding this to a really small teardrop camper that already has this All-in-one panel: https://www.progressivedyn.com/pd4100-series/  I am having to find space to put the inverter (I am going to go with the Victron MultiPlus 800), there simply isn't a good place to but another box.
Comment: @SamCarleton drat... My line of thinking was you could replace your previous choice of AC panelboard.  Yeah, you probably should've mentioned all that lol.  That's the trouble with all-in-ones lol.   My original concept *could* be replaced by a UL listed 30A rated DPDT switch in proper enclosure, which could be as small as 2x4".... but that's industrial exotica.  I was focusing on picking stuff your local Home Depot stocks.  (And that's legal of course).
Comment: And as far as powering the battery charger discretely i.e. not in the panel, easy peasy... the black and white wires coming out of the DC section **are the battery charger leads**, and can be fed from anywhere you please, doesn't have to go in that 3-space panel.
Answer: There are inverter chargers that have this functionality built in that would go between your incoming shore power and the AC panel. They automatically switch between shore and battery power, if shore is plugged in then it passes through the inverter to the panel and charges the battery automatically.
Victron example of an inverter charger
www.amazon.com/Programmed-Victron-MultiPlus-Inverter-Charger/dp/B08QTT6JTL
Comment: Yeah, a multimode inverter-charger is generally the best all-around solution to the problem -- Harper's solution is basically a legal/safe quick-hack for the OP's situation
Comment: I totally agree I would LOVE to have that unit, but there are a few problems.  See my added comments above on what those are.
Answer: RVs are tricky beasts because a single unit may be used in different contexts; fixing the wiring so that it automatically satisfies electrical code requirements of each context is a tricky thing to do. The RV can act like:

A subpanel. When connected to shore power the RV and its distribution center should be wired like an ordinary subpanel. It should use a 3-wire (20/30 amp) or 4-wire (50 amp) shore power connection; there should be no bond between neutral and ground in the RV. Usually there are batteries to be charged; it makes sense that the charger would connect to one of the circuits on that distribution center.
A separately derived system. When AC loads are powered by an inverter and the RV has no electrical connection to a larger electrical grid then a neutral-ground bond is needed inside the RV. Some inverters automatically make and break the neutral-ground bond. Also there's the challenge that brought you here: how to avoid using inverter AC power to charge the battery that's powering the inverter.
A separately derived system.. kinda. When the RV is powered by a portable generator through the shore power cord it's still a separately derived system and a neutral-ground bond is needed. But the inverter won't provide the bond in this condition and many generators don't either (the Honda EU series, for instance).

There are, of course, myriad valid ways of dealing with these issues. There are a number of choices to be made; each selection narrows the field of options for the remaining choices.
AC Power Source Selection
One detail not mentioned in the question is how the switching between shore power and inverter power will be accomplished.

Cord-and-plug transfer: To use inverter power the shore power cord could simply be plugged to one of the receptacles on the inverter. (If the inverter has hardwire output, wire a single receptacle to it.)
Manual transfer: The shore power cord and the inverter output could be hard wired to a manual switch. The hot wire(s) must be switched; switching the neutral and ground wires may be optional depending on how the neutral-ground bond is dealt with. So, a 1-, 2-, or more-pole switch might be needed.
Automatic transfer: very similar to manual transfer except that the switch operates automatically based on some criteria.

Benefits of the cord-and-plug transfer method include that it's very easy to understand and to build correctly, and it's low cost. It provides a nice hook for automatically disabling the charger too: assuming the inverter has two output receptacles, use the second one to activate a relay which shuts off the power to the charger. A diagram might help:
<code>           +-> Shore power -> Panel -> Relay -> Charger
           |                            ^
Inverter --+-> -------------------------+
</code>
A device such as this Functional Devices RIBU1C will probably do nicely. Its coil inputs can be wired directly to the 120 volt output of the inverter; its normally closed contacts can be wired in series with the charger. When the relay coil is powered it'll break the circuit on the NC contacts, thus turning off the charger.

Neutral-ground bond
Another benefit of the cord-and-plug transfer method is that it makes it easy to do the right thing for the neutral-ground bond. If the inverter makes the bond automatically then you don't have to do anything extra. If it doesn't make the bond automatically, you can create one by:

Get a 3-prong replacement cord end and install a 12 gauge jumper wire between its ground and neutral terminals. Plug that into a spare receptacle on the inverter.
If the inverter is the hard-wire type, tie ground and neutral together at the inverter or at the receptacle that you hard-wired to it.

A nice side benefit of #1 is that, if you happen to have a generator that does not provide a neutral-ground bond, then when using the generator you can grab that "bonding plug" off the inverter and plug it to a spare socket on the generator instead.
Comment: Ok, so you bring up grounding.  Something I know little to nothing about, but your post highlighted the fact that I NEED to become knowledgeable about this to wire things up corectly. Can you point me to any sources that will educate me on the topic?
Comment: Mike Sokol at No Shock Zone has written extensively about electrical safety in the [RV](http://noshockzone.org/category/rv-safety/), marine, and theater contexts. I was introduced to the idea of the "bonding plug" mentioned in my answer through his article [Generator Ground-Neutral Bonding](http://noshockzone.org/generator-ground-neutral-bonding/).
Answer: You have some misconceptions about the MultiPlus. This summer I've installed a 24/3000/70 model and became intimately familiar with its capabilities so I'll clear up a couple points for you.
Looking at the data sheet for the MultiPlus 500-2000 VA models we see the 500-1600 models have a 16 A transfer switch. This means that when shore power is connected the MultiPlus will pass up to 16 amps from shore power through itself and on to your AC distribution panel (not 650 W as you had thought).
The 650 W limit is continuous inverter power at 40 degrees C ambient. Because the 800 VA and larger MultiPlus devices offer PowerAssist, this means that if you're connected to shore power you could actually draw up to the full 16 A of transfer switch capacity plus the 650 W of inverter capacity at the MultiPlus output -- a total of about 21 A. When the load dropped below 16A the MultiPlus would automatically resume charging the battery bank. This PowerAssist feature would come in handy if you happened to have the RV powered from a generator and wanted to run your air conditioner but the generator alone isn't quite powerful enough to start the air conditioner.
It isn't necessary to have a massive battery bank with this or the larger MultiPlus models. The primary concern is to avoid drawing excessive current from the battery bank. "Excessive" varies according to the Ah capacity of the bank and its chemistry. According to a chart given there, a battery with lead chemistry might support 2C or higher discharge rate. If you had a 100 Ah battery and wanted to allow a 2C discharge rate that's 200 A allowed, which from a 12 V battery is 2400 W. So it wouldn't be unreasonable to choose a 2000 VA MultiPlus. A nice benefit of choosing the 12/2000/80 model is that you get an upgrade to 35 A transfer switch instead of 16 A with the 500-1600 VA models.
There's one other thing to consider: split the AC power system. Wire it so that heavier loads (air conditioning, microwave, water heater) go through a breaker panel that is fed only from shore power. Wire the other circuits to be fed from the MultiPlus -- its 16 A transfer capacity will easily handle all your smaller loads. An RV with a 50 A shore power hookup is likely to be built this way at the factory.
To convert yours to this topology, start with a normal 120/240 volt breaker panel. Connect the shore power hot to one of its input lugs and also to the MultiPlus AC input. Connect the MultiPlus AC output to the other hot input lug of the panel. Install single-pole breakers into the panel arranged so that they plug to either the shore-power bus or the MultiPlus bus.
Comment: Thank you so much, that is VERY helpful.  I will seriously reconsider the MultiPlus.  While I do like the idea of splitting the AC power system, in this tiny little camper it just isn't practical. It has the PROGRESSIVE DYNAMICS PD4135KW2B, a compact all in one system that combines both the AC and DC.  I simply don't have space for another subpanel..  The RV in question is the Intech Luna, which just has enough room for the one queen size bed and has about 4 1/2 feet of head room inside.  Very small, very tight.
Comment: P.S.  16 amp is plenty, I run the A/C unit when the RV is at home and plugged into my 15 amp line at the house.


Why do Wizards use 1-hand weapons if 2-hand weapons hit harder?

Question: The answers to the question Should we use slow or fast weapon on the wizard? say that many spells, like Blizzard, are not affected by attack speed. So, for better DPS, people should be better off using heavy 2 handed weapons.
Yet most Wizards use 1 handed weapons.
Why?
Comment: Keep in mind that a good offhand adds both a lot of damage and a lot of extra stats. This means 2-handed weapons won't necessarily hit harder.
Comment: Dunno if anyone said it, but a 2H Weapon can have only 1 Socket, as well as 1H. So the additional Socket on your offhand is kinda important, especially if you Dual Wield.
Answer: Because if you use 1 hand weapon you can benefit from an offhand item that bring you a lot of stats as well as damage that you wouldnt be able to find on a weapon. You can find

Crit chance
Elemental damage
Vitality
Some good damage that compensate for not using a 2handed weapon
Arcane power
Bonus to a skill
etc

Since 2.0 patch, elemental damage and +x% skill damage has became the bread and butter of every classes. Imagine you "lose" 10% damage by not using a 2 handed weapon but you gain 15% to blizzard on your off-hand, in the end you benefit more from it since you gain more damage.
Currently I don't see why any class would use a 2 handed weapon (Except the Crusader for obvious reason)
Comment: 2 handers still plain suck, period.  Even as a crusader I'd have to think twice about one since it ties up a passive and makes me slow as heck.
Comment: I agree that this logic applies to most classes. For example for monks, see [this question](http://gaming.stackexchange.com/questions/66792/monks-and-the-effectiveness-of-2-handed-weapons). Better stats, and also faster attack speed means faster resource generation.
Comment: @z- Blizzard need to seriously buff the damage to make it worth haveing a 2H weapon. Even as a Demon Hunter where you can still have a quivher with 2H crossbow, nobody use them because damage are the same as 1H
Comment: I think most DHs use Maticor as 2H, because of the heavy damage and you save your hate because of slower attacking but the same damage.
Comment: I play only DH and I can assure you that since RoS, no one want to use 2H. The attack speed is way to slow to generate enough hartred and the damage has been nerfed on ther manticore which can roll max 35% Crit Damage as well as a socket. Compared to the Vanilla one which could roll 100% CD + 2 socket.(thats why dps was gigantic)
Answer: What WizLiz said is true.
However I would still probably choose a 2H weapon if I want to make say a Disintegrate or a Ray of Frost build, because the slow attack speed will make my arcane power tick slower and I can hold the ray for much much longer (about 30 secs with skills).
Also the damage is really nice and not to be ignored even without the extra stats from the offhand.
The Disnintegrate/Blizzard build (pre RoS), which was the next most popular one, next to the CM wizard, was played with a Skorn about 90% of the time.
Comment: while that's true disintegrate works just as well with a slow one hander and a source with arcane power on crit.
Comment: Indeed, slow one-handers are harder to come by though. I seem to like Odyn Son for a disintegrate build, or any channeled spell build for that matter.


Preventing full width layouts from stretching on large screens

Question: I wonder if there is a way to prevent full width layouts from stretching on large screens. An example for that is mashable.com, on my screen (13 inch) the layout is in full width. If you try to zoom out the page, you will notice that the layout is not full width.
This is how the layout appear on small-medium screens:

And the below image is for larger screen, notice that it's not full width now:

Another example, the below design is a full width layout, I want to prevent stretching it out when viewing it on wide screens.

Any thoughts on that please? How can we achieve it in Bootstrap 3
Thanks,
Comment: If you use Bootstrap it'd be a good idea to learn css as well as all examples are achieved either by modifying an existing class or rolling your own. What have you tried to do to get any of the examples you want?
Comment: I got your message in my email. If you are hiring me, then please let me know, otherwise this question can be answered on StackOverflow. Thanks
Answer: Add a 'max-width' to your container/wrapper. For example:
.container {
width: 100%;
max-width: 1550px;
}

In this example the website would appear fully 'stretched' across the screen until the screen dimensions exceed 1550px wide.
See a scaled-down demo here
Comment: Great idea! what if I want to make the header blue background (like Mashable) stretch on all the screen while the content inside is affected by the max-width property? Thanks
Comment: Read up on the difference between `.container` and `.container-fluid`, see http://getbootstrap.com/css/#grid
Answer: By default Bootstrap uses a 1140 pixel grid, see http://getbootstrap.com/css/#grid. Simply adding a .container around your content makes sure that content will never grow larger.
It's possible to customize the maximum size by creating a customized version of Bootstrap using http://getbootstrap.com/customize/ or by compiling Bootstrap yourself and setting the @container-large-desktop variable
Comment: If you have a fixed width simply add a container `` and style it with `width: ...px;`. I think you can even add the fluid `.container-fluid` inside it if you want to use Bootstraps grid columns.
Comment: That won't work with my case, please check the updated question. I added another example.
Answer: Use max-width to stop getting 100% width on larger screens:
div.container{
margin: auto;
padding: 0;
width: 100%;
max-width: 1024px;
height: auto;
}


AWS Secret Manager `ParamValidationError`: `"SecretID", must be one of: SecretId, VersionId, VersionStage`

Question: I am having a problem with accessing a secret from Secret Manager in a lambda function.
Here is the relevant code:
import boto3

session = boto3.session.Session()
secretsmanager = session.client(service_name="secretsmanager")

get_secret_value_response = secretsmanager.get_secret_value(
    SecretID="arn:aws:secretsmanager:SECRETNAME"
)
secret = get_secret_value_response["SecretString"]

The error message, however, is confusing. Neither I found mentions of it elsewhere.
[ERROR] ParamValidationError: Parameter validation failed:
Missing required parameter in input: "SecretId"
Unknown parameter in input: "SecretID", must be one of: SecretId, VersionId, VersionStage
Traceback (most recent call last):
  File "/var/task/notification_parser.py", line 14, in handler
    get_secret_value_response = secretsmanager.get_secret_value(
  File "/var/runtime/botocore/client.py", line 530, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/runtime/botocore/client.py", line 919, in _make_api_call
    request_dict = self._convert_to_request_dict(
  File "/var/runtime/botocore/client.py", line 990, in _convert_to_request_dict
    request_dict = self._serializer.serialize_to_request(
  File "/var/runtime/botocore/validate.py", line 381, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())

The documentation shows a string value, so I am confused.
Any ideas where I could go wrong?
Answer: You error is clear which is the name of the SecretID and SecretId. You named it incorrectly.
Just change the variable name to SecretId instead of SecretID the last letter should be lowercase.
But if you want here is the example how to use it
import boto3

SECRET_ARN = "YOUR_SECRET_ARN"
secret_manager = boto3.client('secretsmanager')

response = secret_manager.get_secret_value(
    SecretId=SECRET_ARN
)

# this might be a json string so you might need to parse it
# to parse it you can use json.loads(response['SecretString'])
print('Secret: ' + response['SecretString'])

Answer: Here is working code to get a secret using Python.
# snippet-start:[python.example_code.secrets-manager.GetSecretValue]
    def get_value(self, stage=None):
        """
        Gets the value of a secret.

        :param stage: The stage of the secret to retrieve. If this is None, the
                      current stage is retrieved.
        :return: The value of the secret. When the secret is a string, the value is
                 contained in the `SecretString` field. When the secret is bytes,
                 it is contained in the `SecretBinary` field.
        """
        if self.name is None:
            raise ValueError

        try:
            kwargs = {'SecretId': self.name}
            if stage is not None:
                kwargs['VersionStage'] = stage
            response = self.secretsmanager_client.get_secret_value(**kwargs)
            logger.info("Got value for secret %s.", self.name)
        except ClientError:
            logger.exception("Couldn't get value for secret %s.", self.name)
            raise
        else:
            return response
# snippet-end:[python.example_code.secrets-manager.GetSecretValue]


Laravel When Condition on a column

Question: I have a ModelA with columns: name, last_name, email
I want ModelA with the name Test to add an extra where on email
what I tried is the following
$model_a_res = A::when(
function($query){
    return $query->where('name','Test');
},
function ($query) {
    $query->where('email', 'NOT LIKE', '%@test%');})
->first();

I want this second where to only run on A with column name =  Test
however, this is not working.
I tried it with user name Mike and his email email@example.com and he didn't appear in the result.
some data
id name email

1 Test email@example.com
2 Test firstname.lastname@example.com
3 Mike email@example.com
4 Mike firstname.lastname@example.com

both 3 and 4 should be in the results
1 and 2 since they have name = Test will have another query which will check if he does have @test in his email if he does he will not be returned
returned Rows are 2, 3, 4
Comment: can't understand what you asking for
Comment: Tell us what the inputs are + what you expect as output.
Comment: Add extra querying, extra where condition if this row has the column name  = Test
Comment: This is an incomplete question.. Add more info to it
Comment: `when()` only executes the closure if the first argument is true. By that logic, your first parameter is not returning true. But we would need more information.
Answer: You can't use when() for this.
$model_a_res = A::where(function ($query) {
    $query->where('name', '!=', 'Test')
          ->orWhere(function ($query) {
              $query->where('name', '=', 'Test')
                    ->where('email', 'NOT LIKE', '%@test%');
          });
})->get();

Outputs
1 Test firstname.lastname@example.com  -  will skipp
2 Test email@example.com - added
3 Mike email@example.com  - added
4 Mike firstname.lastname@example.com  - added

Laravel When Condition on a column