ASP.NET - Call Web Service From User Control ( .Ascx ) Returns Error 500 Internal Server Error

Question: so I have some problem. The Problem's Goal is that, when i try to call Web Service from User Control with Ajax, I got 500 Internal Server Error.
There is my code sample:
Web Service .CS
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class BudgetJson : System.Web.Services.WebService {

    public BudgetJson ()
    {
    }

    [WebMethod]
    public static String GetRecordJson()
    {
        return " Hello Master, I'm Json Data ";
    }
}

User Control ( .Ascx ) File ( Ajax Call )
$(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "BudgetJson.asmx",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg)
                {
                    alert(msg);
                }
            });
        });

So, when page loads and request is sent, I got such response:

soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was
  unable to process request. ---> System.Xml.XmlException: Data at
  the root level is invalid. Line 1, position 1.    at
  System.Xml.XmlTextReaderImpl.Throw(Exception e)    at
  System.Xml.XmlTextReaderImpl.Throw(String res, String arg)    at
  System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()    at
  System.Xml.XmlTextReaderImpl.ParseDocumentContent()    at
  System.Xml.XmlTextReaderImpl.Read()    at
  System.Xml.XmlTextReader.Read()    at
  System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
  at System.Xml.XmlReader.MoveToContent()    at
  System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
  at
  System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
  at
  System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
  at
  System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage
  message)    at
  System.Web.Services.Protocols.SoapServerProtocol.Initialize()    at
  System.Web.Services.Protocols.ServerProtocol.SetContext(Type type,
  HttpContext context, HttpRequest request, HttpResponse response)    at
  System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
  HttpContext context, HttpRequest request, HttpResponse response,
  Boolean& abortProcessing)    --- End of inner exception stack
  trace ---

If i will add method name to url, I got such error:

Unknown web method GetRecordJson. Parameter name: methodName
  Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method
  GetRecordJson. Parameter name: methodName

Any Solution ?
Answer: A couple things on the server-side:
The method should not be static. That's only the case for "page methods" on ASPX pages.
Second, you need to decorate the service class with the [ScriptService] attribute to be able to communicate with it in JSON, which I'm assuming you probably want to do since you're using jQuery.
[ScriptService]
public class BudgetJson : System.Web.Services.WebService {
  [WebMethod]
  public String GetRecordJson()
  {
    return " Hello Master, I'm Json Data ";
  }
}

On the client-side, you need to specify which method you want to execute in your $.ajax() URL:
$.ajax({
  type: "POST",
  url: "BudgetJson.asmx/GetRecordJson",
  data: "{}",
  // The charset and dataType aren't necessary.
  contentType: "application/json",
  success: function (msg) {
    alert(msg);
  }
});

You can also simplify the $.ajax() usage a bit, as shown above. The charset isn't necessary and jQuery automatically detects the dataType from the headers sent back from the server.
Comment: @AlekoGharibashvili There was a client-side issue I missed originally. Updated my answer.
Comment: Also updated client side script but nothing new, does this code works on your machine ? does there is some configurations problem ? if this code runs on your machine, please share your web.config file...
Comment: @AlekoGharibashvili The configuration requirements depend on which version of ASP.NET you're using. Have a look at this: http://encosia.com/asmx-scriptservice-mistakes-installation-and-configuration/
Comment: This project runs over .net 2.0. my web.config file is also like your sample. Does there is some IIS problem ?
Comment: @AlekoGharibashvili You'll need to install the ASP.NET Ajax Extensions on the server to get that working with ASP.NET 2.0 (as mentioned in the post I linked in my last comment; do what it says and it should work).


How to send asynchronous requests by guzzle without using proxy

Question: I am trying to send 100 requests to instagram website asynchronously by php guzzle like this:
$client = new Client();
$promises = [];
for($i = 1; $i <= 100; $i++)
{
    $options = ['timeout' => 60];

    $promise = $client->getAsync("https://www.instagram.com/p/B7IoQYhACcF/", $options)
            ->then(function($response){
                return $response;
            }, function($exception){
                return [
                    'msg' => $exception->getMessage(),
                ];
            });
    $promises[$i] = $promise;
}

after that I try to print requests status:
foreach ($promises as $key => $promise)
{
    $response = $promise->wait();

    if(is_array($response))
    {
        echo "{$key}) error: {$response['msg']}
";
        continue;
    }

    echo "{$key}) {$response->getStatusCode()} {$response->getReasonPhrase()}
";
}

ok! but what is the problem here?
The problem is that only the first 20 (or some more) requests are ok and other requests not resolved.
the result of this code is here:
1) 200 OK
2) 200 OK
3) 200 OK
4) 200 OK
5) 200 OK
6) 200 OK
7) 200 OK
8) 200 OK
9) 200 OK
10) 200 OK
11) 200 OK
12) 200 OK
13) 200 OK
14) 200 OK
15) 200 OK
16) 200 OK
17) 200 OK
18) 200 OK
19) 200 OK
20) 200 OK
21) 200 OK
22) 200 OK
23) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
24) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
25) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
26) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
27) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
28) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
29) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
30) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
31) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
32) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
33) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
34) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
35) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
36) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
37) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
38) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
39) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
40) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
41) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
42) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
43) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
44) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
45) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
46) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
47) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
48) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
49) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
50) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
51) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
52) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
53) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
54) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
55) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
56) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
57) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
58) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
59) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
60) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
61) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
62) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
63) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
64) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
65) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
66) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
67) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
68) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
69) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
70) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
71) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
72) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
73) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
74) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
75) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
76) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
77) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
78) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
79) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
80) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
81) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
82) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
83) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
84) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
85) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
86) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
87) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
88) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
89) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
90) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
91) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
92) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
93) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
94) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
95) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
96) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
97) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
98) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
99) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
100) error: cURL error 6: (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

note that I resolved this problem by using an http proxy but i cant use any proxies for doing that.
$options = ['timeout' => 60, 'proxy' => '188.8.131.52:8080'];

I think when I am using proxy to send requests, some of the guzzle(or cURL library) options are changed.
at final my question is that how can I send 100 async requests without using any proxies ?????
Answer: The function curl_multi() which is used in the background by Guzzle afaik only allows a specific number of parallel requests at once. You might want to configure that number higher like this
curl_multi_setopt($curlHandle, CURLMOPT_MAXCONNECTS, 100)

and/or check out the other curl multi options here.
Now you might be wondering how to set that option on the curl handle that guzzle is using. According to this you can pass the curl options as an array to the Handlerstack.
Excerpt from linked docs:
use \GuzzleHttp\Client;
use \GuzzleHttp\HandlerStack;
use \GuzzleHttp\Handler\CurlMultiHandler;

$client = new Client(['handler' => HandlerStack::create(new CurlMultiHandler([
    'options' => [
        CURLMOPT_MAX_TOTAL_CONNECTIONS => 50,
        CURLMOPT_MAX_HOST_CONNECTIONS => 5,
    ]
]))]);

Note that the mentioned options in the example might be relevant in your case as well.


Getting goto was unexpected at the time

Question: I am currently making a game that has a persuasion system in it.  I had all the code for one of the systems set up, but then I set up 2 more, and it started give me an error that said '(number) was not expected at this time'. when I put in 2 for the second choice, and 3 for the 3rd choice.
The code is like this.
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (

set "DEL=%%a"

)
set name=Quantum

cls

color 0a

Echo King Redwood: So 2000?

pause >nul

echo.

call :colorText 09 "1. 2500"

echo.

call :colorText 0e "2. 3000"
echo.
call :colorText 0c "3. 4000"
echo.
echo 4. 2000
echo.
set /p "purs=Enter:"
if /i %purs% == 1 (
goto CheckB )
if /i %purs% == 2 (
goto CheckY )
if /i %purs% == 3 (
goto CheckR )
if /i %purs% == 4 (
goto Convo )

:CheckB
set bleu=%random:~-2,1%
if %bleu% GTR 10 (
goto CheckB )
if %bleu% LSS 0 (
goto CheckB )
set /a  num = 3
set /a  reward = 2500
goto Res
:CheckY
set Yel=%random:~-2,1%
if %Yel% GTR 10 (
goto CheckY )
if %Yel% LSS 0 (
goto CheckY )
set /a num = 5
set reward = 3000
goto Res

:CheckR
set red=%random:~-2,1%
if %red% GTR 10 (
goto CheckB )
if %red% LSS 0 (
goto CheckB )
set /a num = 7
set /a reward = 4000
goto Res

:Convo
set /a reward = 2000
Echo %name%: I think that is a reasonable price.
Echo King Redwood: Very well.
Echo King Redwood: We will now take you to make sure you are
echo ready.
pause >nul

:Res
if %bleu% GEQ %num% goto Succeed
if NOT %bleu% GEQ %num% goto Fail

:Succeed
Echo %name%: I think that the struggles for such a long trip will be more then that
Echo %name%: How about %reward%?
Echo King Redwod: OK %reward% will work.
pause >nul
goto end

:Fail
Echo %name%: I think that you can give me %reward%.
Echo %name%: You know, for the struggles that there will be along the way.
echo If 2000 isn't good enough for you, I'll just have someone else do it.
pause >nul

:end
exit

:colorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1i

Comment: Comment out `@echo off` to see what actually happens; do not double-click the batch-file, but run it by opening a command prompt window and typing its path...
Comment: I made an edit,I changed the set num and set reward under :CheckR and Y to set /a instead, now. but that still gives me an error.
Comment: For instance, `%bleu%` is an empty string under `:res` because `bleu` is not set going through either `:CheckY` or `:CheckR` or `:Convo` (this list may be incomplete). Hence, `if %bleu% GEQ %num% goto Succeed` results to something like `if  GEQ 3 goto Succeed`… Apparently wrong syntax…
Comment: I tried changing the     %bleu% and all the other variables to something like color so that it was the same and in everything, but I still get the same problem.  Except now I get  it saying that 0 was unexpected at this time.  @JosefZ
Answer: First, make sure to close the FOR loop by putting a ) before :CheckB.
For the 'was not expected at this time' error, you're sometimes comparing an empty variable to something. For example, by following CheckY, you set Yel, then proceed to Res and check Bleu, which is empty because it hasn't been set. You're putting nothing next to the binary GEQ operator, and that's why it's complaining.
Tip: to debug, try inserting ECHO statements like this:
:Res
echo bleu=%bleu%,num=%num%

Another problem: when using SET, do not surround the = by spaces. SET /a will work with spaces around =, just because of the nature of /a, but plain SET will not. Well, it will append your variable name with a space and prepend your value with a space, which is not what you want.
Another tip: you can constrain what RANDOM returns through SET /a and the modulus operator, like this.
SET /a red=%random% %% 11

This will set red to a number between 0 and 10, so there is no need for the substrings and goto routines you're using after picking your random number.
Also, consider using EXIT /b to exit the batch file and not the whole CMD environment.
Comment: First, the  the `FOR` loop body is already closed by  `)`  parenthesis just before `set name=Quantum`…
Comment: Thank you.  This has helped me a lot. @soja.

Getting goto was unexpected at the time


Correct way to implement onMeasure() and onLayout() in custom AdapterView

Question: I know that I should measure children in onMeasure() and layout them in onLayout(). The question is in what of these methods should I add/recycle views so I could measure all children together with an eye on how they are mutually positioned (i.e. grid, list or whatever)?
My first approach was to add/recycle views in onLayout() but from that point I can't measure my children because they aren't added to AdapterView yet and getChildCount() returns 0 in onMeasure(). And I can't measure AdapterView itself without children being already layouted because it really depends upon their mutual positions, right?
I'm really confused with android layouting process in AdapterView when childrens are added/removed dynamically.
Comment: I have no idea how you would approach this. Personally, I would work off of `RecyclerView`. There, the work of laying out children is handled by a dedicated, pluggable manager class. There is a clearer API, and there are already third-party managers available that you can use (along with the three ones shipping in `recyclerview-v7`) to see how to approach the problem.
Answer: I can't post a comment because I'm a new user, but can you describe WHAT you're trying to do, as opposed to HOW you're trying to do it? Frequently, you will find that this is an issue of design as opposed to coding. Especially if you're coming from a different platform (example, iOS). From experience, I found that measuring and manual layouts in Android is mostly unnecessary if you design your layout properly in light of your business need.
EDIT:
As I mentioned this can be solved using some design decisions. I will use your Nodes/List example (hoping that this is your actual use case, but the solution can be expanded for a more general problem).
So if we think about your Header as a comment in a forum, and the List as replies to your comment, we can make the following assumption:

One list is enough, not two. Each item in the list can either be a header (comment) or a list item (reply). Each reply is a comment, but not all comments are replies.
For item n, I know if it's a comment or a reply (i.e. is it a header or an item in your list).
For item n, I have a boolean member isVisible (default false; View.GONE).

Now, you can use the following components:

One extended adapter class
Two Layout XMLs: One for your Comment, one for your reply. You can have unlimited comments and each comment can have unlimited replies. Both those satisfy your requirements.
Your fragment or activity container class that implements OnItemClickListener to show/hide your list.

So let's look at some code, shall we?
First, your XML files:
Comment row (your header)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/overall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true">

<TextView
    android:id="@+id/comment_row_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</RelativeLayout>

Now your reply row (an element in your list)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/overall"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
    android:id="@+id/reply_row_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"/>
</RelativeLayout>

Ok, now your adapter class
public class CommentsListAdapter extends BaseAdapter implements OnClickListener
{

public static String TAG = "CommentsListAdapter";

private final int NORMAL_COMMENT_TYPE = 0;
private final int REPLY_COMMENT_TYPE = 1;

private Context context = null;
private List<Comment> commentEntries = null;
private LayoutInflater inflater = null;

//All replies are comments, but not all comments are replies. The commentsList includes all your data. (Remember that the refresh method allows you to add items to the list at runtime.
public CommentsListAdapter(Context context, List<Comment> commentsList)
{
    super();

    this.context = context;
    this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.commentEntries = commentsList;

}
//For our first XML layout file
public static class CommentViewHolder
{
    public RelativeLayout overall;
    public TextView label;
}

//For our second XML
public static class ReplyViewHolder
{
    public RelativeView replyOverall;
    public TextView replyLabel;
}

@Override
public int getViewTypeCount()
{
    return 2; //Important. We have two views, Comment and reply.
}

//Change the following method to determine if the current item is a header or a list item.
@Override
public int getItemViewType(int position)
{
    int type = -1;
    if(commentEntries.get(position).getParentKey() == null)
        type = NORMAL_COMMENT_TYPE;
    else if(commentEntries.get(position).getParentKey() == 0L)
        type = NORMAL_COMMENT_TYPE;
    else
        type = REPLY_COMMENT_TYPE;

    return type;
}

@Override
public int getCount()
{
    return this.commentEntries.size(); //all data
}

@Override
public Object getItem(int position)
{
    return this.commentEntries.get(position);
}

@Override
public long getItemId(int position)
{
    return this.commentEntries.indexOf(this.commentEntries.get(position));
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    CommentViewHolder holder = null;
    ReplyViewHolder replyHolder = null;

    int type = getItemViewType(position);

    if(convertView == null)
    {
        if(type == NORMAL_COMMENT_TYPE)
        {
            convertView = inflater.inflate(R.layout.row_comment_entry, null);
            holder = new CommentViewHolder();
            holder.label =(TextView)convertView.findViewById(R.id.comment_row_label);
            convertView.setTag(holder);
        }
        else if(type == REPLY_COMMENT_TYPE)
        {
            convertView = inflater.inflate(R.layout.row_comment_reply_entry, null);
            replyHolder = new ReplyViewHolder();
            replyHolder.replyLable = (TextView)convertView.findViewById(R.id.reply_row_label);
            convertView.setTag(replyHolder);
        }
    }
    else
    {
        if(type == NORMAL_COMMENT_TYPE)
        {
            holder = (CommentViewHolder)convertView.getTag();
        }
        else if(type == REPLY_COMMENT_TYPE)
        {
            replyHolder = (ReplyViewHolder)convertView.getTag();
        }
    }
    //Now, set the values of your labels
    if(type == NORMAL_COMMENT_TYPE)
    {
        holder.label.setTag((Integer)position); //Important for onClick handling

        //your data model object
        Comment entry = (Comment)getItem(position);
        holder.label.setText(entry.getLabel());
    }
    else if(type == REPLY_COMMENT_TYPE)
    {
        replyHolder = (ReplyViewHolder)convertView.getTag(); //if you want to implement onClick for list items.

        //Or another data model if you decide to use multiple Lists
        Comment entry = (Comment)getItem(position);
        replyHolder.replyLabel.setText(entry.getLabel()));

        //This is the key
        if(entry.getVisible() == true)
           replyHolder.replyLabel.setVisibility(View.VISIBLE);
        else
          replyHolder.replyLabel.setVisibility(View.GONE);
    }

    return convertView;

}

//You can use this method to add items to your list. Remember that if you are using two data models, then you will have to send the correct model list here and create another refresh method for the other list.
public void refresh(List<Comment> commentsList)
{
    try
    {
        this.commentEntries = commentsList;
        notifyDataSetChanged();
    }
    catch(Exception e)
    {
        e.printStackTrace();
        Log.d(TAG, "::Error refreshing comments list.");
    }
}

//Utility method to show/hide your list items
public void changeVisibility(int position)
{
    if(this.commentEntries == null || this.commentEntries.size() == 0)
         return;
    Comment parent = (Comment)getItem(position);
    for(Comment entry : this.commentEntries)
    {
        if(entry.getParent().isEqual(parent))
           entry.setVisible(!entry.getVisible()); //if it's shown, hide it. Show it otherwise.
    }
    notifyDataSetChanged(); //redraw
}

}

Ok great, now we have a list of headers with hidden children (remember, we set the default visibility of children to 'gone'). Not what we wanted, so let's fix that.
Your container class (fragment or activity) you will have the following XML definition

<ListView
    android:id="@+id/comments_entries_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:divider="@null"
    android:dividerHeight="5dp" />

And your onCreateView will implement OnItemClickListener and have the following
private ListView commentsListView = null;
private List<Comment>comments = null;
private static CommentsListAdapter adapter = null;
....
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
 ...
 //comments list can be null here, and you can use adapter.refresh(data) to set the data
 adapter = new CommentsListAdapter(getActivity(), comments);
 this.commentsListView.setAdapter(adapter);
 this.commentsListView.setOnClickListener(this); //to show your list
}

Now to show your list when you click a header
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id)
{

     adapter.changeVisibility(position);

}

Now, if an item is clicked and that item has a parent (i.e. list item), it will be shown/hidden according to its current state.
Some comments about the code:

I wrote this on WordPad as I don't have a dev environment handy. Sorry for any compilation errors.
This code can be optimized: If you have a very large data set, this code would be slow since you're redrawing the entire list on every call to changeVisibility(). You can maintain two lists (one for headers, one for list items) and in changeVisibility you can query over the list items only).
I re-enforce that idea that some design decisions would make your life a lot easier. For example, if your list items were actually just a list of labels, then you can have one custom XML file (for your header) and a ListView view within it that you can set to View.GONE. This will make all other views pretend that it's not even there and your layout will work properly.

Hope this helps.


Do we need Async Storage for firebase auth to store user data in react native

Question: I have a question about firebase auth. After the user login, I can do anything. But when I close my app and reopen it again, I need to log in to my app again. To avoid this happening again and aging I used Async Storage to store the token, and login: true attribute. But I have doubts about this. I used rnfirebase.io to set up my firebse in my app. Is there a way to do this without Async Storage?.. Can anyone explain a little bit about this?
Thanks❤. (I used react native with redux-saga)
Answer: If you use react-redux middleware in react-native, you should use AsyncStorage as the middle-ware of saving persist state to reduce the calls to firebase.
It allow you to save the login state of users & other stuffs without have to request & auth again from firebase ( excerpt you can set timeout for it).
This is an example of store.js which can use AsyncStorage as middleware of redux to save state locally:

import { applyMiddleware, createStore, compose } from "redux";
import { persistStore, persistReducer } from "redux-persist";

import AsyncStorage from "@react-native-async-storage/async-storage";

import thunkMiddleware from "redux-thunk";
import { createLogger } from "redux-logger";

import reducer from "./reducers/"; // lets get the reducers
// create logger in DEV
const enhancers = [
    applyMiddleware(
        thunkMiddleware,
        createLogger({
            collapsed: true,
            predicate: () => __DEV__,
        })
    ),
];

const composeEnhancers =
    (__DEV__ &&
        typeof window !== "undefined" &&
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ||
    compose;

const enhancer = composeEnhancers(...enhancers);

const persistConfig = {
    key: "blabla", // key of storage
    storage: AsyncStorage,
    blacklist: [],
};

const persistedReducer = persistReducer(persistConfig, reducer);
export const store = createStore(persistedReducer, {}, enhancer);
export const persistor = persistStore(store);


Find the matrix of linear transformation with respect to different basis

Question: Let $f:P_2[x]\rightarrow M_{2\times 2}(\mathbb{R})$ is a linear transformation defined as $f(a+bx+cx^2)=        \begin{bmatrix}
        b+c & a  \\
        b & c \\
        \end{bmatrix}$
Find the matrix of $f$ with respect to basis $        ({\begin{bmatrix}
        1 & 0  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 1 \\
        \end{bmatrix}})$ and $(1,x,x^2)$. Find a basis and dimension of $Im (f)$ and $Ker(f)$.
In a standard basis for $P_2[x]$, the mapping is:
$$f        \begin{bmatrix}
        a  \\
        b  \\
        c  \\
        \end{bmatrix}=        \begin{bmatrix}
        0 + b + c \\
        a + 0 + 0 \\
        0 + b + 0 \\
        0 + 0 + c
        \end{bmatrix}\Rightarrow f=\begin{bmatrix}
        0 & b & c \\
        a & 0 & 0 \\
        0 & b & 0 \\
        0 & 0 & c
        \end{bmatrix}$$
Question: Is the matrix of $f$ the same for both basis  $ ({\begin{bmatrix}
        1 & 0  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 1 \\
        \end{bmatrix}})$ and $(1,x,x^2)$? If not, what is the method for finding the matrix of $f$ in both cases?
Answer: For the standard basis of $P_2[x]$, your answer is wrong: there can't be $a,b,c $ in the matrix, which should be:
$$\begin{pmatrix}
0&1&1\\1&0&0\\0&1&0\\0&0&1
\end{pmatrix}.$$
Now with the given basis of $P_2[x]$, first set
$$E_1=\begin{pmatrix}
1&0\\0&0
\end{pmatrix},\enspace
E_2=\begin{pmatrix}
1&1\\0&0
\end{pmatrix},\enspace
E_3=\begin{pmatrix}
1&1\\1&0
\end{pmatrix},\enspace
E_4=\begin{pmatrix}
1&1\\1&1
\end{pmatrix}.
$$
Then note that
\begin{align*}
f(1)=\begin{pmatrix}
0&1\\0&0
\end{pmatrix}&=E_2-E_1,
&f(x)=\begin{pmatrix}
1&0\\1&0
\end{pmatrix}&=E_3-E_2+E_1,\\
f(x^2)=\begin{pmatrix}
1&0\\0&1
\end{pmatrix}&=E_4-E_3+E_1.\\
\end{align*}
whence the matrix of $f$:
$$\begin{pmatrix}
-1&1&1\\1&-1&0\\0&1&-1\\0&0&1
\end{pmatrix}.$$
Answer: First of all, something about the notations. I would rather write
$$[f]_E^F        \begin{bmatrix}
        a  \\
        b  \\
        c  \\
        \end{bmatrix}=        \begin{bmatrix}
        0 + b + c \\
        a + 0 + 0 \\
        0 + b + 0 \\
        0 + 0 + c
        \end{bmatrix}\Rightarrow [f]_E^F=\begin{bmatrix}
        0 & 1 & 1 \\
        1 & 0 & 0 \\
        0 & 1 & 0 \\
        0 & 0 & 1
        \end{bmatrix}$$
instead of $f$ itself, since $f$ is not a matrix but an operator. $[f]_E^F$ is the matrix representation of $f$ with respect to the bases $E = \{1,x,x^2\}$ for $V = P_2$ and $F = \left\{\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix},\begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix},\begin{bmatrix}  0 & 0 \\ 1 & 0 \end{bmatrix},\begin{bmatrix} 0 & 0 \\ 0 & 1 \end{bmatrix}\right\}$ for $W = M_{2 \times 2}$.
The above matrix representation $[f]_E^F$ of $f$ with respect to $E$ and $F$ is constructed column-by-column sense where the $j$-th column of the matrix is determined by:

$v_j = x^{j-1}$ is the $j$-th vector in the basis $E$.
$f(v_j)$ is in the vector space $W$.
$f(v_j)$ can be written into a linear combination of the basis $F$.
$[f(v_j)]_F$ contains the coefficients of $f(v_j)$ with respect to the basis $F$.
$[f(v_j)]_F$ is the $j$-th column of $[f]_E^F$.

Now can you do the same with the basis $F$ replaced by $G = \left\{\begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix},\begin{bmatrix} 1 & 1 \\ 0 & 0 \end{bmatrix},\begin{bmatrix}  1 & 1 \\ 1 & 0 \end{bmatrix},\begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}\right\}$?
This is the direct way of doing this question. Another way is to use the matrix representation of composite of linear operators and the change of coordinate matrix. You can look for more if interested.
Answer: Your question is fuzzy: $f$ has one matrix with respect to the two given bases. So there is only one case.
Let's call the matrix we want to find $M_f$ and write the coefficients of the two given vectors down:
The vector $a + bx + cx^2$ with respect to the basis $(1,x,x^2)$ is $(a,b,c)$.
The vector $\begin{bmatrix}
        b+c & a  \\
        b & c \\
        \end{bmatrix}$ with respect to the basis $({\begin{bmatrix}
        1 & 0  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        0 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 0 \\
        \end{bmatrix},\begin{bmatrix}
        1 & 1  \\
        1 & 1 \\
        \end{bmatrix}})$ is $(b+c-a,a-b,b-c,c)$.
So, $M_f (a,b,c)^T = (b+c-a,a-b,b-c,c)^T$.
If you denote the $3$ columns of $M_f$ by $c_1, c_2, c_3$ then you want $c_i$ to be such that
$$ a c_1 + b c_2 + c c_3 = (b+c-a,a-b,b-c,c)$$
How to find the $c_i$?
Note that a linear map is uniquely determined by what it maps basis vectors to. In this case, we have the basis vectors
$$ 1 = (1,0,0)^T = b_1, x = (0,1,0)^T=b_2, x^2 = (0,0,1)^T = b_3$$
and
$$ M_f(b_1) = (-1,1,0,0), M_f(b_2) = (1,-1,1,0), M_f(b_3)=(1,0,-1,1)$$
Can you read the columns of $M_f$ off of this?


Line and Perpendicular Plane

Question: I have a parametric defined line as follows:
$<x,y,z>=<a,b,c>+t<d,e,f>$
$a,b,c,d,e,f$ are constants.
otherwise stated as
\begin{align}
     x &= a+dt \\
     y &= b+et \\
     z &= c+ft
\end{align}
I have this parametric line, and I have this point $P(g,h,i)$ this is not on the parametric line.
My question is how would you find the perpendicular plane I thought about doing it this way:
My Method:
$$A = (x,y,z)\Bigg\vert_{t=0}= (a,b,c)$$
$$B = (x,y,z)\Bigg\vert_{t=1}= (a+d,b+e,c+f)$$
$$C = (g,h,i)$$
These are 3 non-collinear points which I plan to formulate the equation of plane that is perpendicular to the parametric line. I hope since two of them are on the line that would not be an issue? Then I did the following:
\begin{align}
\vec{AB}&= \vec{OB}-\vec{OA} = <d,e,f> \\
\vec{BC}&= \vec{OC}-\vec{OB} = <g-(a+d), h-(b+e), i-(c+f)>
\end{align}
I then took the cross product of the two vectors:
$$\vec{AB} \times \vec{BC} = \det(\begin{bmatrix}
\vec{i} & \vec{j} & \vec{k} \\
d & e & f \\
g-(a+d) & h-(b+e) & i-(c+f)
\end{bmatrix})=\det(\begin{bmatrix}
e & f \\
h-(b+e) & i-(c+f)
\end{bmatrix})\vec{i}-\det(\begin{bmatrix}
d & f \\
g-(a+d) & i-(c+f)
\end{bmatrix})\vec{j}+\det(\begin{bmatrix}
d & e \\
g-(a+d) & h-(b+e)
\end{bmatrix})\vec{k}$$
which I call $\vec{n}= <m,n,o>$
With this normal vector $m, n, o$ being of course the determinants of the 2 by 2 minors of the 3 by 3 matrix. Using this normal vector I then did the following, and used this one to calculate the perpendicular plane to that line including that point P.
I began my method as the following I took the dot product of the normal vector $\vec{n}$, and $\vec{r}-\vec{r_0}$.
\begin{align}
\vec{n} \cdot (\vec{r}-\vec{r_0}) &= 0 \\
<m,n,o> \cdot (<x,y,z>-<g,h,i>) &= 0 \\
<m,n,o> \cdot <x-g,y-h,z-i> &= 0 \\
mx -mg +ny-nh + oz -oi &= 0 \\
mx +ny +oz -(mg +nh +oi) &= 0
\end{align}
The equation of the plane is given by the following equation:
$$mx +ny+oz -(mg +nh +oi) = 0$$
Is my method correct in tackling the problem that given a line find a perpendicular plane that contains the point P?
Answer: It is correct, but you can obtain an equation of the perpendicular plane in a much simpler way:
The directing vector of the line, with coordinates $(d,e,f)$, is a normal vector of the plane. If this plane passes through  the point $P(g,h,i)$,  a cartesian equation is simply
$$dx+ey+fz=dg+eh+fi.$$

Line and Perpendicular Plane


go vet complaining about loop variable being captured by func literal

Question: One of the common newbies' mistakes documented in go github's page, is neglecting to pass a loop variable as a parameter to the goroutine (in which the program's output could show unexpected results:
   for _, val := range values {
      go func() {
/* here is where go-vet complains loop variable v captured by func literal*/
          fmt.Println(val)
      }()
   }

there is a very good chance that when you run this code you will see
the last element printed for every iteration instead of each value in
sequence, because the goroutines will probably not begin executing
until after the loop.

So the proposed solution is (as said) to pass the actual loop var as goroutine parameter:
for _, val := range values {
    go func(val interface{}) {
        fmt.Println(val)
    }(val)
}

So what does go-vet nag about in the below example?
func main() {
    ch := make(chan int)

    for i := 0; i < 2; i++ {
        go func(emp int) {
            for range ch {
                rcv := <-ch
         /*  loop variable i captured by func literal */
                fmt.Printf("employee %d received signal %d\n", i, rcv)
            }
        }(i)
    }

}

Comment: you should also note that your `for range` is probably incorrect, as you're skipping every other element passed through the channel
Comment: Don't receive a second time in the loop, use the range expression. See the [Tour of Go](https://tour.golang.org/concurrency/4)
Comment: thanks. any suggestions on how to fix this?
Answer: This is the line:
fmt.Printf("employee %d received signal %d\n", i, rcv)

Here, use emp instead of i. You're passing in the loop variable as emp to the goroutine, but you seem to have forgotten to use it.


change database when clicking an  tag

Question: I am making a download counter. So i have a link, let's say:
rdp_download_31seqs
In my table "files" there is a column "timesdownloaded".
How can I increment this parameter by 1 when someone clicks on the link?
Thank you guys!
Comment: You've to make an ajax request to your server in order to execute the code that will update the timesdownloaded field in your table.
Comment: Errrrmm Which language by the way?
Comment: how do I do that? I'm dont have a clue about ajax
Answer: You're going to want to start by creating a download file, preferably in php, which will accept a file parameter. An example would be "download.php?file=42.txt". From there the file will update the download count, and fetch the file from the uploads folder.

change database when clicking an  tag


Is it permissible to wear hand gloves while fielding in cricket?

Question: Is it permissible for a fielder to wear hand gloves while fielding in cricket due to some climate conditions or infections?
we can see the football players wearing hand gloves while playing(but they won't deal the ball with the hand).
What does the Icc rules and laws of cricket say about this?
Answer: The rules are very clear, the wicket keeper is the only player allowed to wear gloves. All other players would incur a 5 run penalty every time they touched the ball while wearing gloves. This includes for instance taking off your hat in order to use it to catch the ball (I have seen this done in a park cricket match!).
See Law 41 in the rules of cricket

Law 41 (The fielder)

Protective equipment

No member of the fielding side other than the wicket-keeper shall be permitted to wear gloves or external leg guards. In addition, protection for the hand or fingers may be worn only with the consent of the umpires.

Fielding the ball

A fielder may field the ball with any part of his person but if, while the ball is in play he wilfully fields it otherwise,
  (a) the ball shall become dead and 5 penalty runs shall be awarded to the batting side. See Law 42.17 (Penalty runs). The ball shall not count as one of the over.

Note that the point about protection for the hand or fingers has been the source of some minor controversy over the years. Cricketers frequently injure their fingers while fielding and will often be seen with fingers taped up or two fingers taped together to protect a damaged finger. Usually this is permitted without any comment as it can actually make fielding harder. However, some players have at times gone a bit over the top and used sports tape to such an extent that they may as well be wearing a glove. As the law above suggests, it is up to the Umpires to judge if the tape being used is only what is required for a specific injury or is being used to gain an advantage.
The other convention that does not appear explicitly in the rules but is always adhered to is that spin bowlers may not use any tape or covering on their bowling hand. This is because tape would allow a much better grip on the ball allowing the bowler to impart much more spin than otherwise. It is also a matter of conditioning since spin bowling a lot of overs leads to blistering and even bleeding at the point of contact between the fingers and the ball. It is part of the art of spin bowling to build up the toughness of the hand to cope with this, rather than covering it with tape.
Comment: I have fielded with dislocated finger taped to the finger next to it, with consent of opposing captain and umpires. We agreed I shouldn't bowl though as the tape could have helped spin the ball.


Finding value of residual

Question: Consider the LSR line: y = 1158.86 - 5.54x
A researcher sought to examine the effect of average teacher salary on the average (total) SAT score.  The data, measured at the state level so 50 observations in total, were average teacher salary (measured in thousands of dollars) and average SAT scores out of 1600 points (the old SAT format).
Alabama has an average teacher salary (in thousands of dollars) of 31.14 and an average SAT score of 1029.  Based on the least squares regression line, what is the value of the residual for the state of Alabama?
Can someone explain what the residual is?  How do I calculate what it is in this case?  Why do they give me information about Alabama specifically (i.e. the salary and score)?
Comment: Is this homework?
Comment: If this is for some subject could you please add the `self-study` tag?
Answer: Think about what a residual is:
Residual = Observed value - Predicted value
$e$ = $y$ - $\hat{y}$
What is the observed value here?
What is the predicted value (from the regression formula)?

Finding value of residual


Average SAN cost per GB per year

Question: Are there any links/arctiles that describe an average price for buying/supporting of SAN solution per GB per year?
Answer: I'd be very surprised if you found any articles of this type because of all of the variables involved, these include but are not limited to;

Type of SAN (FC/iSCSI)
Manufacturer and model
Dual or single controller
Controller cache size
FC/NIC ports and speed
Min/Max capacity of controllers (i.e. number of disks/shelves supported)
Type/capacity/speed of disks supported
Additional functionality requiring licencing
Capacity licencing
Support requirements
Region/country of supply, vendor and client - all make huge difference to the cost

As you can see there are SO many things that would vary the cost of a given array that combining many models and configs from multiple manufacturers would not only be hard to do once but would be an ongoing job updating every time someone changed anything.
Given this was a very general question do you have a more specific one we could help you with?
Comment: Chopper really has given you some excellent advice and I suggest you heed it.

I do sense you're trying to build a business case for justification of a new SAN versus direct attached storage.  In that case, you'd probably want to talk to a reseller as they'd be able to look at your current configuration and help you build out a new solution.  At that point you can look at pros/cons and cost per gigabyte.
Comment: Oh dude, you can't have understood my post. If you bought a HDS top-end FC box with cross-site replication and backup, needed SSD speed plus oceans of cache, 24x7x365 support and you only wanted a single GB LUN well I reckon that would cost you about $500k per year - so that's about the most per GB you're likely to come across but honestly that's so unrealistic.
Comment: What would be the maximum of that cost?
Answer: Cost per GB for our systems are $5.42 for one system (FATA drives, in a Fibre Channel array) and $25.68 for another system (FC drives, in a Fibre Channel array). Those costs include backup costs, by the way. And we're not even paying anything for inter-array replication or snapshots. If we did, our costs on the more expensive array would be in the neighborhood of $40 or more.
As you can see, there is a wide spread on prices, for all the reasons Chopper3 pointed out.
Answer: IMHO, it might be interesting for you to compare the pricing of Amazon S3, and consider the different feature set and what value and disadvantages it will have compared to a SAN solution:
http://aws.amazon.com/s3/#pricing
Comment: S3 and a SAN fill two very different storage niches.

Average SAN cost per GB per year


Calculating group size from hazard ratio

Question: I am undertaking a systematic review and as part of the data extraction process I would like to know how many patients were analysed in the treatment and control arm (in a particular subgroup). In one included study, the only information given (for this particular subgroup) is the total number of patients analysed, the number of events in each arm and the hazard ratio with the CI. Based only on this information, is it possible to calculate the number of patients analysed in each arm (treatment arm and control arm)?
Thank you very much in advance for your help.
Answer: If this was a designed trial, do you have any reason to suppose that there were not approximately equal numbers in each arm within this subgroup?
The simplest way to get the information would be to ask the authors of the study; they should be prepared to provide supporting information to those who inquire about published work.
Failing that, I see no way to calculate the numbers, but you might be able to make a reasonable estimate. The hazard ratio represents the relative risk of events between the 2 arms. You might try an estimate assuming that the relative numbers of events would have been proportional to the hazard ratio if there were equal numbers in each arm, and solving for the numbers in each arm that would be consistent with the observed numbers of events and total number in the subgroup. The accuracy of this estimate will depend on the ways that the analysis was performed, the timings and distributions between arms of censored cases, etc., and might not work if almost all cases in an arm either had events or did not have events. But for your purposes that might be better than nothing, provided you specify in your review how you made your estimate and how errors in your estimate might influence the conclusions of your review.
Comment: Yes, in this study, patients were randomised in a 1:1 ratio so there should be equal numbers in each arm. I have worked on estimating the numbers using your explained method, which gave plausible values. I will also try to contact the authors. Thank you for your help, explanation and advices. Much appreciated.


why is a loop on a flat torus unshrinkable?

Question: I am reading Knows, Molecules, and the Universe: An Introduction to Topology.  A definition of for shrinkable has been given (pg. 68, chapter 3): If a loop can be pulled in, we say the loop is shrinkable. Otherwise, we say the loop is unshrinkable
Three examples are given: a curved torus with a loop around the hole, a knotted (trefoil, I think) torus that has a curve around the whole loop, and a loop crossing the left/right cut line of a flat torus.
I understand the first two just fine.  I don't understand the third.  It seems that the loop can be pulled in easily to me.
Comment: None of these are loops. A loop is supposed to start and end at the same point.
Comment: https://photos.app.goo.gl/n84cWqj36exRcS926
Comment: Yes, I agree with Moishe the figures are misleading as these are not loops. The last one can be thought as a torus by glueing the sides with same type of arrow. The top and bottom sides would create a "tube". Once you have glued those into a "tube" you need to glue the other two sides (left and right), that now are the top and bottom "circles" of the "tube". A bit rough as an explanation, but should give the intuition, I hope.
Answer: I browsed the book that you are reading. It is written by a good professional topologist, but is totally non-rigorous to the point where definitions are utterly lacking and (even intuitive) proofs are impossible. For instance, the notion of a "loop" is undefined and where it is used in pictures, it is rather an "arc", which is inconsistent with the common notion of a loop in topology. (On many pictures in the book a "loop" is an "arc" connecting a square to a triangle.) The notion of a "shrinkable loop" is defined as a "loop which can be pulled in", which is also left undefined. To make any sense of this, one will have to redraw the pictures so that the square equals the triangle, and the latter equals a point on the surface. A shrinkable loop then is "loosely speaking" a loop which can be continuously deformed to a single point. (Defining a "continuously deformation"  requires some work, but it is at least intuitively clear.)
If you want to continue reading this book, I suggest supplementing with a more rigorous basic algebraic topology book (parts related to fundamental groups) which will explain all this staff and will provide rigorous proofs. My personal favorite is
W.Massey, A Basic Course in Algebraic Topology, Chapters I and II.
Also:
J. Lee, Introduction to Topological Manifolds, Chapter 1-8, excluding the Category Theory and higher homotopy groups.
A.Hatcher, Algebraic Topology, Chapter 1. (Yes, there are many complaints about the book being too geometric, but, for most readers, this will be a plus.)
I would not recommend (to somebody who is not a pure mathematician) any of the other books  mentioned here.


Term reference field lists the terms for all the languages

Question: What I meant is that I have the i18n module installed and configured for content and taxonomies, this is what I need
I have a taxonomy called "Colors" I have translated all the terms of this taxonomy from spanish to english
I have a term reference field in a content type that points to the taxonomy "Colors"
While I create the the node of that content type and try to select a color, the select list shows me all the colors in english and spanish, is there a way of update that term reference select list to show only the terms for the selected language for that node?
Check the image and you will understand what I mean

If you check the image I selected in the list as language spanish, but in the color checkboxes it shows me all the terms in both languages (English & Spanish)
How to show the terms depending of the selected language while creating the node?
This is the image of the translated and original taxonomy terms in Spanish and English
Comment: What `Translation mode` you have selected for "Colors"? Did you translate the term or you created seperate term for each language?
Comment: In the edit page of the taxonomy I checked "Translate. Different terms will be allowed for each language and they can be translated."
Comment: Then can you post your term list and edit page screenshot
Comment: when you edit a term there will be a select box called **Language**, can you tell me what value you have for each term.
Comment: ok I added the the image of the taxonomy term list
Answer: Try selecting Localize. Terms are common for all languages, but their name and description may be localized as the Translation mode, after that remove the terms that you added separately for Spanish language and edit each term that are there in English and translate it to Spanish.
Answer: If you want different colors for each languages, set "Translate. Different terms will be allowed for each language and they can be translated." in the vocabolary terms, after check in admin/config/regional/i18n/select -> Select taxonomy terms by language


Qual o erro com meu script? - setTimeOut

Question: Olá!!
O script abaixo, pega uma imagem de id assinatura e aplica um efeito nela quando meu scroll está à certa altura do site.
$(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            $("#assinatura").addClass("animated jello");
        }
    });

Porém, eu gostaria de que quando o scroll atingisse 400 ou mais de altura, o programa esperasse 2 segundos para aplicar o efeito que eu queria. (2 segundos para teste).
Então tentei fazer da forma abaixo, mas que resultou na mesma coisa que o anterior, ou seja, o programa só está executando como se não ouvesse o setTimeOut:
$(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 400) {
            window.setTimeout($("#assinatura").addClass("animated jello"), 5000);
        }
    });

Answer: No console (F12) poderá ver que o problema é:
Uncaught SyntaxError: Unexpected identifier

O setTimeout espera que o primeiro parâmetro seja uma função ou uma string do código, veja aqui:
setTimeout(func[, delay, param1, param2, ...]);
setTimeout(code[, delay]);

Dessa forma você tem as seguintes soluções:
1. Criar uma função anonima:
setTimeout(function() {
    $("#assinatura").addClass("animated jello")
}, 5000);

2. Criar um função e chama-la:
function animate(){
   $("#assinatura").addClass("animated jello")
}

setTimeout(animate, 5000);

Se função exigir algum argumento você pode informar o valor após o delay.

3. Tornar uma string para um eval():
setTimeout('$("#assinatura").addClass("animated jello")', 5000);

Essa solução não é recomendada e variáveis locais não podem ser acessadas.
Comment: Não gosto da idéia de você dizer "como" arrumar mas não dizer "o que está errado" e por que.  O OP agora vai decorar que tem que colocar o "function" em volta de sua chamada, e achar que é mágica.
Comment: Dei uma melhorada e acrescentei a possibilidade sem a necessidade do `function`.
Answer: Tenta substituir este trecho:
if (scroll >= 400) {
    window.setTimeout($("#assinatura").addClass("animated jello"), 5000);
}

por
if (scroll >= 400) {
    window.setTimeout(function() {
        $("#assinatura").addClass("animated jello")
    }, 5000);
}

Ocorre que o parâmetro do setTimeout recebe uma função, e com seu código, você está chamando a função addClass imediatamente e passando o retorno dela.
Answer: Você tem que passar uma função e para o setInterval ou setTimeout. Ex:
setInterval(function(){ /*Minha declaração*/ },1000) ou setInterval(() => {/* Minha declaração */},1000)

Comment: O `setInterval` e `setTimeout` são funções completamente distintas, o `setInterval` irá executar a função a cada 1 segundo e não apenas após 1 segundo. :S


Transforming differential equation to polar coordinates, example.

Question:
... For example, if we write $\dfrac{\operatorname dy}{\operatorname dx} = \dfrac{-x}{y}$ in polar coordinates, we obtain the equation $\dfrac{\operatorname dr}{\operatorname d\theta} = 0$ whose solution is $r = C$.

Seems like a straightforward statement, but I don't seem to get there. I guess i'm doing something wrong... Could someone help?
If $x = r\cos \theta$, $y=r \sin \theta$ with the inverse transformation $r = \sqrt{x^2+y^2}$, $\theta = \arctan \dfrac{y}{x}$.
Then $\dfrac{-x}{y} = \dfrac{-\cos \theta}{\sin \theta}$
Next:
$$\dfrac{\operatorname dy}{\operatorname dx} \stackrel{\color{red}{(1)}}{=} \dfrac{\operatorname dy}{\operatorname dr}\cdot \dfrac{\operatorname dr}{\operatorname d\theta}\cdot \dfrac{\operatorname d\theta}{\operatorname dx} = \sin \theta \cdot  \dfrac{\operatorname dr}{\operatorname d\theta}\cdot \dfrac{-r\sin \theta}{r^2}$$
This results in:
$$\sin \theta \cdot  \dfrac{\operatorname dr}{\operatorname d\theta}\cdot \dfrac{-r\sin \theta}{r^2} = \dfrac{-\cos\theta}{\sin \theta}$$
or
$$\dfrac{\operatorname dr}{\operatorname d\theta}= \dfrac{r \cos\theta}{\sin^3 \theta}$$
Fault?
I suspect $\color{red}{(1)}$ is not right. Since $\dfrac{\operatorname dy}{\operatorname d r}$ doesn't make any sense. I should be using something like $\partial$, but how exactly?
Comment: I remember having similar problem,a quick revision of chain rule should make it clear. Please see this question http://math.stackexchange.com/questions/84736/how-to-do-a-change-of-variable-in-an-ode
Comment: Indeed, $(1)$ does not make sense because $r$ and $\theta$ are independent variables.
Answer: The fault is in:
$\frac{dy}{dx}=\frac{dy}{d\theta}\frac{d\theta}{dx} + \frac{dy}{dr}\frac{dr}{dx} $
Answer: $$\frac{dy}{dx}=\frac{dy}{d\theta}\times\frac{d\theta}{dx}=\frac{\frac{dy}{d\theta}}{\frac{dx}{d\theta}}\tag{1}$$$$x=r\cos(\theta)$$$$\therefore\frac{dx}{d\theta}=\cos(\theta)\frac{dr}{d\theta}-r\sin(\theta)\tag{2}$$$$y=r\sin(\theta)$$$$\therefore\frac{dy}{d\theta}=\sin(\theta)\frac{dr}{d\theta}+r\cos(\theta)\tag{3}$$Substituting (2) and (3) into (1) then gives:$$\frac{dy}{dx}=\frac{\sin(\theta)\frac{dr}{d\theta}+r\cos(\theta)}{\cos(\theta)\frac{dr}{d\theta}-r\sin(\theta)}$$Hopefully you can proceed from here...

The mistakes you made were in the calculations of $\frac{dy}{dr}$ and $\frac{dx}{d\theta}$:$$\frac{dy}{dr}=\sin(\theta)+r\cos(\theta)\frac{d\theta}{dr}$$$$\frac{dx}{d\theta}=-r\sin(\theta)+\cos(\theta)\frac{dr}{d\theta}$$Using these in your approach would have led to the same result as I got above, i.e.:$$\frac{dy}{dx}=\frac{dy}{dr}\cdot\frac{dr}{d\theta}\cdot\frac{d\theta}{dx}$$$$=\left(\sin(\theta)+r\cos(\theta)\frac{d\theta}{dr}\right)\cdot\frac{dr}{d\theta}\cdot\left(\frac{1}{-r\sin(\theta)+\cos(\theta)\frac{dr}{d\theta}}\right)$$$$=\frac{\sin(\theta)\frac{dr}{d\theta}+r\cos(\theta)}{\cos(\theta)\frac{dr}{d\theta}-r\sin(\theta)}$$
Answer: You could also view your problem as an equality of differential forms: $x\mathbb{d}x + y\mathbb{d}y =0$. Since $\mathbb{d}x=\mathbb{d}(r\cos \theta)=\cos \theta \mathbb{d}r-r \sin \theta \mathbb{d}\theta$ and $\mathbb{d}y= \sin \theta \mathbb{d}r+ r \cos \theta \mathbb{d} \theta$, a simple substitution makes this is equivalent to $0= r \cos^2 \theta \mathbb{d} r - r^2 \sin \theta \cos \theta \mathbb{d}\theta + r \sin^2 \theta \mathbb{d}r + r^2 \sin \theta \cos \theta \mathbb{d}\theta = r \mathbb{d}r$, which means $\mathbb{d}r=0$ which gives $r=constant$.


Right way to redirect to paypal with data

Question: I am altering the user registration form and sending the user to paypal on submission. I am fetching all the values and sending them in query. But when I am returning from there...I am not getting anything in $_POST variable...
I am wondering...what can be wrong here in my sending process. Here is my code --
//Form alter for registration form.
function user_type_register_form_alter(&$form, &$form_state, $form_id){
  switch($form_id) {
      case 'user_register_form':
        $form['account']['user_type'] = array(
          '#type' => 'select',
          '#title' => t('Membership Type:'),
          '#options' => array(
            0 => t('General $50.00/Yr'),
            1 => t('Student $50.00/Yr'),
            2 => t('Government $50.00/Yr'),
            ),
           '#weight' => 1,
           '#description' => t('Select the membership type, which you want to have.'),
          );
        $form['account']['user_type_submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
          '#submit' => array('user_type_register_form_submit'),
          '#validate' => array('user_type_register_form_alter_validate'),
          '#weight' => 10,
        );
        $form['account']['name']['#description'] = t('');
        $form['account']['mail']['#description'] = t('');
        $form['#method'] = 'post';
        unset ($form['actions']); //unset the default submit Button
        return $form;
      break;
    }
}

function user_type_register_form_submit($form, &$form_state){
  global $base_url;
  $username = $form_state['values']['name'];
  $user_email = $form_state['values']['mail'];
  $user_pass = $form_state['value']['password'];
  $user_type = $form_state['values']['user_type'];
  $user_first_name = $form_state['values']['field_first_name']['und'][0]['value'];
  $user_last_name = $form_state['values']['field_last_name']['und'][0]['value'];
  $user_company_name = $form_state['values']['field_company_name']['und'][0]['value'];
  $user_address_line_1 = $form_state['values']['field_address_line_1']['und'][0]['value'];
  $user_address_line_2 = $form_state['values']['field_address_line_2']['und'][0]['value'];
  $user_city = $form_state['values']['field_user_city']['und'][0]['value'];
  $user_state = $form_state['values']['field_user_state']['und'][0]['value'];
  $user_zip = $form_state['values']['field_user_zip']['und'][0]['value'];
  $user_phone_number = $form_state['values']['field_phone_number_']['und'][0]['value'];
  $user_mobile_number = $form_state['values']['field_mobile_number_']['und'][0]['value'];
  $user_fax_number = $form_state['values']['field_fax_number_']['und'][0]['value'];

  $paypal = array();
  $paypal['cmd'] = '_xclick';
  $paypal['business'] = 'email@example.com';
  $paypal['page_style'] = 'Primary';
  $paypal['bn'] = 'PP-DonationsBF';
  $paypal['item_name'] = 'Membership';
  $paypal['currency_code'] = 'USD';
  $paypal['no_shipping'] = '1';
  $paypal['tax'] = '0';
  $paypal['lc'] = 'US';
  $paypal['rm'] = '1';
  $paypal['notify_url'] = $base_url.'/?q=paypal/payment';
  $paypal['return'] = $base_url.'/?q=paypal/payment';
  $paypal['cancel_return'] = $base_url.'/?q=user/register';
  $paypal['uname'] = $username;
  $paypal['email'] = $user_email;
  $paypal['pass'] = $user_pass;
  if($user_type == 0){
    $paypal['user_type'] = 'General';
  }
  elseif($user_type == 1){
    $paypal['user_type'] = 'Student';
  }
  elseif ($user_type == 2){
    $paypal['user_type'] = 'Government';
  }
  $paypal['first_name'] = $user_first_name;
  $paypal['last_name'] = $user_last_name;
  $paypal['comp_name'] = $user_company_name;
  $paypal['address1'] = $user_address_line_1;
  $paypal['address2'] = $user_address_line_2;
  $paypal['city'] = $user_city;
  $paypal['state'] = $user_state;
  $paypal['zip'] = $user_zip;
  $paypal['phone'] = $user_phone_number;
  $paypal['mobile'] = $user_mobile_number;
  $paypal['fax'] = $user_fax_number;

  switch($user_type){
    case '0':
      //dpm("General");
      $membership_price = 10;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 1;

      $query = http_build_query($paypal, '', '&');

      //watchdog('Query--',$query);

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;

      break;

    case '1':
      //dpm("Student");
        $membership_price = 12;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 2;

      $query = http_build_query($paypal, '', '&');

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
      break;

    case '2':
      //dpm("Government");
      $membership_price = 15;
      $paypal['amount'] = $membership_price;
      $paypal['item_number'] = 3;

      $query = http_build_query($paypal, '', '&');

      $form_state['redirect'] = 'https://www.sandbox.paypal.com/cgi-bin/webscr?' .$query;
      break;
  }

}

Anybody have any idea about it ?
Answer: It doesn't look like a Drupal problem, but your wrong HTML variable for PayPal. You should use rm = 2 for POST.
$paypal['rm'] = '2';

Here is the description for its value:

Allowable values are:
  0 – all shopping cart payments use the GET method
  1 – the buyer's browser is redirected to the return URL by using the GET method, but no payment variables are included
  2 – the buyer's browser is redirected to the return URL by using the POST method, and all payment variables are included
  The default is 0.
  NOTE:
  Thermvariable takes effect only if the return variable is set.


where my '[]' is?, bash program

Question: in linux ,bash program.
I write this:
msg=`date  '+%m-%d %H:%M'`" alipay recharge [$sum] in past 15 mins"
echo $msg >> $MonitorLog

Mostly it works ,but sometime.the result will like this:
07-15 09:01 card recharge 0 in past 30 mins

My sentence changes. not 0, if $sum=0 ,it should be:
07-15 09:01 card recharge [0] in past 30 mins

I don't know where my '[]' is? can you help me ,thanks a lot.
Comment: try escaping your sq-brackets, ie. `...alipay recharge \[$sum\] ..`. Good luck.
Answer: You are hitting shell globbing. See the output below.
$ ls -l
total 4
-rw-r--r-- 1 root root 0 Jul 14 21:40 5
$ sum=10
$ msg=`date  '+%m-%d %H:%M'`" alipay recharge [$sum] in past 15 mins"
$ echo $msg
07-14 21:41 alipay recharge [10] in past 15 mins
$ sum=5
$ msg=`date  '+%m-%d %H:%M'`" alipay recharge [$sum] in past 15 mins"
$ echo $msg
07-14 21:41 alipay recharge 5 in past 15 mins
$ echo "$msg"
07-14 21:41 alipay recharge [5] in past 15 mins

Comment: @kojiro Actually, if you want to get technical this is `Pattern Matching` in the context of `Pathname expansion` (which is generally, and colloquially, called `globbing`). And since, in this case, this is in fact filename matching it is globbing in both the general and specific cases.
Answer: @Etan Reisinger's answer contains the crucial pointer:
Shell expansions are inadvertently applied to $msg, because it is unquoted.
tl;dr:
Double-quote your variable references to protect them from interpretation by the shell:
echo "$msg" >> "$MonitorLog"    # due to double-quoting, contents of $msg used as is

Generally, the only reason NOT to double-quote a variable reference is the express intent to have the shell interpret the value (apply expansions to it) - see below.

In the case at hand, here's what happens if you do not double-quote $msg:
After splitting the value of $msg into words by whitespace (word splitting), pathname expansion is applied to each:
I.e., each word that looks like a glob (a filename pattern), is matched against filenames - in the specified directory or, without a path component, in the current one - and if matches are found, that word is replaced by matching filenames.
A word such as [0] happens to be a valid glob ([...] encloses a set of matching characters; in this case, the set is made up of only 1 char., 0), and if a file named 0 happens to be present in the current directory, [0] is replaced by that matching filename, 0 - effectively making the [] disappear  - this is what happened in the OP's case.
(See man bash, section Pathname Expansion, for what constitutes valid globs.)

where my '[]' is?, bash program


Clarification on the Hausdorff property

Question: If $X$ is a Hausdorff space then for points $a,b \in X$ there are disjoint open sets $U$ and $V$ such that $a \in U$ and $b \in V$.  So, take a set of points $\{a_1, \ldots , a_n\}$ and another point $x$.  Then for each $a_i$ there are disjoint open sets $U_i$ and $V$ containing $a_i$ and $x$, respectively.
My question is: is $V$ disjoint from all the $U_i$, or does this only hold pairwise?  Are there conditions we can impose to guarantee an open set separating $x$ from all points in some given finite set?
Answer: Let $\{a_1, ..., a_n\}$ be a finite collection of points. Let $x$ be a point different from all the $a_i$'s. For each $i$, by being Hausdorff, there exists $U_i$ and $V_i$ such that $a_i \in U_i$, $x \in V_i$ and $U_i \cap V_i = \emptyset$.
Then $V = \bigcap_{1 \leq i \leq n} V_i$ is an open set (being a finite intersection of open set) containing $x$ which is disjoint from all the $A_i$'s.
Comment: Small Typo: $U_i$'s, not $A_i$'s.
Answer: I just want to point out that with the idea in William's proof, above, you can easily prove the following (seemingly more general) property:
If $X$ is Hausdorff and $x_1, \ldots , x_n \in X$ are distinct, then there are open neighbourhoods $V_1 , \ldots , V_n$ about $x_1, \ldots , x_n$, respectively, such that $V_i \cap V_j = \emptyset$ for $i \neq j$.
Answer: William's answer shows that for your example, the set $A=\{a_1,\ldots,a_n\}$ can be separated from the one-point set $B=\{x\}$ in any Hausdorff space.  ("Separated" here means there are disjoint open sets $U$ and $V$, containing $A$ and $B$ respectively.)  But as you can see, the proof only goes through because $A$ is finite.
A more general property, which holds for infinite sets $A$, is called "regularity".  A regular space is one in which every closed subset $S$ can be separated (in the sense of the previous paragraph) from each single point $x$.  If single points are closed, then this implies that the space is also Hausdorff, by taking $S$ to consist of some single point $y$. Hausdorff spaces may fail to be regular, however.
There is a whole family of these so-called separation axioms, and study of the relations between them is a significant field of study.

Clarification on the Hausdorff property


Precisely which sets of numbers have this "fieldable" property?

Question: Let $\mathbb{N}_2$ be the set of natural numbers greater than or equal to $2$. Given a field $F$ and a subset $S \subseteq \mathbb{N}_2$, I define $F$ to be an $S$-field if, for all $n \in S$, every $n$-th degree polynomial equation with coefficients in $F$ has a solution in $F$, and also, for every natural number $m \geq 2$ such that $m \notin S$, there exists at least one $m$-th degree polynomial with coefficients in $F$ which does not have a solution in $F$.
Let me give some examples. The rational numbers are a $\emptyset$-field, the complex numbers are a $\mathbb{N}_2$-field, and the real numbers are an $O$-field, where $O$ is the set of odd integers greater than or equal to $3$.
I define a subset $S$ of $\mathbb{N}_2$ to be fieldable if there exists a field $F$ such that $F$ is an $S$-field. Not every subset of $\mathbb{N}_2$ is fieldable. My question is, what are some necessary and sufficient conditions for a given subset $S$ of $\mathbb{N}_2$ to be fieldable?
Comment: An interesting variant of this question would be to reduce attention to irreducible polynomials with degrees in $S$, rather than all polynomials.
Comment: Building on the answer to your [earlier question](https://math.stackexchange.com/a/4723841/7062), if $F$ is an $S$-field, then $S$ is factor-closed, in the sense that if $m\mid n$ and $n\in S$, then $m\in S$. Indeed, if $n\in S$, $md = n$, and $p$ is a polynomial of degree $m$, then $p^d$ is a polynomial of degree $n$, so it has a root in $F$. But any root of $p^d$ is a root of $p$. I don't know whether every factor-closed set is "fieldable".
Answer: I don't know the answer, but I would like to restate the question in a form that refers to $\mathbb N$ rather than $\mathbb N_2$.
Let $\mathbb N = \langle \{0,1,2,\ldots\}; +, 0\rangle$ be the additive monoid of natural numbers. For a subset $S\subseteq \mathbb N$, call a field $\mathbb F$ an $S$-field if: ($n\in S$ $\Leftrightarrow$ every polynomial in $\mathbb F[x]$ of degree $n$ has a root in $\mathbb F$).
Question. For which subsets $S\subseteq \mathbb N$ is there an $S$-field?
Observation 1. A necessary condition for the existence of an $S$-field is that the complement of $S$ ($S^c = \mathbb N\setminus S$) is a proper additive submonoid of $\mathbb N$.
Reasoning.
Choose and fix an $S$-field $\mathbb F$. We want to prove that $S^c$ is a proper additive submonoid of $\mathbb N$.
To show that $S^c$ is a submonoid of $\mathbb N$ we must explain why (i) $0\in S^c$ and (ii) $S^c$ is closed under addition. To show that $S^c$ is proper we must explain why (iii) $1\notin S^c$. (The proper submonoids of $\mathbb N$ are precisely the submonoids that do not contain $1$.)
For (i), we know that if $f(x)=1$, then this constant polynomial has degree zero and $f(x)=0$ has no root in $\mathbb F$, since $1\neq 0$ is part of the definition of a field. Thus $0\in S^c$.
For (ii), if $m, n\in S^c$, then there exist polynomials $f(x), g(x)\in \mathbb F[x]$ where $\deg(f)=m$, $\deg(g)=n$, and neither $f$ nor $g$ has a root in $\mathbb F$. The product $f(x)g(x)$ has degree $m+n$ and has no root in $\mathbb F$, so $m+n\in S^c$.
For (iii), every degree-one polynomial $\alpha x+\beta\in \mathbb F[x]$ has a root $-\beta/\alpha$ in $\mathbb F$, so $1\in S$, equivalently $1\notin S^c$. \\\

This is already enough to
resolve a question suggested by the comments
(I don't know whether every factor-closed set is "fieldable").
It is not true that every factor closed set is 'fieldable', since the set $S=\{1, 2, 4, 8\}$ is factor closed, but its complement $S^c=\{0,3,5,6,7,9,\ldots\}$ is not a submonoid of $\mathbb N$. For example, $3, 5\in S^c$, but $3+5\notin S^c$.

The necessary condition from above is not a sufficient condition.
For example, it is not to hard to verify this:
Observation 2. If there is an $S$-field $\mathbb F$
and $2, 3\in S$, then $4\in S$. In particular,
there is no $S$-field for $S=\{1,2,3\}$.
Consequently, even though the complementary set
$\mathbb N\setminus \{1,2,3\}=\{0,4,5,6,\ldots\}$ IS a proper submonoid
of $\mathbb N$, there is no $S$-field such that
$S^c = \mathbb N\setminus \{1,2,3\}=\{0,4,5,6,\ldots\}$.
Reasoning.
Observation 2 almost follows from the quartic formula.
For, if $\mathbb F$ is an $S$-field and $2, 3\in S$, then
every polynomial in $\mathbb F[x]$ of degree $1$, $2$, or $3$
has a root in $\mathbb F$. If $f(x)\in \mathbb F[x]$
has degree $4$, then the quartic formula allows one to reduce
the problem of finding a root of $f(x)$ to the problem of solving
polynomial equations of degrees $1$, $2$, and $3$.
If all linear, quadratic and cubic equations over $\mathbb F$ have solutions in $\mathbb F$, then all quartic equations over $\mathbb F$ will also have solutions in $\mathbb F$.
The above argument does not work in characteristics $2$ or $3$ (since the quartic formula involves division by $2$ and by $3$), so I will give a different argument for those characteristics. Let's maintain that $2, 3\in S$, $4\notin S$, and now assume that $\mathbb F$ is an $S$-field of characteristic $p\in \{2, 3\}$. Let $f(x)\in \mathbb F[x]$ be a quartic that has no root in $\mathbb F$.
Claim 1. $f(x)$ is irreducible in $\mathbb F[x]$.
Otherwise $f(x) = g(x)h(x)$ where the factors have smaller degree than $4$, so the factors have roots in $\mathbb F$, so $f(x)$ has a root in $\mathbb F$.
Claim 2. $\mathbb F$ is a perfect field.
Otherwise there would be some $\alpha\in \mathbb F$ such that $x^p=\alpha$ has no root in $\mathbb F$. This cannot happen, since $p=\textrm{char}(\mathbb F)\in \{2,3\}$ and every polynomial in $\mathbb F[x]$ of degree $2$ or $3$ has a root in $\mathbb F$.
Claim 3. If $\mathbb K$ is the splitting field for $f(x)$ over $\mathbb F$, then
$\mathbb K$ is Galois over $\mathbb F$ and the Galois group of $\mathbb K/\mathbb F$ is a transitive subgroup of $S_4$.
This follows from Claims 1 and 2 and from Galois theory and from the fact that $\deg(f)=4$.
Claim 4. The transitive subgroups of $S_4$ are $S_4, A_4, D_4, \mathbb Z_4$ and $K$ = Klein group. In particular, any transitive subgroup of $\textrm{Gal}(\mathbb K/\mathbb F)$ has a (normal) subgroup of index $2$ or $3$.
This follows from group theory.
Claim 5. $\mathbb F$ has a field extension $\mathbb E$ such that $[\mathbb E:\mathbb F]\in \{2, 3\}$.
Let $\mathbb E$ = the fixed subfield of $\mathbb K$ for some subgroup of  index $2$ or $3$ in $\textrm{Gal}(\mathbb K/\mathbb F)$.
Claim 6. There is an irreducible polynomial $m(x)\in \mathbb F[x]$
of degree $2$ or $3$.
Let $m(x)$ be the minimal polynomial over $\mathbb F$ of a primitive
element of $\mathbb E$ over $\mathbb F$.
Claim 7. Contrary to Claim 6, there is no irreducible polynomial
$m(x)\in\mathbb F[x]$ of degree $2$ or $3$.
Because we have assumed that every polynomial of degree $2$ or $3$ in $\mathbb F[x]$ has a root in $\mathbb F$.
Claims 6 and 7 contradict one another.
The contradiction was derived from the assumption that there is a
set set $S$ with $2, 3\in S$ and $4\notin S$ for which there is an $S$-field.
This establishes Observation 2.


C++ find largest BST in a binary tree

Question: what is your approach to have the largest BST in a binary tree? with largest, i mean: highest.
I refer to this post where a very good implementation for finding if a tree is
BST or not is
bool isBinarySearchTree(BinaryTree * n,
int min=std::numeric_limits<int>::min(),
int max=std::numeric_limits<int>::max())
{
     return !n || (min < n->value && n->value < max
     && isBinarySearchTree(n->l, min, n->value)
     && isBinarySearchTree(n->r, n->value, max));
}

It is quite easy to implement a solution to find whether a tree contains a binary search tree. i think that the following method makes it:
bool includeSomeBST(BinaryTree* n)
{
      return includeSomeBST(n->left)  ||  includeSomeBST(n->right) ;

      if(n == NULL)
           return false ;

      return true ;
}

but what if i want the largest BST? this is my first idea,
BinaryTree largestBST(BinaryTree* n)
{
      if(isBinarySearchTree(n))
           return n;

      if(!isBinarySearchTree(n->left))
      {
           if(!isBinarySearchTree(n->right))
               if(includeSomeBST(n->right))
                    return largestBST(n->right);

               else if(includeSomeBST(n->left))
                    return largestBST(n->left);

               else
                   return NULL;

           else
               return n->right;
      }
      else
          return n->left;
}

but its not telling the largest actually. i struggle to make the comparison. how should it take place?
thanks
Comment: What is the largest BST? Are you looking for the height of the tree? Or its deepest node? Your question is quite unclear.
Comment: @fonjibe do you want the largest node..
Comment: includeSomeBST function is wrong...
Answer: Yes,your function includeSomeBST is wrong. You just check the nodes n,n->left and n->right, but you must check the nodes recursively.
bool includeSomeBST(BinaryTree* n)
{
  if(!isBinarySearchTree(n))
  {

       return includeSomeBST(n->left) || includeSomeBST(n->right);
  }

  if(n==NULL) return false;
  return true;

}
Comment: some idea on the largest tree problem?
Comment: @fonjibe As you said,the largest tree problem is the hightest tree problem.One possible easy solution is: 1, for every node,add an element "level" representing the height.The height of leaf node is zero,and you can calculate others nodes' height recursively. 2, for every node,add an element "is_bst", you can use the function isBinarySearchTree to calculate this value for every node recursively. 3, find the node which has the biggest level and which is bst recursively
Answer: Here is a successful code implementation for the same along with the driver program:
#include <iostream>
using namespace std;

class BinaryTree {
    public:
        BinaryTree *right;
        BinaryTree *left;
        int value;
        BinaryTree(int value) {
            this->value = value;
        }
};

int max_value(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

int min_value(int a, int b) {
    if (a < b) {
        return a;
    } else {
        return b;
    }
}

BinaryTree* findLargestBST(BinaryTree *n, int* maxSize, int *max, int *min, bool *is_bst) {
    if (n == NULL) {
        *maxSize = 0;
        *is_bst = true;
        return n;
    }
    int *lc_max_size = new int;
    int *rc_max_size = new int;
    int *lc_max = new int;
    int *lc_min = new int;
    int *rc_max = new int;
    int *rc_min = new int;
    *lc_max = std::numeric_limits<int>::min();
    *rc_max = *lc_max;
    *lc_min = std::numeric_limits<int>::max();
    *rc_min = *lc_min;
    BinaryTree* returnPointer;

    bool is_curr_bst = true;
    BinaryTree* lc = findLargestBST(n->left, lc_max_size, lc_max, lc_min, is_bst);
    if (!*is_bst) {
        is_curr_bst = false;
    }

    BinaryTree* rc = findLargestBST(n->right, rc_max_size, rc_max, rc_min, is_bst);
    if (!*is_bst) {
        is_curr_bst = false;
    }

    if (is_curr_bst && *lc_max <= n->value && n->value <= *rc_min) {
        *is_bst = true;
        *maxSize = 1 + *lc_max_size + *rc_max_size;
        returnPointer = n;
        *max = max_value (n->value, *rc_max);
        *min = min_value (n->value, *lc_min);
    } else {
        *is_bst = false;
        *maxSize = max_value(*lc_max_size, *rc_max_size);
        if (*maxSize == *lc_max_size) {
            returnPointer = lc;
        } else {
            returnPointer = rc;
        }
        *max = *min = n->value;
    }

    delete lc_max_size;
    delete rc_max_size;
    delete lc_max;
    delete lc_min;
    delete rc_max;
    delete rc_min;
    return returnPointer;
}

int main() {

    /* Let us construct the following Tree
          50
       /      \
     10        60
    /  \       /  \
   5   20    55    70
            /     /  \
          45     65    80
  */

  BinaryTree *root = new BinaryTree(50);
  root->left        = new BinaryTree(10);
  root->right       = new BinaryTree(60);
  root->left->left  = new BinaryTree(5);
  root->left->right = new BinaryTree(20);
  root->right->left  = new BinaryTree(55);
  root->right->left->left  = new BinaryTree(45);
  root->right->right = new BinaryTree(70);
  root->right->right->left = new BinaryTree(65);
  root->right->right->right = new BinaryTree(80);

  /* The complete tree is not BST as 45 is in right subtree of 50.
     The following subtree is the largest BST
        60
      /  \
    55    70
   /     /  \
  5     65    80
  */

  int *maxSize = new int;
  int *min_value = new int;
  int *max_value = new int;
  *min_value = std::numeric_limits<int>::max();
  *max_value = std::numeric_limits<int>::min();
  bool *is_bst = new bool;
  BinaryTree *largestBSTNode = findLargestBST(root, maxSize, max_value, min_value, is_bst);
  printf(" Size of the largest BST is %d", *maxSize);
  printf("Max size node is %d", largestBSTNode->value);
  delete maxSize;
  delete min_value;
  delete max_value;
  delete is_bst;
  getchar();

  return 0;
}

The approach used is fairly straightforward and can be understood as follows:
It is a bottom to top approach instead of a top to bottom one which we use when determining whether the tree is a BST or not. It uses the same max-min approach used while determining the tree as a BST or not.
Following are the steps which are executed at each of the nodes in a recursive fashion:
Note: Please remember that this is a bottom up approach and the information is going to flow from the bottom to the top.
1) Determine whether I am existent or not. If I am not (I am null) I should not influence the algorithm in any way and should return without doing any modifications.
2) At every node, maximum size of the BST till this point is stored. This is determined using the total size of the left subtree + the total size of the right subtree + 1(for the node itself) if the tree at this particular node satisfies the BST property. Otherwise, it is figured out from the max values that have been returned from the left subtree and the right subtree.
3) In the case if the BST property is satisfied at the given node then the current node is returned as the maximum size BST till this point otherwise it is determined from the left and the right subtrees.

C++ find largest BST in a binary tree


C# Selenium looping through XPath results

Question: How can i loop through each result from same Xpath?
My code:
IList<IWebElement> base = driver.FindElements(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/div[4]/div/table/tbody//td[contains(@style,'text-align: center;')and contains(text(),'?')]/following-sibling::td[1]"));

String[] baseALL = new string[base.Count];
int i = 0;

foreach (IWebElement elm in base)
{
    string uhm = driver.FindElement(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/div[4]/div/table/tbody//td[contains(@style,'text-align: center;')and contains(text(),'?')]/following-sibling::td[1]")).Text;
    string liczba = uhm;
    Console.WriteLine(liczba);
    double d = Convert.ToDouble(liczba.Replace(".", ","));
    if (d < 10)
    {
        foreach (IWebElement wyslij in base)
        {
            driver.FindElement(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/div[4]/div/table/tbody//td[contains(@style,'text-align: center;')and contains(text(),'?')]/following-sibling::td[2]/a")).Click();
        }
    }
    driver.FindElement(By.XPath("//td//table//td//a[@class='manager_icon'] [@title='Asystent Farmera']")).Click();
}

My xpath gives results like
1.8
3.2
4.8
7.8

I want to loop through each one and compare (if its less than 10 Click there)
But it always picks first result, how can i jump to next one? Same for Click Loop.
Answer: Use relative xpath instead of absolute xpath.
Find element always return first element. You have to have change the xpath by including nth .
Try this and if doesn't work add your html to the question.
int i = 0;

foreach (IWebElement elm in base)
{
    i++;
    string uhm = driver.FindElement(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table[2]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/div[4]/div/table/tbody//tr["+i+"]/td[contains(@style,'text-align: center;')and contains(text(),'?')]/following-sibling::td[1]")).Text;
    string liczba = uhm;
    Console.WriteLine(liczba);
}


Can prior distributions incorporate uncertainty AND variability in parameters?

Question: I am trying to understand how to interpret Bayesian prior and posterior distributions in situations where there is believed to be variability in model parameters (due to variation in the population under study) as well as uncertainty. My understanding is that, typically, the prior distribution for a model parameter represents uncertainty in our knowledge of that parameter. My question is, would it be statistically valid to proceed with the computation of the posterior using priors that incorporate both uncertainty and variability? And would the interpretation of the posterior need to change if this was done?
Thoughts:

I am aware that, if a parameter is believed to vary, then it would be possible to specify a hierarchical model, with variability in the parameter quantified by a hyperparameter (and uncertainty in this hyperparameter represented by an associated hyperprior). So I guess this is one approach.
In the context of quantitative risk analysis (QRA e.g. in books by Vose) parameter distributions can be chosen to represent uncertainty and variability. These distributions seem very similar to prior distributions. The difference being that, usually, no posterior distribution is computed - instead, something akin to a prior predictive distribution would typically be computed.
Comment: What do you mean by variability? Do you mean, changing over time?
Comment: Not exactly... I was thinking of variability between units in the population under study. A specific example I have been thinking of is in the context of disease transmission models for infectious disease transmission within animals on farms. Parameters controlling disease transmission are likely to be unknown, but are also likely to vary between farms.
Comment: Sounds like you have an unknown parameter for each farm, and the same prior for each parameter?
Comment: Currently I just have one unknown parameter which is shared by all farms.
Comment: I think I understand what you're asking now. So you might something like: (1) Some variable (eg. transmission rate) $b_i$ for $n$ farms (2) $b_i$ are drawn from some distribution $C$ (3) The parameters that describe $C$ are also unknown, but you've got some prior for $C$.
Answer: Consider that you measure $x_{i,j}$ in site $i$ according to ($\sigma_i$ being considered here as known and $\mu_i$ unknown being your parameter value for site $i$):
$$
p(x_{i,j}|\mu_i,\sigma_i)
$$
You know that the parameter $\mu_i$ vary from one site $i$ to the other but consider as reasonable to represent this variation by a density
$$
p(\mu_i|\sigma,\mu)
$$
with scale and location parameters $\mu$ and $\sigma$ unknown. Then you can perfectly estimate
$$
p(\mu,\sigma|(x_{i,j})_{i,j})
$$
or
$$
p((\mu_i)|(x_{i,j})_{i,j})
$$
that both account for variation around $\mu$ and measurement error around $\mu_i$. Notice that if you assume a normal distribution for the two above-mentioned densities you have:
$$
X_{i,j}|\mu,\sigma,\sigma_i \sim N(\mu,\sigma^2+\sigma^2_i)
$$
where you can consider that $\sigma$ represents your inter-site variability and $\sigma_i$, your uncertainty related to the measurement process. Moreover even with a limited observation number $J$ for each site ($j$ in $1:J$), the accuracy of $\mu$ and $\sigma$ estimates will increase when the sample number $I$ increases.
Comment: In this case, don't $\sigma, \sigma_i$ both contribute to uncertainty?  How is the maximum a posteriori solution not simply $x_i=\mu_i$?  How does such a model encourage variability?
Comment: @Neil G. IMHO uncertainty and variability is more a lexical problematic than a design one. The MAP is not $m_i=x_i$ because of $p(\mu_i | \sigma, \mu)$ that tends to group more or less the $\mu_i$ (depending on  the prior for $\sigma$ and $\mu$)(I think that shrinkage estimator is the keyword to look at). The model encourages variability as much as the data (and the choosen prior) encourages it to do it.
Comment: Your density over the $x_i$ is Gaussian, so how is the MAP solution not simply the mean?   The whole point of this question is to encourage variability using a prior — you cannot control the data.  I still don't see how your prior encourages variability.
Comment: Sorry I will try to make the post clearer. The point is that I have not defined priors on $\sigma$ and $\mu$ so that it seems to me difficult to discuss the MAP. is it ? Maybe, I miss the question but the model encourages variability by allowing it then the data speaks... Thanks for helping me improving the answers :)
Comment: "the model encourages variability by allowing it then the data speaks..." — that is exactly "uncertainty".  That is not encouraging variability.  By your logic both $\sigma$ and $\sigma_i$ do the same thing: they both encode uncertainty.
Comment: I do not see your point, can you explain ?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/32957/discussion-between-neil-g-and-peuhp).
Comment: A simple way to explain why this doesn't work is that your $\sigma$ measures variability.  It does not make configurations $x_i$ with higher variability more likely than non-variable ones.  The maximum likelihood solution of your model is always $x_i=\mu_i \forall i$ even when all $\mu_i$ are equal.
Comment: @Neil G. ML of what ?
Answer: There are priors that encode variability.  However, these can't be priors over the parameters of a distribution of an individual example.  These priors have to involve multiple examples.  For one example of encouraging variability in latent features, see Wang, Ye, and David B. Dunson. "Probabilistic Curve Learning: Coulomb Repulsion and the Electrostatic Gaussian Process." Advances in Neural Information Processing Systems. 2015.
Here's a simple exampe:  If the $x_i$ are your data points, then a likelihood term $$\sigma\left(\frac{(x_i-x_j)^2}{\theta}\right) \qquad \forall i\ne j$$ where $\sigma$ is the logistic sigmoid, encourages variability.  A large $\theta$ pushes the $x_i$s apart.  You can still encode your uncertainty by having wide priors on the $x_i$.  Note how this constraint is over pairs of examples — a constraint over an individual example cannot enforce variability.


Dominant weight as a positive combination of simple roots

Question: Let G be a semisimple algebraic group.
I can see (geometrically) why every dominant weight has to be a non-negative combination of simple roots (and if it strictly dominant then it has to be a positive combination). I assume that the coefficients are allowed to be in $\mathbb{Q}$.
Does anybody have an algebraic proof?
Answer: To show the non-negativity. Write a dominant character as the sum of negative linear combination of some of the simple roots and non-negative of the others.
Now, taking scalar product with the negative part, gives the deusired result.