问:
Google fonts working on live server but not on localhost
My google fonts display fine on my live website, but in production on localhost, they show differently. More boxy/standard, but not the same as the standard font.

How they show on localhost:

How they show on live server (this is want I want):

Here's my CSS:

```<code>@import url('https://fonts.googleapis.com/css?family=Droid+Sans|Caveat+Brush');

body{
  font-family: "Droid Sans", sans-serif; //'projects'
}
#title {
  font-family: 'Caveat Brush', cursive; //'Junior Web Developer'
}
</code>```

I am using gulp and browser-sync, but opening the html file directly from the browser has the same problem

答:
Move the @import code to the very top of your CSS file above everything else.</p>

```<code>@import url('https://fonts.googleapis.com/css?family=Droid+Sans|Caveat+Brush');
</code>```

Body:
My google fonts display fine on my live website, but in production on localhost, they show differently. More boxy/standard, but not the same as the standard font.

How they show on localhost:

How they show on live server (this is want I want):

Here's my CSS:

@import url('https://fonts.googleapis.com/css?family=Droid+Sans|Caveat+Brush');

body{
  font-family: "Droid Sans", sans-serif; //'projects'
}
#title {
  font-family: 'Caveat Brush', cursive; //'Junior Web Developer'
}

I am using gulp and browser-sync, but opening the html file directly from the browser has the same problem

Body:
Move the @import code to the very top of your CSS file above everything else.

@import url('https://fonts.googleapis.com/css?family=Droid+Sans|Caveat+Brush');


来源: stackexchange

问:
Google SilentSignIn C#
I'm trying to implement Google Sign In in a app that I'm testing out. I can make everything connect and work without any problems however I want the app to attempt to silently log in (cached credentials) and move on if it finds them.

The only examples I can find to do this are in Java and while it's not radically different from C# I'm not really an expert in that either :)

I have taken the example from here:

https://github.com/googlesamples/google-services/blob/master/android/signin/app/src/main/java/com/google/samples/quickstart/signin/SignInActivity.java

However I have hit what I think is a catch 22 that I would like some help with. If I use the code:

```<code>    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.SilentSignIn(plusClient);
    if(opr != null)
    {
        if (opr.IsDone)
        {
            Console.Out.Write("we have cached login");
            try
            {
                GoogleSignInResult signInResult = opr.Get;
                GoogleSignInAccount gsa = signInResult.SignInAccount;

                Toast.MakeText(this, gsa.DisplayName, ToastLength.Short).Show();

            }
            catch (Exception e)
            {
                Console.Out.Write("error getting cache login: {0}", e.ToString());
            }
        }
        else
        {
            Console.Out.Write("we're gonna have to log in");
        }
</code>```

Then the first line fails on the OptionalPendingResult section for:

CS0308    The non-generic type 'OptionalPendingResult' cannot be used
  with type arguments

I can drop the  and the error goes away. I can then use opr.isDone so I know this is working correctly. However I then get an error on the line:

```<code>                GoogleSignInResult signInResult = opr.Get;
</code>```

CS0428    Cannot convert method group 'Get' to non-delegate type
  'GoogleSignInResult'. Did you intend to invoke the method?

or, if I put brackets at the end I get

```<code>                GoogleSignInResult signInResult = opr.Get();
</code>```

CS0266    Cannot implicitly convert type 'Java.Lang.Object' to
  'Android.Gms.Auth.Api.SignIn.GoogleSignInResult'. An explicit
  conversion exists (are you missing a cast?)

Now, I'm pretty sure the original cast that I removed is at the heart of the problem however I don't know enough about this and Google just returns java results.

Anyone able to help out?

Thanks,
Justin

答:
when the error says

An explicit conversion exists (are you missing a cast?)

it's telling you need to explicitly cast (change the type) of the object, like this:

```<code>GoogleSignInResult signInResult = (GoogleSignInResult) opr.Get();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Google SilentSignIn C#

Body:
I'm trying to implement Google Sign In in a app that I'm testing out. I can make everything connect and work without any problems however I want the app to attempt to silently log in (cached credentials) and move on if it finds them.

The only examples I can find to do this are in Java and while it's not radically different from C# I'm not really an expert in that either :)

I have taken the example from here:

https://github.com/googlesamples/google-services/blob/master/android/signin/app/src/main/java/com/google/samples/quickstart/signin/SignInActivity.java

However I have hit what I think is a catch 22 that I would like some help with. If I use the code:

    OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.SilentSignIn(plusClient);
    if(opr != null)
    {
        if (opr.IsDone)
        {
            Console.Out.Write("we have cached login");
            try
            {
                GoogleSignInResult signInResult = opr.Get;
                GoogleSignInAccount gsa = signInResult.SignInAccount;

                Toast.MakeText(this, gsa.DisplayName, ToastLength.Short).Show();

            }
            catch (Exception e)
            {
                Console.Out.Write("error getting cache login: {0}", e.ToString());
            }
        }
        else
        {
            Console.Out.Write("we're gonna have to log in");
        }

Then the first line fails on the OptionalPendingResult section for:

CS0308    The non-generic type 'OptionalPendingResult' cannot be used
  with type arguments

I can drop the  and the error goes away. I can then use opr.isDone so I know this is working correctly. However I then get an error on the line:

                GoogleSignInResult signInResult = opr.Get;

CS0428    Cannot convert method group 'Get' to non-delegate type
  'GoogleSignInResult'. Did you intend to invoke the method?

or, if I put brackets at the end I get

                GoogleSignInResult signInResult = opr.Get();

CS0266    Cannot implicitly convert type 'Java.Lang.Object' to
  'Android.Gms.Auth.Api.SignIn.GoogleSignInResult'. An explicit
  conversion exists (are you missing a cast?)

Now, I'm pretty sure the original cast that I removed is at the heart of the problem however I don't know enough about this and Google just returns java results.

Anyone able to help out?

Thanks,
Justin

Body:
when the error says

An explicit conversion exists (are you missing a cast?)

it's telling you need to explicitly cast (change the type) of the object, like this:

GoogleSignInResult signInResult = (GoogleSignInResult) opr.Get();


问:
Interactive Quiz: How to keep input values when hidden?
I've created an interactive quiz and created functions that showed the next question and goes back to the previous questions. My problem is that when it changes questions, the information I input in is erased. For example Question 1 and 2, I would write in an animal and then I go onto Question 3, but when I go back to Question 1 and 2, the animals I wrote in are gone. Same with the radio choices. Sorry if code is tedious, I'm just starting. Any tips on how I can fix that?

Quiz link: https://repl.it/GSiI/latest

```<code>    function initialize()
    {
      questionList = document.getElementsByClassName("questions");
      quizOutput = document.getElementById("showQuiz");
      beginBtn = document.getElementById("initiate");
      button = document.getElementById("button");
      next = document.getElementById("next");
      previous = document.getElementById("previous");
      questionIndex = 0;
      totalQuestions = questionList.length - 1;
    }

    function beginQuiz()
    {
     currentQuestion = questionList.item(questionIndex).innerHTML;
     button.style.visibility = "visible";
     quizOutput.innerHTML = currentQuestion;
     beginBtn.style.display = "none";
     quizOutput.style.display = "block";
    }

    function changeQuestion(factor)
    {
       if(factor == -1 && questionIndex > 0)
       {
        questionIndex--;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
       if(factor == 1 && questionIndex < totalQuestions)
       {
        questionIndex++;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
   }

    function writeNumber(el, num)
    {
     input = document.getElementById(el);
        if(input.value.length < 2)
        {
            input.value += num;
        }
    }

    function clearAnswer(el)
    {
     document.getElementById(el).value = "";
    }

    function takeValues()
    {
     var x = document.getElementById("frm1");
     var text = "";
     var i;
     for (i = 0; i < x.length ;i++)
        {
          text += x.elements[i].value + "<br>";
        }
     document.getElementById("demo").innerHTML = text;
    }
</code>```

答:
I will suggest using javascript FormData object to get entries of input values .
First removing all the "form" elements from your html but keep their inner elements.
Then make "showQuiz" div into a form element.
Then create 1 single form ( I set this form to have id "form1")  to contain all the questions and the submit button .
Then modify the javascript function changeQuestion as follow:

```<code>function changeQuestion(factor)
{
  var myform = document.getElementById("showQuiz");
  var fdata = new FormData(myform);
  var storeForm = document.getElementById("form1");
  var sdata = new FormData(storeForm);
  for (var pair of fdata.entries()) {
    var elem = document.getElementsByName(pair[0])[0];
    storeForm.elements[pair[0]].value = pair[1];
  }
  if(factor == -1 && questionIndex > 0)
  {
    questionIndex--;
    currentQuestion = questionList.item(questionIndex).innerHTML;
    quizOutput.innerHTML = currentQuestion;
  }
  if(factor == 1 && questionIndex < totalQuestions)
  {
    questionIndex++;
    currentQuestion = questionList.item(questionIndex).innerHTML;
    quizOutput.innerHTML = currentQuestion;
  }
  myform = document.getElementById("showQuiz");
  storeForm = document.getElementById("form1");
  fdata = new FormData(myform);
  sdata = new FormData(storeForm);
  for (var pair of sdata.entries()) {
      var fld = myform.elements[pair[0]];
      if (fld)
        fld.value = pair[1];
  }
}
</code>```

Body:
I've created an interactive quiz and created functions that showed the next question and goes back to the previous questions. My problem is that when it changes questions, the information I input in is erased. For example Question 1 and 2, I would write in an animal and then I go onto Question 3, but when I go back to Question 1 and 2, the animals I wrote in are gone. Same with the radio choices. Sorry if code is tedious, I'm just starting. Any tips on how I can fix that?

Quiz link: https://repl.it/GSiI/latest

    function initialize()
    {
      questionList = document.getElementsByClassName("questions");
      quizOutput = document.getElementById("showQuiz");
      beginBtn = document.getElementById("initiate");
      button = document.getElementById("button");
      next = document.getElementById("next");
      previous = document.getElementById("previous");
      questionIndex = 0;
      totalQuestions = questionList.length - 1;
    }

    function beginQuiz()
    {
     currentQuestion = questionList.item(questionIndex).innerHTML;
     button.style.visibility = "visible";
     quizOutput.innerHTML = currentQuestion;
     beginBtn.style.display = "none";
     quizOutput.style.display = "block";
    }

    function changeQuestion(factor)
    {
       if(factor == -1 && questionIndex > 0)
       {
        questionIndex--;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
       if(factor == 1 && questionIndex < totalQuestions)
       {
        questionIndex++;
        currentQuestion = questionList.item(questionIndex).innerHTML;
        quizOutput.innerHTML = currentQuestion;
       }
   }

    function writeNumber(el, num)
    {
     input = document.getElementById(el);
        if(input.value.length < 2)
        {
            input.value += num;
        }
    }

    function clearAnswer(el)
    {
     document.getElementById(el).value = "";
    }

    function takeValues()
    {
     var x = document.getElementById("frm1");
     var text = "";
     var i;
     for (i = 0; i < x.length ;i++)
        {
          text += x.elements[i].value + "
";
        }
     document.getElementById("demo").innerHTML = text;
    }

Body:
I will suggest using javascript FormData object to get entries of input values .
First removing all the "form" elements from your html but keep their inner elements.
Then make "showQuiz" div into a form element.
Then create 1 single form ( I set this form to have id "form1")  to contain all the questions and the submit button .
Then modify the javascript function changeQuestion as follow:

function changeQuestion(factor)
{
  var myform = document.getElementById("showQuiz");
  var fdata = new FormData(myform);
  var storeForm = document.getElementById("form1");
  var sdata = new FormData(storeForm);
  for (var pair of fdata.entries()) {
    var elem = document.getElementsByName(pair[0])[0];
    storeForm.elements[pair[0]].value = pair[1];
  }
  if(factor == -1 && questionIndex > 0)
  {
    questionIndex--;
    currentQuestion = questionList.item(questionIndex).innerHTML;
    quizOutput.innerHTML = currentQuestion;
  }
  if(factor == 1 && questionIndex < totalQuestions)
  {
    questionIndex++;
    currentQuestion = questionList.item(questionIndex).innerHTML;
    quizOutput.innerHTML = currentQuestion;
  }
  myform = document.getElementById("showQuiz");
  storeForm = document.getElementById("form1");
  fdata = new FormData(myform);
  sdata = new FormData(storeForm);
  for (var pair of sdata.entries()) {
      var fld = myform.elements[pair[0]];
      if (fld)
        fld.value = pair[1];
  }
}


问:
Understanding RSpec 2's generated specs
I think I may be biting off more than I can chew by trying to learn RSpec on my own...there doesn't appear to be any complete documentation on RSpec 2?!? at least none that I have been able to find...

Anyway, I, in a feeble attempt to integrate RSpec, started by examining the 29 specs created by the scaffold generator in Rails 3. Some I understand but much still escapes me. Hoping someone can help (or point me to decent RSpec 2 documentation).

For example in the first code block below (def mock_clown...) I can assume mock_clown is creating a mock of my Clown class to test against. But what exactly is going on? what is generating this "mock"?  what does .as_null_object and .tap mean? This is very confusing as I can't find an example to compare this block to in any docs or tutorials I've come across...

```<code>#clowns_controller_spec.rb

require 'spec_helper'

describe ClownsController do

  def mock_clown(stubs={})
    (@mock_clown ||= mock_model(Clown).as_null_object).tap do |clown|
      clown.stub(stubs) unless stubs.empty?
    end
  end

  describe "GET index" do
    it "assigns all clowns as @clowns" do
      Clown.stub(:all) { [mock_clown] }
      get :index
      assigns(:clowns).should eq([mock_clown])
    end
  end

...

  describe "POST create" do

...

    describe "with invalid params" do
      it "assigns a newly created but unsaved clown as @clown" do
        Clown.stub(:new).with({'these' => 'params'}) { mock_clown(:save => false) }
        post :create, :clown => {'these' => 'params'}
        assigns(:clown).should be(mock_clown)
      end

      it "re-renders the 'new' template" do
        Clown.stub(:new) { mock_clown(:save => false) }
        post :create, :clown => {}
        response.should render_template("new")
      end
    end

...

end
</code>```

答:
The best source of documentation for rspec is probably its github wikis. Here's a general link to all gems:https://github.com/rspec/rspec/wiki. Also, checkout the rdoc, linked to here.

As for specific answers, as_null_object causes the mock to record and ignore all method calls. (This is great, as you don't have to spec out every single method on an object, just the ones you care about.)

Tap is a Ruby 1.9 feature. From the documentation at this link:

Object#tap

Passes the object to the block and returns it (meant to be used for call chaining).

For learning Rspec 2 Webrat and Cucumber on your own, I definitely recommend checking out the RSpec Book. Awesome resource, and covers all aspects.

ContentLicense: CC BY-SA 2.5

Title: Understanding RSpec 2's generated specs

Body:
I think I may be biting off more than I can chew by trying to learn RSpec on my own...there doesn't appear to be any complete documentation on RSpec 2?!? at least none that I have been able to find...

Anyway, I, in a feeble attempt to integrate RSpec, started by examining the 29 specs created by the scaffold generator in Rails 3. Some I understand but much still escapes me. Hoping someone can help (or point me to decent RSpec 2 documentation).

For example in the first code block below (def mock_clown...) I can assume mock_clown is creating a mock of my Clown class to test against. But what exactly is going on? what is generating this "mock"?  what does .as_null_object and .tap mean? This is very confusing as I can't find an example to compare this block to in any docs or tutorials I've come across...

#clowns_controller_spec.rb

require 'spec_helper'

describe ClownsController do

  def mock_clown(stubs={})
    (@mock_clown ||= mock_model(Clown).as_null_object).tap do |clown|
      clown.stub(stubs) unless stubs.empty?
    end
  end

  describe "GET index" do
    it "assigns all clowns as @clowns" do
      Clown.stub(:all) { [mock_clown] }
      get :index
      assigns(:clowns).should eq([mock_clown])
    end
  end

...

  describe "POST create" do

...

    describe "with invalid params" do
      it "assigns a newly created but unsaved clown as @clown" do
        Clown.stub(:new).with({'these' => 'params'}) { mock_clown(:save => false) }
        post :create, :clown => {'these' => 'params'}
        assigns(:clown).should be(mock_clown)
      end

      it "re-renders the 'new' template" do
        Clown.stub(:new) { mock_clown(:save => false) }
        post :create, :clown => {}
        response.should render_template("new")
      end
    end

...

end


问:
reading gctx file in R
I am trying to read a gctx file extracted from LINCS source for gene expression analysis. The codes for eading the file are provided at the link below.
https://github.com/cmap/l1ktools.
I am using the script provided and I have sourced the script. however when I tried the function parse.gctx it gives me following error:

```<code>ds <- parse.gctx("../L1000 Data/zspc_n40172x22268.gctx")

reading ../L1000 Data/zspc_n40172x22268.gctx
Error in h5checktypeOrOpenLoc(file, readonly = TRUE) :
  Error in h5checktypeOrOpenLoc(). Cannot open file. File 'C:\L1000 Data\zspc_n40172x22268.gctx' does not exist.
</code>```

How can I resolve this issue and read my gctx file?

答:
Since you're getting a 'file does not exist' error, I think the problem is because you have a space in the path to the file you're trying to read (specifically, in "L1000 Data"); if you remove the space in the path it should parse properly.

In other words, try renaming your "L1000 Data" folder so that instead of:

```<code>ds <- parse.gctx("../L1000 Data/zspc_n40172x22268.gctx")
</code>```

you have something along the lines of:

```<code>ds <- parse.gctx("../L1000_Data/zspc_n40172x22268.gctx")
</code>```

Title: reading gctx file in R

Body:
I am trying to read a gctx file extracted from LINCS source for gene expression analysis. The codes for eading the file are provided at the link below.
https://github.com/cmap/l1ktools.
I am using the script provided and I have sourced the script. however when I tried the function parse.gctx it gives me following error:

ds <- parse.gctx("../L1000 Data/zspc_n40172x22268.gctx")

reading ../L1000 Data/zspc_n40172x22268.gctx
Error in h5checktypeOrOpenLoc(file, readonly = TRUE) :
  Error in h5checktypeOrOpenLoc(). Cannot open file. File 'C:\L1000 Data\zspc_n40172x22268.gctx' does not exist.

How can I resolve this issue and read my gctx file?

Body:
Since you're getting a 'file does not exist' error, I think the problem is because you have a space in the path to the file you're trying to read (specifically, in "L1000 Data"); if you remove the space in the path it should parse properly.

In other words, try renaming your "L1000 Data" folder so that instead of:

ds <- parse.gctx("../L1000 Data/zspc_n40172x22268.gctx")

you have something along the lines of:

ds <- parse.gctx("../L1000_Data/zspc_n40172x22268.gctx")


问:
Bash - How to check if command gave no output without printing it?
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

```<code>failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests
</code>```

Thank you in advance for all the answers.

答:
diff has an exit status of 0 if there are no differences, non-zero otherwise. You can use the -q option to suppress most output, and redirect the rest of it to /dev/null. Then, the if statement can test the exit status directly.

```<code># Also, use an array to store a list of filenames
failed_tests=()
for filename in "$directory"/*.in; do
    if ./"$program" "$filename" | diff -q - "${filename%.in}.out" > /dev/null; then
        failed_tests+=( "$filename" )
    fi
done
</code>```

Body:
I am writing a testing script. It executes program with *.in files passed as input and compares its output with *.out files using diff command.

However, I don't want to print diff output, but to check if there is any and if so, then add *.in file name to the list of failed tests.

The problem is I have no idea how to check if command produces output without printing it.

My script now:

failed_tests=""

for filename in $directory/*.in; do

    command=< ${filename} ./${program} | diff - ${filename%.in}.out

    # Check if command produces output.
    if command; then
        # Add filename to failed tests list.
        failed_tests="${failed_tests} ${filename}"
    fi

done

echo $failed_tests

Thank you in advance for all the answers.

Body:
diff has an exit status of 0 if there are no differences, non-zero otherwise. You can use the -q option to suppress most output, and redirect the rest of it to /dev/null. Then, the if statement can test the exit status directly.

# Also, use an array to store a list of filenames
failed_tests=()
for filename in "$directory"/*.in; do
    if ./"$program" "$filename" | diff -q - "${filename%.in}.out" > /dev/null; then
        failed_tests+=( "$filename" )
    fi
done


问:
Servlet passes value to jsp on reload or new window
I have a JSP page and a servlet that process a checkbox form. I want the form to retain the last value even in a new session. If the page reloads or a new window is opened, I want the data to be stored.

JSP:

```<code><html><body>
<p>
<form name="checkboxes" action="${pageContext.request.contextPath}/Servlet" method="post">
<%  if(getServletContext().getAttribute("test").equals("on")) { %>
<input type=checkbox name="test" checked>Test
<%  } else { %>
        <input type=checkbox name="test" >Test
<% } %>
       <input type="submit" value="submit"">
       <%= getServletContext().getAttribute("test") %>
</form>
</p>
</code>```

Servlet:

```<code>import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/Servlet")
public class Servlet extends HttpServlet
{
  private String c4;
  public void init()
  {
      c4 = "";
  }

public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
      response.setContentType("text/html");
      String c1 = request.getParameter("test");
      ServletContext context = request.getServletContext();
      if(c1!=null) {
          System.out.println("c1 " + c1);
          context.setAttribute("test", "on");
      }
      else {
          context.setAttribute("test", "off");
      }
      request.getRequestDispatcher("/index.jsp").forward(request, response);

}

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
    doPost(request,response);
}
}
</code>```

答:
I want the form to retain the last value even in a new session. If the
  page reloads or a new window is opened, I want the data to be stored.

There are two options that you can choose:

(1) Save the last value in an in-memory cache store and retrieve it again when the request comes.

(2) Save the last value in a persistent store (preferably database) and retrieve it again when the request comes.

Body:
I have a JSP page and a servlet that process a checkbox form. I want the form to retain the last value even in a new session. If the page reloads or a new window is opened, I want the data to be stored.

JSP:

<form name="checkboxes" action="${pageContext.request.contextPath}/Servlet" method="post">
<%  if(getServletContext().getAttribute("test").equals("on")) { %>
<input type=checkbox name="test" checked>Test
<%  } else { %>
        <input type=checkbox name="test" >Test
<% } %>
       <input type="submit" value="submit"">
       <%= getServletContext().getAttribute("test") %>
</form>

Servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/Servlet")
public class Servlet extends HttpServlet
{
  private String c4;
  public void init()
  {
      c4 = "";
  }

public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
      response.setContentType("text/html");
      String c1 = request.getParameter("test");
      ServletContext context = request.getServletContext();
      if(c1!=null) {
          System.out.println("c1 " + c1);
          context.setAttribute("test", "on");
      }
      else {
          context.setAttribute("test", "off");
      }
      request.getRequestDispatcher("/index.jsp").forward(request, response);

}

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
    doPost(request,response);
}
}


问:
MaxMessageSizeExceededException
We are doing a EJB call as below which is returning us the MaxMessageSizeExceededException.

Java Code to Call the EJB -

```<code>Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://xxxxxx.xxxx.xxx.com:4444");
InitialContext context;
try {
    context = new InitialContext(env);
    Home hb =  context.lookup("lookupname");
    Service service = hb.create();
    Request request = new Request();
    service.getAPI(request);
}
</code>```

Error Details -

```<code><Error> <Socket> <BEA-000403> <IOException occurred on socket: Socket[addr=XXXX.xxx.xxx.com/xxx.x.xxx.xxx,port=xxxx,localport=xxxxx]
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes exceeds the configured maximum of: '10000000' bytes for protocol: 't3'.
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes exceeds the configured maximum of: '10000000' bytes for protocol: 't3'
</code>```

On the Weblogic where the service is deployed they have updated the configs to 30MB,Do we have to do any changes in our client side to increase the incoming size of the response. Any JVM level changes.?

答:
Try  setting the value programatically in your java code e.g:

```<code>System.setProperty("weblogic.MaxMessageSize", "300000000");
</code>```

You can also set the value in your JAVA_OPTIONS -Dweblogic.MaxMessageSize=300000000

Source: https://blogs.oracle.com/LuzMestre/entry/how_to_fix_weblogic_socket

Title: MaxMessageSizeExceededException

Body:
We are doing a EJB call as below which is returning us the MaxMessageSizeExceededException.

Java Code to Call the EJB -

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://xxxxxx.xxxx.xxx.com:4444");
InitialContext context;
try {
    context = new InitialContext(env);
    Home hb =  context.lookup("lookupname");
    Service service = hb.create();
    Request request = new Request();
    service.getAPI(request);
}

Error Details -

<Error> <Socket> <BEA-000403> <IOException occurred on socket: Socket[addr=XXXX.xxx.xxx.com/xxx.x.xxx.xxx,port=xxxx,localport=xxxxx]
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes exceeds the configured maximum of: '10000000' bytes for protocol: 't3'.
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes exceeds the configured maximum of: '10000000' bytes for protocol: 't3'

On the Weblogic where the service is deployed they have updated the configs to 30MB,Do we have to do any changes in our client side to increase the incoming size of the response. Any JVM level changes.?

Body:
Try  setting the value programatically in your java code e.g:

System.setProperty("weblogic.MaxMessageSize", "300000000");

You can also set the value in your JAVA_OPTIONS -Dweblogic.MaxMessageSize=300000000

Source: https://blogs.oracle.com/LuzMestre/entry/how_to_fix_weblogic_socket


问:
TreeSet ignoring values
I am trying to create a class that is given pairs of strings & told one is 'greater" than the other then keeps a running order of all known strings.

To do this I keep a Map<String, Set<String>> that maps a given String to all the values it's greater than, then I created a TreeSet with a comparator that uses that data to compare two strings.

Here's my class:

```<code>public class StringSorter {

    private Map<String, Set<String>> greaterThan = new HashMap<>();
    private SortedSet<String> order;

    public StringSorter() {
        order = new TreeSet<>((o1, o2) -> {
            if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
                return 1;
            else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
                return -1;
            return 0;
        });
    }

    public void addRule(String bigger, String smaller) {

        if (!greaterThan.containsKey(bigger))
            greaterThan.put(bigger, new HashSet<>());
        greaterThan.get(bigger).add(smaller);

        order.add(bigger);
        order.add(smaller);
    }

    public SortedSet<String> getOrder() {
        return order;
    }
}
</code>```

However, for some reason, the TreeSet seems to just ignore many of the values added to it.

Example:

```<code>StringSorter sorter = new StringSorter();
sorter.addRule("one", "two");
sorter.addRule("two", "three");
sorter.addRule("three", "four");
System.out.println(sorter.getOrder());
</code>```

Output:

```<code>[two, one]
</code>```

What happened to the strings three & four?

答:
You can answer this yourself by adding this line to your Comparator.compare lambda:

```<code>System.out.printf("(%s, %s)%n", o1, o2);
</code>```

As you’ll see, there is no guarantee that adjacent values are passed to the Comparator.  When o1 is "three" and o2 is "one", the comparison falls back to returning zero, which tells the TreeSet that the two values are equal, and obviously it won’t add a value it perceives as equal to a value that’s already in the set.

You would need to make your traversal of greaterThan transitive.  I’m pretty sure it will require recursion:

```<code>private boolean isGreater(String o1,
                          String o2,
                          Set<String> keysTried) {
    Set<String> greaterSet = greaterThan.get(o1);
    if (greaterSet == null) {
        return false;
    }

    if (greaterSet.contains(o2)) {
        return true;
    }

    for (String g : greaterSet) {
        if (keysTried.add(g) && isGreater(g, o2, keysTried)) {
            return true;
        }
    }

    return false;
}

public StringSorter() {
    order = new TreeSet<>((o1, o2) -> {
        if (isGreater(o1, o2, new HashSet<>())) {
            return 1;
        } else if (isGreater(o2, o1, new HashSet<>())) {
            return -1;
        } else {
            return 0;
        }
    });
}
</code>```

The purpose of keysTried is to prevent infinite recursion.  (In theory, that should never happen anyway, if greaterThan is a directed graph.)

Title: TreeSet ignoring values

Body:
I am trying to create a class that is given pairs of strings & told one is 'greater" than the other then keeps a running order of all known strings.

To do this I keep a Map<String, Set<String>> that maps a given String to all the values it's greater than, then I created a TreeSet with a comparator that uses that data to compare two strings.

Here's my class:

public class StringSorter {

    private Map<String, Set<String>> greaterThan = new HashMap<>();
    private SortedSet<String> order;

    public StringSorter() {
        order = new TreeSet<>((o1, o2) -> {
            if (greaterThan.getOrDefault(o1, Collections.emptySet()).contains(o2))
                return 1;
            else if (greaterThan.getOrDefault(o2, Collections.emptySet()).contains(o1))
                return -1;
            return 0;
        });
    }

    public void addRule(String bigger, String smaller) {

        if (!greaterThan.containsKey(bigger))
            greaterThan.put(bigger, new HashSet<>());
        greaterThan.get(bigger).add(smaller);

        order.add(bigger);
        order.add(smaller);
    }

    public SortedSet<String> getOrder() {
        return order;
    }
}

However, for some reason, the TreeSet seems to just ignore many of the values added to it.

Example:

StringSorter sorter = new StringSorter();
sorter.addRule("one", "two");
sorter.addRule("two", "three");
sorter.addRule("three", "four");
System.out.println(sorter.getOrder());

Output:

[two, one]

What happened to the strings three & four?

Body:
You can answer this yourself by adding this line to your Comparator.compare lambda:

System.out.printf("(%s, %s)%n", o1, o2);

As you’ll see, there is no guarantee that adjacent values are passed to the Comparator.  When o1 is "three" and o2 is "one", the comparison falls back to returning zero, which tells the TreeSet that the two values are equal, and obviously it won’t add a value it perceives as equal to a value that’s already in the set.

You would need to make your traversal of greaterThan transitive.  I’m pretty sure it will require recursion:

private boolean isGreater(String o1,
                          String o2,
                          Set<String> keysTried) {
    Set<String> greaterSet = greaterThan.get(o1);
    if (greaterSet == null) {
        return false;
    }

    if (greaterSet.contains(o2)) {
        return true;
    }

    for (String g : greaterSet) {
        if (keysTried.add(g) && isGreater(g, o2, keysTried)) {
            return true;
        }
    }

    return false;
}

public StringSorter() {
    order = new TreeSet<>((o1, o2) -> {
        if (isGreater(o1, o2, new HashSet<>())) {
            return 1;
        } else if (isGreater(o2, o1, new HashSet<>())) {
            return -1;
        } else {
            return 0;
        }
    });
}

The purpose of keysTried is to prevent infinite recursion.  (In theory, that should never happen anyway, if greaterThan is a directed graph.)


问:
Table cell shrinks after finished Loading page
So I have to pages which are the same.  Each are displaying some articles in a table layout.  The table layout and CSS are the same.  However, the one page is listing hundreds of archive articles which after it gets about 80% loaded, the table cell that contains all the text shrinks to about 30% of the actual row width.

However, there is nothing different on the layout, properties, CSS.  The row containing the cell that is shrinking is the right width.  The odd thing is even if I put a "width="100%" on the cell in question, it still is short of the row's width by about 20%.

Any thoughts, suggestions?

NOTE: I removed the text and just left the actual layout and cell/table/row properties.
Correct page:

```<code><tr>
  <td>
  <table width="100%" cellpadding="4">
    <tbody><tr>
     <td width="100%" valign="top" align="left">
       <a class="docnavigation" href="removed link ">
        <strong></strong>
        </a>
         <br>
          <span class="steelNewsArticleDate"> </span> - <span class="Normal">
         <br>
       </span>
     </td>
    </tr>
  </tbody>
</table>
</code>```

Problem Page:

```<code><tr>
 <td>
  <table width="100%" cellpadding="4">
   <tbody><tr>
    <td width="100%" valign="top" align="left">
       <a href="removed link" class="docnavigation">
        <strong>  </strong>
        </a>
        <br>
        <span class="steelNewsArticleDate"></span> - <span class="Normal">
       <br>
       </span>
     </td>
   </tr>
  </tbody>
</table>
</code>```

答: The problem had to do with a missing tag from a Wysiwyg editor cleaning up some bad HTML incorrectly.  So it was forcing what would have been a parent row into a child table row.</p>

Body:
So I have to pages which are the same.  Each are displaying some articles in a table layout.  The table layout and CSS are the same.  However, the one page is listing hundreds of archive articles which after it gets about 80% loaded, the table cell that contains all the text shrinks to about 30% of the actual row width.

However, there is nothing different on the layout, properties, CSS.  The row containing the cell that is shrinking is the right width.  The odd thing is even if I put a "width="100%" on the cell in question, it still is short of the row's width by about 20%.

Any thoughts, suggestions?

NOTE: I removed the text and just left the actual layout and cell/table/row properties.
Correct page:

            -

Problem Page:

         -


问:
Camera2 api problems firing flash/no flash images
I will explain my case.
I'm trying to do an application in which every 5 seconds will take an image, one without flash, and then after 5 seconds one with flash, and repeat this every time. So it will take one without flash, one with flash, one without flash, one with flash... infinitely.

The case is that with my code I can do this in some devices, but the same code won't work in others as I want. i.e:

BQ Aquaris X5 Plus : The no-flash image is correct, but the flash image will be just white.

BQ Aquaris E5 : Won't fire the flash.

How can this be possible, all devices in which I have tried are LEGACY hardware support level for Camera2 API.

This are some important methods in my code (I can't post all code due to char limit). I started from the Google Example:

This setAutoFlash does the mentioned above.

```<code>private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            if(phototaken) {
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }else{
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);
            }
        }
    }
</code>```

This other one works in some devices and the bq aquaris e5 but doesn't fire the flash in the bq aquaris x5 plus.

```<code>private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            if(phototaken) {
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }else{
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
        }
    }
</code>```

And my captureStillPicture

```<code>private void captureStillPicture() {
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }
            // This is the CaptureRequest.Builder that we use to take a picture.
            final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // Use the same AE and AF modes as the preview.
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            setAutoFlash(captureBuilder);

            // Orientation
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("Saved: " + mFile);
                    Log.d(TAG, mFile.toString());
                    unlockFocus();
                }
            };

            mCaptureSession.stopRepeating();
            mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
            phototaken = !phototaken;

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
}
</code>```

The question is, what am i doing wrong so it doesn't work in all devices? Any help will be great.

答:
There are two levels of control for the flash - manual, and controlled by the auto-exposure routine. You're currently mixing them together.

If you want to fire the flash manually, then you need to set AE_MODE to either AE_MODE_OFF or AE_MODE_ON; not any of the FLASH modes.  Then, FLASH_MODE will control whether the flash will be in torch mode, off, or fire once for a given request.

Since you're always leave AE_MODE in one of the FLASH states, what you do to FLASH_MODE should not matter, barring a bug in some specific device.

If you want to guarantee flash firing in every other picture, you need to use AE_MODE_ON_ALWAYS_FLASH for the force-flash photos, and you need to use AE_MODE_ON for the no-flash phoots; don't touch FLASH_MODE.
Right now, with AUTO_FLASH, it's up to the device whether to fire a flash or not, so you'll see different behavior from different devices and lighting conditions - some will fire, some won't.

The other key thing you're not doing is running a precapture sequence; this is essential for flash pictures, because it allows the device to fire the preflash to determine correct flash power, focus, and white balance.

To run precapture, set the AE_MODE as desired, and then set AE_PRECAPTURE_TRIGGER to START for one request. This will transition AE_STATE to PRECAPTURE, and it'll stay there for some number of frames; once AE_STATE is no longer PRECAPTURE, you can issue the actual image capture request.  Make sure you keep the AE_MODE consistent throughout this.

The sample app Camera2Basic implements the precapture sequence, so take a look there; it also has some optimizations that skip precapture in case the scene is not dark enough to need flash, but since you want to force-fire flash, that's not relevant to you.

Body:
I will explain my case.
I'm trying to do an application in which every 5 seconds will take an image, one without flash, and then after 5 seconds one with flash, and repeat this every time. So it will take one without flash, one with flash, one without flash, one with flash... infinitely.

The case is that with my code I can do this in some devices, but the same code won't work in others as I want. i.e:

BQ Aquaris X5 Plus : The no-flash image is correct, but the flash image will be just white.

BQ Aquaris E5 : Won't fire the flash.

How can this be possible, all devices in which I have tried are LEGACY hardware support level for Camera2 API.

This are some important methods in my code (I can't post all code due to char limit). I started from the Google Example:

This setAutoFlash does the mentioned above.

private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            if(phototaken) {
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }else{
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_SINGLE);
            }
        }
    }

This other one works in some devices and the bq aquaris e5 but doesn't fire the flash in the bq aquaris x5 plus.

private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            if(phototaken) {
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }else{
                requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
                requestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
        }
    }

And my captureStillPicture

private void captureStillPicture() {
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }
            // This is the CaptureRequest.Builder that we use to take a picture.
            final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // Use the same AE and AF modes as the preview.
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            setAutoFlash(captureBuilder);

            // Orientation
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("Saved: " + mFile);
                    Log.d(TAG, mFile.toString());
                    unlockFocus();
                }
            };

            mCaptureSession.stopRepeating();
            mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
            phototaken = !phototaken;

        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
}

The question is, what am i doing wrong so it doesn't work in all devices? Any help will be great.


问:
Prevent click events in a FrameLayout
I have a FrameLayout, inside the FrameLayout I have two views, one a is a ViewPager and the other is a LinearLayout, the LinearLayout acts like a window, so it has some buttons. I show and hide the LinearLayout using the visibility property. The problem is when I show the LinearLayout, it covers the ViewPager but the user can still scroll the ListView inside the ViewPager. I want to prevent all the click events to the view behind.

The XML looks something like this:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/colorBeige"
          android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_diner_food"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:titleTextColor="@android:color/white"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"/>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout_diner_food"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/white"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager_diner_food"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linea_layout_filter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlackAlpha">

        <com.wonderkiln.blurkit.BlurLayout
            android:id="@+id/blurLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipChildren="true"
                android:orientation="vertical">

                <SeekBar
                    android:id="@+id/seek_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="61dp"/>
            </LinearLayout>
        </com.wonderkiln.blurkit.BlurLayout>
    </LinearLayout>
</FrameLayout>
</code>```

答:
It will prevent scroll in ListView when you click on any part of LinearLayout.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@color/colorBeige"
      android:orientation="vertical">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_diner_food"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/white"
android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:titleTextColor="@android:color/white"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout_diner_food"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="@android:color/white"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager_diner_food"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>

<LinearLayout
    android:id="@+id/linea_layout_filter"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBlackAlpha">

    <com.wonderkiln.blurkit.BlurLayout
        android:id="@+id/blurLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="true"
            android:orientation="vertical">

            <SeekBar
                android:id="@+id/seek_bar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="61dp"/>
        </LinearLayout>
    </com.wonderkiln.blurkit.BlurLayout>
</LinearLayout>
</FrameLayout>
</code>```

Title: Prevent click events in a FrameLayout

Body:
I have a FrameLayout, inside the FrameLayout I have two views, one a is a ViewPager and the other is a LinearLayout, the LinearLayout acts like a window, so it has some buttons. I show and hide the LinearLayout using the visibility property. The problem is when I show the LinearLayout, it covers the ViewPager but the user can still scroll the ListView inside the ViewPager. I want to prevent all the click events to the view behind.

The XML looks something like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@color/colorBeige"
          android:orientation="vertical">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_diner_food"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@android:color/white"
    android:contentInsetLeft="0dp"
    android:contentInsetStart="0dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:titleTextColor="@android:color/white"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"/>

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout_diner_food"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:background="@android:color/white"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/view_pager_diner_food"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"/>

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linea_layout_filter"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorBlackAlpha">

        <com.wonderkiln.blurkit.BlurLayout
            android:id="@+id/blurLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:clipChildren="true"
                android:orientation="vertical">

                <SeekBar
                    android:id="@+id/seek_bar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="61dp"/>
            </LinearLayout>
        </com.wonderkiln.blurkit.BlurLayout>
    </LinearLayout>
</FrameLayout>

Body:
It will prevent scroll in ListView when you click on any part of LinearLayout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:background="@color/colorBeige"
      android:orientation="vertical">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_diner_food"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@android:color/white"
android:contentInsetLeft="0dp"
android:contentInsetStart="0dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:titleTextColor="@android:color/white"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout_diner_food"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="@android:color/white"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager_diner_food"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>

<LinearLayout
    android:id="@+id/linea_layout_filter"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBlackAlpha">

    <com.wonderkiln.blurkit.BlurLayout
        android:id="@+id/blurLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="true"
            android:orientation="vertical">

            <SeekBar
                android:id="@+id/seek_bar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="61dp"/>
        </LinearLayout>
    </com.wonderkiln.blurkit.BlurLayout>
</LinearLayout>
</FrameLayout>


问:
Java: How to get the caller function name
To fix a test case I need to identify whether the function is called from a particular caller function. I can't afford to add a boolean parameter because it would break the interfaces defined. How to go about this?

This is what I want to achieve. Here I can't change the parameters of operation() as it is an interface implementation.

```<code>operation()
{
   if not called from performancetest() method
       do expensive bookkeeping operation
   ...

}
</code>```

答:
Another sample for android usage:

```<code>//package your.package.name;
import android.util.Log;
/*
 File name: MyDebugLog.java
*/
public class MyDebugLog {
    private static final int    index      = 4;     // <== Index in call stack array
    private static final String methodName = "Log"; // <== Name of method for public call
    private static String getCallerName() {
        String caller = "NONE";
        final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stacktrace.length; i++) {
            Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
        }
        if (stacktrace.length >= index){
            caller = stacktrace[index].getMethodName();
        }
        return caller;
    }

    private static String getTag() {
        String tag = "NONE";
        final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stacktrace.length; i++) {
            Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
            if (stacktrace[i].getMethodName().equals(methodName)) {
                tag = "("+stacktrace[i + 1].getFileName() + ":" + stacktrace[i + 1].getLineNumber()+")";
                return tag;
            }
        }
        return tag;
    }

    public static void Log(String message){
        Log.v(getTag(), getCallerName() + " " + message);
    }
}
</code>```

Usage:

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sample_main);
            MyDebugLog.Log("XXXXX");
    }
</code>```

Output:

```<code>    V/(MainActivity.java:117): onCreate XXXXX
</code>```

Sample of arrays:

```<code> getTag Sample of stacktace array:

    Method: [0]getThreadStackTrace
    Method: [1]getStackTrace
    Method: [2]getTag
    Method: [3]Log                 <== Method for external call
    ...
 getName Sample of stacktace array:
    Method: [0]getThreadStackTrace
    Method: [1]getStackTrace
    Method: [2]getCallerName
    Method: [3]Log
    Method: [4]onCreate            <== Our external method
    Method: [5]performCreate
    ...
</code>```

Body:
To fix a test case I need to identify whether the function is called from a particular caller function. I can't afford to add a boolean parameter because it would break the interfaces defined. How to go about this?

This is what I want to achieve. Here I can't change the parameters of operation() as it is an interface implementation.

operation()
{
   if not called from performancetest() method
       do expensive bookkeeping operation
   ...

}

Body:
Another sample for android usage:

//package your.package.name;
import android.util.Log;
/*
 File name: MyDebugLog.java
*/
public class MyDebugLog {
    private static final int    index      = 4;     // <== Index in call stack array
    private static final String methodName = "Log"; // <== Name of method for public call
    private static String getCallerName() {
        String caller = "NONE";
        final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stacktrace.length; i++) {
            Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
        }
        if (stacktrace.length >= index){
            caller = stacktrace[index].getMethodName();
        }
        return caller;
    }

    private static String getTag() {
        String tag = "NONE";
        final StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stacktrace.length; i++) {
            Log.e("Method ", "[" + i + "]" + stacktrace[i].getMethodName());
            if (stacktrace[i].getMethodName().equals(methodName)) {
                tag = "("+stacktrace[i + 1].getFileName() + ":" + stacktrace[i + 1].getLineNumber()+")";
                return tag;
            }
        }
        return tag;
    }

    public static void Log(String message){
        Log.v(getTag(), getCallerName() + " " + message);
    }
}

Usage:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sample_main);
            MyDebugLog.Log("XXXXX");
    }

Output:

    V/(MainActivity.java:117): onCreate XXXXX

Sample of arrays:

 getTag Sample of stacktace array:

    Method: [0]getThreadStackTrace
    Method: [1]getStackTrace
    Method: [2]getTag
    Method: [3]Log                 <== Method for external call
    ...
 getName Sample of stacktace array:
    Method: [0]getThreadStackTrace
    Method: [1]getStackTrace
    Method: [2]getCallerName
    Method: [3]Log
    Method: [4]onCreate            <== Our external method
    Method: [5]performCreate
    ...


问:
Looping through rows to copy one based on condition
I have code that will loop through my worksheet, but it performs copies all of the rows and not just the ones based on my criteria. How would I get it to only copy the row I want?</p>

```<code>Sub Major2_Paster()

Dim LastRow As Integer
Dim i As Integer
Dim erow As Integer

LastRow = Cells(Rows.count, 1).End(xlUp).Row

For i = 2 To LastRow
If Cells(i, 12) = “MLA” Then
range(Cells(i, 1), Cells(i, 21)).Select
Selection.Copy

Workbooks.Open Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx"
erow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row

ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False

End If

Next i
End Sub
</code>```

答:
A couple of things:

Only open the workbook once, this will be the most significant performance boost

Create references to workbooks/worksheets rather than using ActiveSheet/ActiveWorkbook

Indenting is so important. It makes code so much more readable and it's the first step in finding your own errors

```<code> Sub Major2_Paster()
    Dim LastRow As Integer, i As Integer, erow As Integer
    Dim destinationWorkbook As Workbook
    Dim sourceWorksheet As Worksheet, destinationWorksheet As Worksheet

    Set destinationWorkbook = Workbooks.Open(Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx")

    Set sourceWorksheet = ThisWorkbook.Worksheets("SheetName")
    Set destinationWorksheet = destinationWorkbook.Worksheets("SheetName")

    With sourceWorksheet
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    For i = 2 To LastRow
        If sourceWorksheet.Cells(i, 12).Value = “MLA” Then
            With destinationWorksheet
                erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
            End With
            destinationWorksheet.Cells(erow, 1).Resize(1, 21).Value = sourceWorksheet.Range(sourceWorksheet.Cells(i, 1), sourceWorksheet.Cells(i, 21)).Value
        End If
    Next i
    destinationWorkbook.Close SaveChanges:=True

    Application.CutCopyMode = False
End Sub
</code>```

Body:
I have code that will loop through my worksheet, but it performs copies all of the rows and not just the ones based on my criteria. How would I get it to only copy the row I want?

Sub Major2_Paster()

Dim LastRow As Integer
Dim i As Integer
Dim erow As Integer

LastRow = Cells(Rows.count, 1).End(xlUp).Row

For i = 2 To LastRow
If Cells(i, 12) = “MLA” Then
range(Cells(i, 1), Cells(i, 21)).Select
Selection.Copy

Workbooks.Open Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx"
erow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Offset(1, 0).Row

ActiveSheet.Cells(erow, 1).Select
ActiveSheet.Paste
ActiveWorkbook.Save
ActiveWorkbook.Close
Application.CutCopyMode = False

End If

Next i
End Sub

Body:
A couple of things:

Only open the workbook once, this will be the most significant performance boost

Create references to workbooks/worksheets rather than using ActiveSheet/ActiveWorkbook

Indenting is so important. It makes code so much more readable and it's the first step in finding your own errors

 Sub Major2_Paster()
    Dim LastRow As Integer, i As Integer, erow As Integer
    Dim destinationWorkbook As Workbook
    Dim sourceWorksheet As Worksheet, destinationWorksheet As Worksheet

    Set destinationWorkbook = Workbooks.Open(Filename:="H:\Degrees List\Sorted_Workbooks\MLA Mar-17.xlsx")

    Set sourceWorksheet = ThisWorkbook.Worksheets("SheetName")
    Set destinationWorksheet = destinationWorkbook.Worksheets("SheetName")

    With sourceWorksheet
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    End With

    For i = 2 To LastRow
        If sourceWorksheet.Cells(i, 12).Value = “MLA” Then
            With destinationWorksheet
                erow = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).Row
            End With
            destinationWorksheet.Cells(erow, 1).Resize(1, 21).Value = sourceWorksheet.Range(sourceWorksheet.Cells(i, 1), sourceWorksheet.Cells(i, 21)).Value
        End If
    Next i
    destinationWorkbook.Close SaveChanges:=True

    Application.CutCopyMode = False
End Sub


问:
How to test the equivalence of maps in Golang?
I have a table-driven test case like this one:

```<code>func CountWords(s string) map[string]int

func TestCountWords(t *testing.T) {
  var tests = []struct {
    input string
    want map[string]int
  }{
    {"foo", map[string]int{"foo":1}},
    {"foo bar foo", map[string]int{"foo":2,"bar":1}},
  }
  for i, c := range tests {
    got := CountWords(c.input)
    // TODO test whether c.want == got
  }
}
</code>```

I could check whether the lengths are the same and write a loop that checks if every key-value pair is the same. But then I have to write this check again when I want to use it for another type of map (say map[string]string).

What I ended up doing is, I converted the maps to strings and compared the strings:

```<code>func checkAsStrings(a,b interface{}) bool {
  return fmt.Sprintf("%v", a) != fmt.Sprintf("%v", b)
}

//...
if checkAsStrings(got, c.want) {
  t.Errorf("Case #%v: Wanted: %v, got: %v", i, c.want, got)
}
</code>```

This assumes that the string representations of equivalent maps are the same, which seems to be true in this case (if the keys are the same then they hash to the same value, so their orders will be the same). Is there a better way to do this? What is the idiomatic way to compare two maps in table-driven tests?

答:
Disclaimer: Unrelated to map[string]int but related to testing the equivalence of maps in Go, which is the title of the question

If you have a map of a pointer type (like map[*string]int), then you do not want to use reflect.DeepEqual because it will return false.

Finally, if the key is a type that contains an unexported pointer, like time.Time, then reflect.DeepEqual on such a map can also return false.

ContentLicense: CC BY-SA 4.0

Body:
I have a table-driven test case like this one:

func CountWords(s string) map[string]int

func TestCountWords(t *testing.T) {
  var tests = []struct {
    input string
    want map[string]int
  }{
    {"foo", map[string]int{"foo":1}},
    {"foo bar foo", map[string]int{"foo":2,"bar":1}},
  }
  for i, c := range tests {
    got := CountWords(c.input)
    // TODO test whether c.want == got
  }
}

I could check whether the lengths are the same and write a loop that checks if every key-value pair is the same. But then I have to write this check again when I want to use it for another type of map (say map[string]string).

What I ended up doing is, I converted the maps to strings and compared the strings:

func checkAsStrings(a,b interface{}) bool {
  return fmt.Sprintf("%v", a) != fmt.Sprintf("%v", b)
}

//...
if checkAsStrings(got, c.want) {
  t.Errorf("Case #%v: Wanted: %v, got: %v", i, c.want, got)
}

This assumes that the string representations of equivalent maps are the same, which seems to be true in this case (if the keys are the same then they hash to the same value, so their orders will be the same). Is there a better way to do this? What is the idiomatic way to compare two maps in table-driven tests?


答:
To get output from command you can use varibale=$(command) or

```<code>variable=$`command`
</code>```

Then you can use some simple condition on variable contents.

Title: Bash - How to check if command gave no output without printing it?

Body:
To get output from command you can use varibale=$(command) or

variable=$`command`

Then you can use some simple condition on variable contents.


问:
C++ cin reading string into int type returns 0
```<code>#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and age\n";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello, " << first_name << " (age " << age << ")!\n";
}
</code>```

If I type in Carlos for age or any other string I get a 0. How does this work(why)?

答:
Not sure why the question got down/close votes as it's clearly stated and not broad (and judging by the comments, many people don't know the answer)...

Anyway, for the code:

```<code>int age;
cin >> age;
</code>```

if the input stream did not contain any digits, then the stream is put into a fail state and age is set to 0. The characters in the input stream remain there; they can be read by a future read operation once the fail state is cleared.

The behaviour of operator>> is summarized on cppreference  , the full description in the standard is somewhat complicated.

Note: This changed in C++11; commentors reporting garbage output are either running compilers in pre-C++11 mode, or bugged ones.

Body:
#include <iostream>
using namespace std;
int main()
{
    cout << "Please enter your name and age\n";
    string first_name;
    int age;
    cin >> first_name;
    cin >> age;
    cout << "Hello, " << first_name << " (age " << age << ")!\n";
}

If I type in Carlos for age or any other string I get a 0. How does this work(why)?

Body:
Not sure why the question got down/close votes as it's clearly stated and not broad (and judging by the comments, many people don't know the answer)...

Anyway, for the code:

int age;
cin >> age;

if the input stream did not contain any digits, then the stream is put into a fail state and age is set to 0. The characters in the input stream remain there; they can be read by a future read operation once the fail state is cleared.

The behaviour of operator>> is summarized on cppreference  , the full description in the standard is somewhat complicated.

Note: This changed in C++11; commentors reporting garbage output are either running compilers in pre-C++11 mode, or bugged ones.


问:
PowerShell, vim and aliases vs. *.cmd (when using git)
I have a weird problem. I am using vim as my in-console text editor in PowerShell. That works very well so far and I don't really have an issue with that.

Previously I had vim set up with a batch script (vim.cmd) in a PATH-accessible folder, that simply calls the vim.exe, like this:

```<code>@echo off
"C:\Program Files\vim72\vim.exe" %*
</code>```

Then I told git to use the editor vim.cmd. That worked fine until I noticed that git has problems with executing batch when using interactive rebase.

So instead, I tried to make vim an alias in my PowerShell console instead:

```<code>Set-Alias vim "C:\Program Files\vim72\vim.exe"
</code>```

Then I told git to use the editor vim instead. This works very good, for both normal commits as well as interactive rebasing etc.. However I noticed something strange when using that:

It seems that either of those possibilities does not respect vim's settings correctly. When I make a commit, and git wants me to enter a commit message in git, I see two different appearances and behaviours of vim; although in both instances the same settings should be loaded (is there a way to check that actually?).

The following two screenshots show the differences in both editor setups:

What exactly is the reason for this, and is there a way to fix this? I would actually like to keep the alias version with the line break behaviour (and the disabled statusbar) from the other one; but understanding this is actually more important to me..

Thank you!

答:
Doh! Thanks to Doon for that comment, that actually made me realize it.

When using vim as git's core.editor value, that doesn't make git use the PowerShell alias at all. Instead, git calls vim from inside of its own bin directory, which does contain a file named vim with the following contents:

```<code>#!/bin/sh

exec /share/vim/vim73/vim "$@"
</code>```

So actually git is opening that vim instance which is shipped with Git itself and runs that instead. And there, of course my personal settings from my system's vim are missing.

After renaming the alias to something else for a moment and trying it, it turns out that git isn't able to use that, so I guess I'll just change that vim shell script inside the bin directory to point to my installation and copy some of the changes over to have my wanted effects.

Edit

Seems that from inside the /bin/ directory, git is unable to go outside of itself. So a folder parallel to the git installation is not reachable from within git's shell interpreter..

Guess I'll need to move my vim installation inside of the share directory then.. Good that all my other tools can easily work with a different vim location <_<

Body:
I have a weird problem. I am using vim as my in-console text editor in PowerShell. That works very well so far and I don't really have an issue with that.

Previously I had vim set up with a batch script (vim.cmd) in a PATH-accessible folder, that simply calls the vim.exe, like this:

@echo off
"C:\Program Files\vim72\vim.exe" %*

Then I told git to use the editor vim.cmd. That worked fine until I noticed that git has problems with executing batch when using interactive rebase.

So instead, I tried to make vim an alias in my PowerShell console instead:

Set-Alias vim "C:\Program Files\vim72\vim.exe"

Then I told git to use the editor vim instead. This works very good, for both normal commits as well as interactive rebasing etc.. However I noticed something strange when using that:

It seems that either of those possibilities does not respect vim's settings correctly. When I make a commit, and git wants me to enter a commit message in git, I see two different appearances and behaviours of vim; although in both instances the same settings should be loaded (is there a way to check that actually?).

The following two screenshots show the differences in both editor setups:

What exactly is the reason for this, and is there a way to fix this? I would actually like to keep the alias version with the line break behaviour (and the disabled statusbar) from the other one; but understanding this is actually more important to me..

Thank you!

Body:
Doh! Thanks to Doon for that comment, that actually made me realize it.

When using vim as git's core.editor value, that doesn't make git use the PowerShell alias at all. Instead, git calls vim from inside of its own bin directory, which does contain a file named vim with the following contents:

#!/bin/sh

exec /share/vim/vim73/vim "$@"

So actually git is opening that vim instance which is shipped with Git itself and runs that instead. And there, of course my personal settings from my system's vim are missing.

After renaming the alias to something else for a moment and trying it, it turns out that git isn't able to use that, so I guess I'll just change that vim shell script inside the bin directory to point to my installation and copy some of the changes over to have my wanted effects.

Edit

Seems that from inside the /bin/ directory, git is unable to go outside of itself. So a folder parallel to the git installation is not reachable from within git's shell interpreter..

Guess I'll need to move my vim installation inside of the share directory then.. Good that all my other tools can easily work with a different vim location <_<


问:
Select all but this element
I have a few accordions setup and I'd like only one to be open throughout the whole page. I thought that the .not() method would achieve what I wanted however it is just immediately closing the current div.

Here is what I have if anyone can spot where I've gone wrong:

JS

```<code>$( document ).ajaxComplete(function() {
$('.accordion-toggle').click(function(){

  //Expand or collapse this panel
  $(this).next().stop().slideToggle('1000');
  $(this).toggleClass('active').siblings().removeClass('active');

  //Hide the other panels
  $('.accordion-content').not(this).slideUp('1000');

});
});
</code>```

HTML

```<code><div id="location1">

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

</div>

<div id="location2">

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

<h3 class="accordion-toggle">Opening times <i class="fa fa-angle-down"></i></h3>
<div class="accordion-content">
<p>List of products available here!</p>
</div>

</div>
</code>```

CSS

```<code>.accordion-content {
  display: none;
  padding:20px 0;
  border-bottom: 1px solid #d4d5d7;
}

.accordion-content.default {display: block;}

.accordion-toggle {
  cursor: pointer;
  font-size:18px;
  padding:10px 0;
  margin:0;
  border-bottom:1px solid #d4d5d7;
  position:relative;
}
</code>```

答:
You were pretty close. You should change this line

```<code>$('.accordion-content').not(this).slideUp('1000');
</code>```

To This:

```<code>$('.accordion-toggle').not(this).next().slideUp('1000');
</code>```

Since your click function is applied to the accordion-toggle class, you have to target that class since this is an accordion-toggle class element, and you want to filter out all elements that are not this object. This will also force you to have to use the .next() method since you're looking to slide the next element in the DOM.

Edit 1:

In order to remove the active class across all of the #locationX divs, you should separate this line

```<code>$(this).toggleClass('active').siblings().removeClass('active');
</code>```

Into this:

```<code>$('.active').not(this).removeClass('active');
$(this).toggleClass('active');
</code>```

The way it was written previously, after the active class is toggled on the current element, it will only remove that class from all sibling elements, which won't properly affect elements in the other divs. It makes the script a bit longer, but it will remove all of the active classes before toggling the class on the current element.

Edit 2:

The simplest solution for the whole function is probably the following:

```<code>$('.accordion-toggle').click(function(){

    //Expand or collapse this panel
    $(this).next().stop().slideToggle('1000');

    //Hide the other panels
    $('.accordion-toggle').not(this).removeClass('active').next().slideUp('1000');
    $(this).toggleClass('active');

});
</code>```

Title: Select all but this element

Body:
I have a few accordions setup and I'd like only one to be open throughout the whole page. I thought that the .not() method would achieve what I wanted however it is just immediately closing the current div.

Here is what I have if anyone can spot where I've gone wrong:

JS

$( document ).ajaxComplete(function() {
$('.accordion-toggle').click(function(){

  //Expand or collapse this panel
  $(this).next().stop().slideToggle('1000');
  $(this).toggleClass('active').siblings().removeClass('active');

  //Hide the other panels
  $('.accordion-content').not(this).slideUp('1000');

});
});

HTML

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

Opening times

List of products available here!

CSS

.accordion-content {
  display: none;
  padding:20px 0;
  border-bottom: 1px solid #d4d5d7;
}

.accordion-content.default {display: block;}

.accordion-toggle {
  cursor: pointer;
  font-size:18px;
  padding:10px 0;
  margin:0;
  border-bottom:1px solid #d4d5d7;
  position:relative;
}

Body:
You were pretty close. You should change this line

$('.accordion-content').not(this).slideUp('1000');

To This:

$('.accordion-toggle').not(this).next().slideUp('1000');

Since your click function is applied to the accordion-toggle class, you have to target that class since this is an accordion-toggle class element, and you want to filter out all elements that are not this object. This will also force you to have to use the .next() method since you're looking to slide the next element in the DOM.

Edit 1:

In order to remove the active class across all of the #locationX divs, you should separate this line

$(this).toggleClass('active').siblings().removeClass('active');

Into this:

$('.active').not(this).removeClass('active');
$(this).toggleClass('active');

The way it was written previously, after the active class is toggled on the current element, it will only remove that class from all sibling elements, which won't properly affect elements in the other divs. It makes the script a bit longer, but it will remove all of the active classes before toggling the class on the current element.

Edit 2:

The simplest solution for the whole function is probably the following:

$('.accordion-toggle').click(function(){

    //Expand or collapse this panel
    $(this).next().stop().slideToggle('1000');

    //Hide the other panels
    $('.accordion-toggle').not(this).removeClass('active').next().slideUp('1000');
    $(this).toggleClass('active');

});


问:
Is getSimCountryIso returning 3 letters or 2 letters ISO code
I was wondering, is getSimCountryIso returning 2 letters or 3 letters ISO code? As this is not being mentioned in the documentation. I tested with my Nexus phone, it is returning 2 letters. However, I'm not sure this is true for other phones.

答: From the SIM cards I tried it returns lowercase two letter country codes.


问:
Write results to permanent table in bigquery
I am using named parameters in Bigquery SQL and want to write the results to a permanent table. I have two functions 1 for using named query parameters and 1 for writing query results to table. How do I combine the two to get query results written to table; the query having named parameters.

This is the function using parameterized queries :

```<code>def sync_query_named_params(column_name,min_word_count,value):
query = """with lsq_results as
(select "%s" = @min_word_count)
replace (%s  AS %s)
from lsq.lsq_results
""" % (min_word_count,value,column_name)

client = bigquery.Client()

query_results = client.run_sync_query(query
,
query_parameters=(
    bigquery.ScalarQueryParameter('column_name', 'STRING', column_name),
    bigquery.ScalarQueryParameter(
        'min_word_count',
        'STRING',
        min_word_count),
    bigquery.ScalarQueryParameter('value','INT64',value)
    ))
query_results.use_legacy_sql = False
query_results.run()
</code>```

Function to write to permanent table

```<code>class BigQueryClient(object):

   def __init__(self, bq_service, project_id, swallow_results=True):
        self.bigquery = bq_service
        self.project_id = project_id
        self.swallow_results = swallow_results
        self.cache = {}
   def write_to_table(
     self,
     query,
     dataset=None,
     table=None,
     external_udf_uris=None,
     allow_large_results=None,
     use_query_cache=None,
     priority=None,
     create_disposition=None,
     write_disposition=None,
     use_legacy_sql=None,
     maximum_billing_tier=None,
     flatten=None):

 configuration = {
    "query": query,
}

if dataset and table:
    configuration['destinationTable'] = {
        "projectId": self.project_id,
        "tableId": table,
        "datasetId": dataset
    }

if allow_large_results is not None:
    configuration['allowLargeResults'] = allow_large_results

if flatten is not None:
    configuration['flattenResults'] = flatten

if maximum_billing_tier is not None:
    configuration['maximumBillingTier'] = maximum_billing_tier

if use_query_cache is not None:
    configuration['useQueryCache'] = use_query_cache

if use_legacy_sql is not None:
    configuration['useLegacySql'] = use_legacy_sql

if priority:
    configuration['priority'] = priority

if create_disposition:
    configuration['createDisposition'] = create_disposition

if write_disposition:
    configuration['writeDisposition'] = write_disposition

if external_udf_uris:
    configuration['userDefinedFunctionResources'] = \
        [ {'resourceUri': u} for u in external_udf_uris ]

body = {
    "configuration": {
        'query': configuration
    }
}

logger.info("Creating write to table job %s" % body)
job_resource = self._insert_job(body)
self._raise_insert_exception_if_error(job_resource)
return job_resource
</code>```

How do I combine the 2 functions to write a parameterized query and write the results to a permanent table?Or if there is another simpler way. Please suggest.

答:
You appear to be using two different client libraries.

Your first code sample uses a beta version of the BigQuery client library, but for the time being I would recommend against using it, since it needs substantial revision before it is considered generally available. (And if you do use it, I would recommend using run_async_query() to create a job using all available parameters, and then call results() to get the QueryResults object.)

Your second code sample is creating a job resource directly, which is a lower-level interface. When using this approach, you can specify the configuration.query.queryParameters field on your query configuration directly. This is the approach I'd recommend right now.

Body:
I am using named parameters in Bigquery SQL and want to write the results to a permanent table. I have two functions 1 for using named query parameters and 1 for writing query results to table. How do I combine the two to get query results written to table; the query having named parameters.

This is the function using parameterized queries :

def sync_query_named_params(column_name,min_word_count,value):
query = """with lsq_results as
(select "%s" = @min_word_count)
replace (%s  AS %s)
from lsq.lsq_results
""" % (min_word_count,value,column_name)

client = bigquery.Client()

query_results = client.run_sync_query(query
,
query_parameters=(
    bigquery.ScalarQueryParameter('column_name', 'STRING', column_name),
    bigquery.ScalarQueryParameter(
        'min_word_count',
        'STRING',
        min_word_count),
    bigquery.ScalarQueryParameter('value','INT64',value)
    ))
query_results.use_legacy_sql = False
query_results.run()

Function to write to permanent table

class BigQueryClient(object):

   def __init__(self, bq_service, project_id, swallow_results=True):
        self.bigquery = bq_service
        self.project_id = project_id
        self.swallow_results = swallow_results
        self.cache = {}
   def write_to_table(
     self,
     query,
     dataset=None,
     table=None,
     external_udf_uris=None,
     allow_large_results=None,
     use_query_cache=None,
     priority=None,
     create_disposition=None,
     write_disposition=None,
     use_legacy_sql=None,
     maximum_billing_tier=None,
     flatten=None):

 configuration = {
    "query": query,
}

if dataset and table:
    configuration['destinationTable'] = {
        "projectId": self.project_id,
        "tableId": table,
        "datasetId": dataset
    }

if allow_large_results is not None:
    configuration['allowLargeResults'] = allow_large_results

if flatten is not None:
    configuration['flattenResults'] = flatten

if maximum_billing_tier is not None:
    configuration['maximumBillingTier'] = maximum_billing_tier

if use_query_cache is not None:
    configuration['useQueryCache'] = use_query_cache

if use_legacy_sql is not None:
    configuration['useLegacySql'] = use_legacy_sql

if priority:
    configuration['priority'] = priority

if create_disposition:
    configuration['createDisposition'] = create_disposition

if write_disposition:
    configuration['writeDisposition'] = write_disposition

if external_udf_uris:
    configuration['userDefinedFunctionResources'] = \
        [ {'resourceUri': u} for u in external_udf_uris ]

body = {
    "configuration": {
        'query': configuration
    }
}

logger.info("Creating write to table job %s" % body)
job_resource = self._insert_job(body)
self._raise_insert_exception_if_error(job_resource)
return job_resource

How do I combine the 2 functions to write a parameterized query and write the results to a permanent table?Or if there is another simpler way. Please suggest.


问:
'csc' is not recognized as an internal or external command, operable program or batch file
I'm fairly new to C# and I'm trying to use cmd to compile a basic hello world file called test.cs. It contains the following:

```<code>// Similar to #include<foo.h> in C++, includes system namespaces in a program

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    // A name space declaration, a class is a group of namespaces
    namespace Program1
    {
        class Hello // my class here, classes can contain multiple functions called methods which define it's behavior
        {
            static void Main(string[] args) // main method, just like in C/C++ it's the starting point for execution cycle
            {
                Console.WriteLine("Hello World");
                Console.ReadKey(); // similar to _getch() in C++ waits for user to input something before closing
            }
        }
    }

    /*
     * Other notes, .cs is a c# file extension
     * cs files can be built via terminal by using csc foo.cs to generate foo.exe run it with foo
     */
</code>```

When I try to run the line csc test.cs I get the following output:

答:
Locate the path of csc.exe and add it your PATH environment variable.

In my case, the path for 64-bit C# compiler  is C:\Windows\Microsoft.NET\Framework64\v4.0.30319.

Similarly, you can look for 32-bit C# compiler in C:\Windows\Microsoft.NET\Framework under different .NET framework version directories

There will be csc.exe for all versions like v2.0.XXXXX and v3.5. Select the one with the highest version in Framework64/Framework directory depending on your requirement.

Copy the path of csc.exe and add it to the PATH system environment variable.

Quit the cmd, and then launch again and run the program. That'd work.

Body:
I'm fairly new to C# and I'm trying to use cmd to compile a basic hello world file called test.cs. It contains the following:

// Similar to #include<foo.h> in C++, includes system namespaces in a program

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    // A name space declaration, a class is a group of namespaces
    namespace Program1
    {
        class Hello // my class here, classes can contain multiple functions called methods which define it's behavior
        {
            static void Main(string[] args) // main method, just like in C/C++ it's the starting point for execution cycle
            {
                Console.WriteLine("Hello World");
                Console.ReadKey(); // similar to _getch() in C++ waits for user to input something before closing
            }
        }
    }

    /*
     * Other notes, .cs is a c# file extension
     * cs files can be built via terminal by using csc foo.cs to generate foo.exe run it with foo
     */

When I try to run the line csc test.cs I get the following output:


问:
Merging mySQL database with PHP while maintaining field
Background: A group of students including me are creating a website for a merit system for our school. We basically had no experience in html, css, php or sql databases at the start. I will say we've managed decently.

However, we've run into a problem with updating the database. Every week, we need to merge the table for students from a csv, which is updated with classes and all from a department of education system. So there are thousands of students and each of them have certain details that when updated can change but others that need to stay the same. For example, we have the number of merits which needs to stay the same when we update but details such as their year group or classes can change. The thing is, is that this update is done of a csv file which may also have new students that need to be updated to the database and the csv is not in any order. So we are trying to find a solution which allows one field to be the same but allow others to change.

So we've tried LOAD DATA INFILE with a unique key but the problem we found was that while it preserved the merits, it ignored the other details and just added new students.

EDIT: So the students have a class field which contains the classes of the student. When we import, we need to be able to change that but still maintain the merit field which will not be in the csv file. We understand that we could just manually import it but suspect that will take a long time to run.

Our code will be in PHP by the way.

tl;dr
Need to find out how to merge/import databases from csv, changing only specific fields of existing students and also adding new students

Thanks in advance for your help and sorry for the long post. This is my first post so do forgive me if I make any mistakes.

答:
You will need a php script which reads the contents of the file, line by line preferably since it is a CSV. You will then need to use the primary key unique identifier from each CSV line to check whether a record with that primary key value already exists in the database. If a record with that primary key exists in the database, use the UPDATE query to update the merits only. If a record cannot be found with that primary key, use the INSERT statement to add that new record to the database.

NOTE: Bolded bits are steps required, in chronological order.