问:
r - Select DF based on value in column of another DF
I want to bind the columns of 2 dataframes.
The second dataframe should be choosen among several dataframes in my environment, depending on the value of a cell in the first dataframe.

Sample Data

```<code>test <- structure(list(main_activity = structure(c(1L, 9L), .Label = c("Manufacturing",
"Manufacturing; Retail", "Manufacturing; Services", "Manufacturing; Wholesale",
"Manufacturing; Wholesale; Services", "Retail", "Retail; Services",
"Retail; Wholesale", "Services", "Services; Manufacturing", "Services; Retail",
"Services; Wholesale", "Wholesale", "Wholesale; Manufacturing",
"Wholesale; Retail", "Wholesale; Services"), class = "factor"),
    p_l_for_period_net_income_th_eur_2019 = c(-4849.968, -4416.404
    ), Name = c("A", "B")), class = "data.frame", row.names = c(NA,
-2L))

Manufacturing_2015 <- as.data.frame(matrix(data = c(2000)))
Services_2015 <- as.data.frame(matrix(data = c(3000)))
</code>```

What I want to be able to do is to check the value of the column 'main_activity' and bind the dataframe that matches that name with the 'test' dataframe. So, the goal is to have the following:

Desired Outcome

```<code>binded_A <- cbind(test %>% filter(Name == "A"), Manufacturing_2015)
binded_B <- cbind(test %>% filter(Name == "B"), Services_2015)
</code>```

Is there a way to do it automatically?

答:
You can use ls to select a data frame from the global environment based on it's value in main_activity and cbind the data to original subset of dataframe.

```<code>result <- lapply(test$main_activity, function(x) cbind(subset(test,
               main_activity == x), get(ls(pattern = x, envir = .GlobalEnv))))

result

#[[1]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#1 Manufacturing                             -4849.968    A 2000

#[[2]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#2      Services                             -4416.404    B 3000
</code>```

This will return you a list of dataframes, if you need them as separate dataframes name them and use list2env.

```<code>names(result) <- paste0('binded_', test$Name)
list2env(result, .GlobalEnv)
</code>```

Body:
I want to bind the columns of 2 dataframes.
The second dataframe should be choosen among several dataframes in my environment, depending on the value of a cell in the first dataframe.

Sample Data

test <- structure(list(main_activity = structure(c(1L, 9L), .Label = c("Manufacturing",
"Manufacturing; Retail", "Manufacturing; Services", "Manufacturing; Wholesale",
"Manufacturing; Wholesale; Services", "Retail", "Retail; Services",
"Retail; Wholesale", "Services", "Services; Manufacturing", "Services; Retail",
"Services; Wholesale", "Wholesale", "Wholesale; Manufacturing",
"Wholesale; Retail", "Wholesale; Services"), class = "factor"),
    p_l_for_period_net_income_th_eur_2019 = c(-4849.968, -4416.404
    ), Name = c("A", "B")), class = "data.frame", row.names = c(NA,
-2L))

Manufacturing_2015 <- as.data.frame(matrix(data = c(2000)))
Services_2015 <- as.data.frame(matrix(data = c(3000)))

What I want to be able to do is to check the value of the column 'main_activity' and bind the dataframe that matches that name with the 'test' dataframe. So, the goal is to have the following:

Desired Outcome

binded_A <- cbind(test %>% filter(Name == "A"), Manufacturing_2015)
binded_B <- cbind(test %>% filter(Name == "B"), Services_2015)

Is there a way to do it automatically?

Body:
You can use ls to select a data frame from the global environment based on it's value in main_activity and cbind the data to original subset of dataframe.

result <- lapply(test$main_activity, function(x) cbind(subset(test,
               main_activity == x), get(ls(pattern = x, envir = .GlobalEnv))))

result

#[[1]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#1 Manufacturing                             -4849.968    A 2000

#[[2]]
#  main_activity p_l_for_period_net_income_th_eur_2019 Name   V1
#2      Services                             -4416.404    B 3000

This will return you a list of dataframes, if you need them as separate dataframes name them and use list2env.

names(result) <- paste0('binded_', test$Name)
list2env(result, .GlobalEnv)


来源: stackexchange

问:
2D array of 0's ruining logic of unrelated loop - C++
The listed code is from a larger project that I am working on (I deleted almost everything else that wasn't necessary for this posting) that is having some trouble running properly. I found the line that is causing the error but I'm hoping for an explanation as to why this line is causing it.

```<code>#include <iostream>
#include <tgmath.h>

using namespace std;

int main() {
  const int m = 2;    //  Number of rows
  const int n = 2;    //  Number of cols

  int totalPoss = 0;  //  Number of unique possibile m X n binary matrices

  //  2^(m * n) = the number of unique binary
  //  combinations of m X n matrices
  int stop = pow(2, m * n);

  //  Error when a = 0, 1 | m = 0 | n = 1
  for (int a = 0; a < stop; a++) {
    int poss[m][n] = {0};       //  2D Array to store each possible matrix
    int nextGen[m][n] = {0};    //  2D Array to store the next generation of cells
    int rem[m * n];             //  1D Array to store the binary entries of the poss[m][n]

    totalPoss = a;
    int hold = a;           //  Stores the current "possibility number" (i.e when
                            //  a = hold = 1 the binary equivilent of 1 will be stored
                            //  in rem[m * n])

    //  Generate binary number based on whatever a is at current iteration
    int c = 0;
    while (hold > 0) {

      // storing remainder in binary array
      rem[c] = hold % 2;
      hold = hold / 2;
      c++;
    }

    cout << "Binary: ";
    for (int i = 0; i < (m * n); i++) {
      cout << rem[i] << " ";
    }

    cout << endl << endl;
  }

  cout << "Total possibilities: " << totalPoss+1 << endl;

  return 0;
}

</code>```

The line in question is line 19, or int nextGen[m][n] = {0};. The program's purpose in this state is to output all possible unique binary numbers of 4 bits. The number to translate to binary is determined by the initial for loop. The number is translated in the while loop and stored in rem[m][n]. This code works fine unless you include line 19. For whatever reason when this 2D array is created the output for 0 and 1 is 1 14 0 0 but outputs correctly for 2-15. My question is why this one (seemingly) unrelated line breaks my code.

Thank you!

答:
rem is not completely initialized. The loop that assigns values only iterates until hold is zero, so it does not set the higher elements. But the loop that prints it always prints n * m elements.

The effect of defining nextGen is incidental. It may affect where rem is placed in memory, resulting in it happening to contain zeroes rather than other bits (and likely you are compiling without optimization).

Initialize rem to all zeroes or change the loop that sets its elements.

ContentLicense: CC BY-SA 4.0

Body:
The listed code is from a larger project that I am working on (I deleted almost everything else that wasn't necessary for this posting) that is having some trouble running properly. I found the line that is causing the error but I'm hoping for an explanation as to why this line is causing it.

#include <iostream>
#include <tgmath.h>

using namespace std;

int main() {
  const int m = 2;    //  Number of rows
  const int n = 2;    //  Number of cols

  int totalPoss = 0;  //  Number of unique possibile m X n binary matrices

  //  2^(m * n) = the number of unique binary
  //  combinations of m X n matrices
  int stop = pow(2, m * n);

  //  Error when a = 0, 1 | m = 0 | n = 1
  for (int a = 0; a < stop; a++) {
    int poss[m][n] = {0};       //  2D Array to store each possible matrix
    int nextGen[m][n] = {0};    //  2D Array to store the next generation of cells
    int rem[m * n];             //  1D Array to store the binary entries of the poss[m][n]

    totalPoss = a;
    int hold = a;           //  Stores the current "possibility number" (i.e when
                            //  a = hold = 1 the binary equivilent of 1 will be stored
                            //  in rem[m * n])

    //  Generate binary number based on whatever a is at current iteration
    int c = 0;
    while (hold > 0) {

      // storing remainder in binary array
      rem[c] = hold % 2;
      hold = hold / 2;
      c++;
    }

    cout << "Binary: ";
    for (int i = 0; i < (m * n); i++) {
      cout << rem[i] << " ";
    }

    cout << endl << endl;
  }

  cout << "Total possibilities: " << totalPoss+1 << endl;

  return 0;
}

The line in question is line 19, or int nextGen[m][n] = {0};. The program's purpose in this state is to output all possible unique binary numbers of 4 bits. The number to translate to binary is determined by the initial for loop. The number is translated in the while loop and stored in rem[m][n]. This code works fine unless you include line 19. For whatever reason when this 2D array is created the output for 0 and 1 is 1 14 0 0 but outputs correctly for 2-15. My question is why this one (seemingly) unrelated line breaks my code.

Thank you!


问:
ImportError: No module named site - mac
I have had this problem for months. every time that I want to get a new python package and use it I get this error in terminal:

```<code>ImportError: No module named site
</code>```

I don't know why do I get this error. actually, I can't use any new package because every time that I wanna install one I get this error. I searched and I found out that the problem would be for PYTHONPATH and PYTHONHOME but I don't know what they are and how can I change them.
My operating system is mac os and I don't know how to solve this problem in mac.

every time that I open the terminal I  use these two commands to solve the problem:

```<code>unset PYTHONHOME
unset PYTHONPATH
</code>```

but the next time I get the error again.

答:
The Python tooling is evolving in Mac OS X such that Python 2.7 is being deprecated. System default paths may no longer apply as I learned after upgrading to Mac OS X Catalina (10.15.x). There are a few scenarios here:

GENERIC FIX -- According to this primer on the site package and Python internal paths, Python 2.7 requires a specific user path for site packages. The solution I settled on was simply this:

```<code>mkdir -p ~/.local/lib/python2.7/site-packages
</code>```

At that point you will have a dedicated directory for Python modules (for Python to function). (NOTE that the error ImportError: No module named site is misleading as it really indicates that the correct directory structure didn't exist to allow the site module to properly load.)

BASIC ALTERNATIVE -- Is your PYTHONHOME pointing to Python3 and your python --version reporting 2.7? Does python3 --version report something different (or work at all)? This error started happening for me after the Catalina upgrade when I was trying to use built-ins. Check your .profile and .bash_profile to see if they are explicitly setting a custom PYTHONHOME and/or PYTHONPATH. One option is to change that so the ENV variables are set explicitly and manually only when a newer Python is needed. You may consider symlinking python3 and pip3 to leave the standard commands to the OS.

DEBUGGING -- If you would like to test and/or get more information, try executing Python in one of the increasingly verbose modes:

```<code>python -v
python -vv
python -vvv
</code>```

Title: ImportError: No module named site - mac

Body:
I have had this problem for months. every time that I want to get a new python package and use it I get this error in terminal:

ImportError: No module named site

I don't know why do I get this error. actually, I can't use any new package because every time that I wanna install one I get this error. I searched and I found out that the problem would be for PYTHONPATH and PYTHONHOME but I don't know what they are and how can I change them.
My operating system is mac os and I don't know how to solve this problem in mac.

every time that I open the terminal I  use these two commands to solve the problem:

unset PYTHONHOME
unset PYTHONPATH

but the next time I get the error again.

Body:
The Python tooling is evolving in Mac OS X such that Python 2.7 is being deprecated. System default paths may no longer apply as I learned after upgrading to Mac OS X Catalina (10.15.x). There are a few scenarios here:

GENERIC FIX -- According to this primer on the site package and Python internal paths, Python 2.7 requires a specific user path for site packages. The solution I settled on was simply this:

mkdir -p ~/.local/lib/python2.7/site-packages

At that point you will have a dedicated directory for Python modules (for Python to function). (NOTE that the error ImportError: No module named site is misleading as it really indicates that the correct directory structure didn't exist to allow the site module to properly load.)

BASIC ALTERNATIVE -- Is your PYTHONHOME pointing to Python3 and your python --version reporting 2.7? Does python3 --version report something different (or work at all)? This error started happening for me after the Catalina upgrade when I was trying to use built-ins. Check your .profile and .bash_profile to see if they are explicitly setting a custom PYTHONHOME and/or PYTHONPATH. One option is to change that so the ENV variables are set explicitly and manually only when a newer Python is needed. You may consider symlinking python3 and pip3 to leave the standard commands to the OS.

DEBUGGING -- If you would like to test and/or get more information, try executing Python in one of the increasingly verbose modes:

python -v
python -vv
python -vvv


问:
Why my multiprocess queue might be "losing" items?
I've got some code where I want to share objects between processes using queues. I've got a parent:

```<code>processing_manager = mp.Manager()
to_cacher = processing_manager.Queue()
fetchers = get_fetchers()
fetcher_process = mp.Process(target=fetch_news, args=(to_cacher, fetchers))
fetcher_process.start()
while 1:
    print(to_cacher.get())
</code>```

And a child:

```<code>def fetch_news(pass_to: Queue, fetchers: List[Fetcher]):
    def put_news_to_query(pass_to: Queue, fetchers: List[Fetcher]):
        for fet in fetchers:
            for news in fet.latest_news():
                print(news)
                pass_to.put(news)
        print("----------------")

    put_news_to_query(pass_to, fetchers)
</code>```

I'm expecting to see N objects printed in put_news_to_query, then a line, and then the same objects printed in while loop in a parent. Problem is, objects appear to miss: if I get, say, 8 objects printed in put_news_to_query I get only 2-3 objects printed in while loop. What am I doing wrong here?

答:
This is not the answer, unless the answer is that the code is already working. I've just modified the code to make it a running example of the same technique. The data gets from child to parent without data loss. </p>

```<code>import multiprocessing as mp
import time
import random

def worker(pass_to):
    for i in range(10):
        time.sleep(random.randint(0,10)/1000)
        print('child', i)
        pass_to.put(i)
    print("---------------------")
    pass_to.put(None)

def main():
    manager = mp.Manager()
    to_cacher = manager.Queue()
    fetcher = mp.Process(target=worker, args=(to_cacher,))
    fetcher.start()
    while 1:
        msg = to_cacher.get()
        if msg is None:
            break
        print(msg)

if __name__ == "__main__":
    main()
</code>```

Body:
I've got some code where I want to share objects between processes using queues. I've got a parent:

processing_manager = mp.Manager()
to_cacher = processing_manager.Queue()
fetchers = get_fetchers()
fetcher_process = mp.Process(target=fetch_news, args=(to_cacher, fetchers))
fetcher_process.start()
while 1:
    print(to_cacher.get())

And a child:

def fetch_news(pass_to: Queue, fetchers: List[Fetcher]):
    def put_news_to_query(pass_to: Queue, fetchers: List[Fetcher]):
        for fet in fetchers:
            for news in fet.latest_news():
                print(news)
                pass_to.put(news)
        print("----------------")

    put_news_to_query(pass_to, fetchers)

I'm expecting to see N objects printed in put_news_to_query, then a line, and then the same objects printed in while loop in a parent. Problem is, objects appear to miss: if I get, say, 8 objects printed in put_news_to_query I get only 2-3 objects printed in while loop. What am I doing wrong here?

Body:
This is not the answer, unless the answer is that the code is already working. I've just modified the code to make it a running example of the same technique. The data gets from child to parent without data loss.

import multiprocessing as mp
import time
import random

def worker(pass_to):
    for i in range(10):
        time.sleep(random.randint(0,10)/1000)
        print('child', i)
        pass_to.put(i)
    print("---------------------")
    pass_to.put(None)

def main():
    manager = mp.Manager()
    to_cacher = manager.Queue()
    fetcher = mp.Process(target=worker, args=(to_cacher,))
    fetcher.start()
    while 1:
        msg = to_cacher.get()
        if msg is None:
            break
        print(msg)

if __name__ == "__main__":
    main()


问:
c2dm : how to receive the message in the device? (using PHP)
I have the registration id and auth token for c2dm. And then I pass store these values in db. and using php, i could send one message to c2dm server. But my problem is I dont know how to receive the message in the application. I am not sure whether my way of getting the message is correct or not. Anyway i will give it below.

I have one activity which registers to the c2dm using registration intent. and one receiver to receive the reg_id and notification message. it is registering with c2dm and not to receive message.

manifest

```<code>    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"></action>
        <category android:name="my.android.c2dm"></category>
    </intent-filter>
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
        <category android:name="my.android.c2dm"></category>
    </intent-filter>
    </receiver>

</application>
</code>```

C2dmRegistration.class (activity)

```<code>    Intent objRegIntnet=new Intent("com.google.android.c2dm.intent.REGISTER");
    objRegIntnet.putExtra("app",PendingIntent.getBroadcast(this,0,new Intent(),0));
    objRegIntnet.putExtra("sender","mymail@gmail.com");
    startService(objRegIntnet);
</code>```

c2dmReceiver

```<code>public class c2dmReceiver extends BroadcastReceiver
{
    private static String KEY = "c2dmPref";
    private static String REGISTRATION_KEY = "registrationKey";

    private Context context;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        this.context = context;
        if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
        {
                  handleRegistration(context, intent);
             }
        else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
        {
            handleMessage(context, intent);
             }
    }

     private void handleRegistration(Context context, Intent intent)
{
       //handles registeration
     }
     private void handleMessage(Context context, Intent intent)
{

    String title= intent.getStringExtra("title");
    String message= intent.getStringExtra("msg");
    Toast.makeText(context,"title : "+title+"\n message : "+message,1).show();
    //Do whatever you want with the message
}
</code>```

please tell what is the mistake i have done...

UPDATE

Hi all, the same code is woring for me today. The mistake i have done is with php code. instaed of passing the values as POST, i sent it was as GET. When I changed it to POST, the toast message is showing. but yet some problems are there.

The title, and msg values are null here.
my php code is :

```<code>function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText)
 {
       //$messageText="have a nice day";
       //$msgtype="important";
       $headers = array('Authorization: GoogleLogin auth=' . $authCode);
       $data = array(
        'registration_id' => $deviceRegistrationId,
        'collapse_key' => $msgType,
        'data.message' => $messageText
                        );
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
      if ($headers)
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $response = curl_exec($ch);
      curl_close($ch);
      return $response;
    }
</code>```

Actually i am not sure what type of values should use for collapse_key, and data.message variables.

Please help me...
Thank you...

答:
Finally I found the way of giving collapse_key and and data..
collapse_key should be a string which is a name for a group of messages or a a parthicular type of messages. If we send more than one message with same collapse_key, the latest message will be sent to the device from c2dm server.

Example : $collapse_key = "important";

And the data. is the important thing. This will contain the message that we want to send.

Ex: if we want to send a message "Have a nice day", then i should give a key name to it.
    data.="Have a nice day";
here 'wishes' is the key. And in receiver, i should retreive the message with the same key name.

```<code>private void handleMessage(Context context, Intent intent)
{
      String mywish= intent.getStringExtra("wishes");
      Toast.makeText(context,"my wishes : "+mywish,1).show();
}
</code>```

Sorry to all..

ContentLicense: CC BY-SA 3.0

Body:
I have the registration id and auth token for c2dm. And then I pass store these values in db. and using php, i could send one message to c2dm server. But my problem is I dont know how to receive the message in the application. I am not sure whether my way of getting the message is correct or not. Anyway i will give it below.

I have one activity which registers to the c2dm using registration intent. and one receiver to receive the reg_id and notification message. it is registering with c2dm and not to receive message.

manifest

    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.REGISTRATION"></action>
        <category android:name="my.android.c2dm"></category>
    </intent-filter>
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
        <category android:name="my.android.c2dm"></category>
    </intent-filter>
    </receiver>

</application>

C2dmRegistration.class (activity)

    Intent objRegIntnet=new Intent("com.google.android.c2dm.intent.REGISTER");
    objRegIntnet.putExtra("app",PendingIntent.getBroadcast(this,0,new Intent(),0));
    objRegIntnet.putExtra("sender","mymail@gmail.com");
    startService(objRegIntnet);

c2dmReceiver

public class c2dmReceiver extends BroadcastReceiver
{
    private static String KEY = "c2dmPref";
    private static String REGISTRATION_KEY = "registrationKey";

    private Context context;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        this.context = context;
        if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION"))
        {
                  handleRegistration(context, intent);
             }
        else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE"))
        {
            handleMessage(context, intent);
             }
    }

     private void handleRegistration(Context context, Intent intent)
{
       //handles registeration
     }
     private void handleMessage(Context context, Intent intent)
{

    String title= intent.getStringExtra("title");
    String message= intent.getStringExtra("msg");
    Toast.makeText(context,"title : "+title+"\n message : "+message,1).show();
    //Do whatever you want with the message
}

please tell what is the mistake i have done...

UPDATE

Hi all, the same code is woring for me today. The mistake i have done is with php code. instaed of passing the values as POST, i sent it was as GET. When I changed it to POST, the toast message is showing. but yet some problems are there.

The title, and msg values are null here.
my php code is :

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText)
 {
       //$messageText="have a nice day";
       //$msgtype="important";
       $headers = array('Authorization: GoogleLogin auth=' . $authCode);
       $data = array(
        'registration_id' => $deviceRegistrationId,
        'collapse_key' => $msgType,
        'data.message' => $messageText
                        );
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
      if ($headers)
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      $response = curl_exec($ch);
      curl_close($ch);
      return $response;
    }

Actually i am not sure what type of values should use for collapse_key, and data.message variables.

Please help me...
Thank you...

Body:
Finally I found the way of giving collapse_key and and data..
collapse_key should be a string which is a name for a group of messages or a a parthicular type of messages. If we send more than one message with same collapse_key, the latest message will be sent to the device from c2dm server.

Example : $collapse_key = "important";

And the data. is the important thing. This will contain the message that we want to send.

Ex: if we want to send a message "Have a nice day", then i should give a key name to it.
    data.="Have a nice day";
here 'wishes' is the key. And in receiver, i should retreive the message with the same key name.

private void handleMessage(Context context, Intent intent)
{
      String mywish= intent.getStringExtra("wishes");
      Toast.makeText(context,"my wishes : "+mywish,1).show();
}

Sorry to all..


问:
Is HTML Turing Complete?
After reading this question Is CSS Turing complete? -- which received a few thoughtful, succinct answers -- it made me wonder: Is HTML Turing Complete?

Although the short answer is a definitive Yes or No, please also provide a short description or counter-example to prove whether HTML is or is not Turing Complete (obviously it cannot be both). Information on other versions of HTML may be interesting, but the correct answer should answer this for HTML5.

答:
It seems clear to me that states and transitions can be represented in HTML with pages and hyperlinks, respectively. With this, one can implement deterministic finite automata where clicking links transitions between states. For example, I implemented a few simple DFA which are accessible here.

DFA are much simpler that the Turing Machine though. To implement something closer to a TM, an additional mechanism involving reading and writing to memory would be necessary, besides the basic states/transitions functionality. However, HTML does not seem to have this kind of feature. So I would say HTML is not Turing-complete, but is able to simulate DFA.

Edit1: I was reminded of the video On The Turing Completeness of PowerPoint when writing this answer.

Edit2: complementing this answer with the DFA definition and clarification.

Edit3: it might be worth mentioning that any machine in the real world is a finite-state machine due to reality's constraint of finite memory. So in a way, DFA can actually do anything that any real machine can do, as far as I know. See: https://en.wikipedia.org/wiki/Turing_machine#Comparison_with_real_machines

Definition

From https://en.wikipedia.org/wiki/Deterministic_finite_automaton#Formal_definition

In the theory of computation, a branch of theoretical computer
science, a deterministic finite automaton (DFA)—also known as
deterministic finite acceptor (DFA), deterministic finite-state
machine (DFSM), or deterministic finite-state automaton (DFSA)—is a
finite-state machine that accepts or rejects a given string of
symbols, by running through a state sequence uniquely determined by
the string.

A deterministic finite automaton M is a 5-tuple, (Q, Σ, δ, q0, F),
consisting of

a finite set of states Q

a finite set of input symbols called the alphabet Σ

a transition function δ : Q × Σ → Q

an initial or start state q0

a set of accept states F

The following example is of a DFA M, with a binary alphabet, which
requires that the input contains an even number of 0s.

M = (Q, Σ, δ, q0, F) where

Q = {S1, S2}

Σ = {0, 1}

q0 = S1

F = {S1} and

δ is defined by the following state transition table:

0
0

s1
s2
s1

s2
s1
s2

State diagram for M:

The state S1 represents that there has been an even number of 0s in
the input so far, while S2 signifies an odd number. A 1 in the input
does not change the state of the automaton. When the input ends, the
state will show whether the input contained an even number of 0s or
not. If the input did contain an even number of 0s, M will finish in
state S1, an accepting state, so the input string will be accepted.

HTML implementation

The DFA M exemplified above plus a few of the most basic DFA were implemented in Markdown and converted/hosted as HTML pages by Github, accessible here.

Following the definition of M, its HTML implementation is detailed as follows.

The set of states Q contains the pages s1.html and s2.html, and also the acceptance page acc.html and the rejection page rej.html. These two additional states are a "user-friendly" way to communicate the acceptance of a word and don't affect the semantics of the DFA.

The set of symbols Σ is defined as the symbols 0 and 1. The empty string symbol ε was also included to denote the end of the input, leading to either acc.html or rej.html state.

The initial state q0 is s1.html.

The set of accept states is {acc.html}.

The set of transitions is defined by hyperlinks such that page s1.html contains a link with text "0" leading to s2.html, a link with text "1" leading to s1.html, and a link with text "ε" leading to acc.html. Each page is analogous according to the following transition table. Obs: acc.html and rej.html don't contain links.

0
1
ε

s1.html
s2.html
s1.html
acc.html

s2.html
s1.html
s2.html
rej.html

Questions

In what ways are those HTML pages "machines"? Don't these machines include the browser and the person who clicks the links? In what way does a link perform computation?

DFA is an abstract machine, i.e. a mathematical object. By the definition shown above, it is a tuple that defines transition rules between states according to a set of symbols. A real-world implementation of these rules (i.e. who keeps track of the current state, looks up the transition table and updates the current state accordingly) is then outside the scope of the definition. And for that matter, a Turing machine is a similar tuple with a few more elements to it.

As described above, the HTML implementation represents the DFA M in full: every state and every transition is represented by a page and a link respectively. Browsers, clicks and CPUs are then irrelevant in the context of the DFA.

In other words, as written by @Not_Here in the comments:

Rules don't innately implement themselves, they're just rules an
implementation should follow. Consider it this way: Turing machines
aren't actual machines, Turing didn't build machines. They're purely
mathematical objects, they're tuples of sets (state, symbols) and a
transition function between states. Turing machines are purely
mathematical objects, they're sets of instructions for how to
implement a computation, and so is this example in HTML.

The Wikipedia article on abstract machines:

An abstract machine, also called an abstract computer, is a
theoretical computer used for defining a model of computation.
Abstraction of computing processes is used in both the computer
science and computer engineering disciplines and usually assumes a
discrete time paradigm.

In the theory of computation, abstract machines are often used in
thought experiments regarding computability or to analyze the
complexity of algorithms (see computational complexity theory). A
typical abstract machine consists of a definition in terms of input,
output, and the set of allowable operations used to turn the former
into the latter. The best-known example is the Turing machine.

Title: Is HTML Turing Complete?


问:
Why does this give me a circular reference error?
I've hacked together this bit of code which throws an error when run in React / Next.js:

```<code>const myArray = ["a","b","c"];

myArray.forEach((item, index, array) => {
  if(item === "b") {
    array[index] = <span>b</span>;
  }
});

console.log(${JSON.stringify(myArray, null, 2)}); // Circular error
</code>```

The above console.log throws this error:

```<code>Unhandled Runtime Error
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property '_context' -> object with constructor 'Object'
    --- property 'Provider' closes the circle
</code>```

Although it renders in the browser OK, the console.log has identified a deeper issue causing downstream issues.

Why is this a circular structure?

答:
I was not able to reproduce that error either, but there is a few things that I can guess:

Circular structure is a structure that references the parent structure, so I think that changing the original array may create duplicate references for the same structure. I would suggest you to use .map instead:

```<code>let myArray = ["a", "b", "c"];

myArray = myArray.map((item) => (item === "b" ? <span>b</span> : item));

console.log(JSON.stringify(myArray, null, 2));
</code>```

That should work, but, going further, i have seen problems with those "self mapping" due to the way javascript reference types works. I suggest to use a new constant:

```<code>const myArray = ["a", "b", "c"];

const myArrayMap = myArray.map((item) =>
  item === "b" ? <span>b</span> : item
);

console.log(JSON.stringify(myArrayMap, null, 2));
</code>```

Body:
I've hacked together this bit of code which throws an error when run in React / Next.js:

const myArray = ["a","b","c"];

myArray.forEach((item, index, array) => {
  if(item === "b") {
    array[index] = b;
  }
});

console.log(${JSON.stringify(myArray, null, 2)}); // Circular error

The above console.log throws this error:

Unhandled Runtime Error
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property '_context' -> object with constructor 'Object'
    --- property 'Provider' closes the circle

Although it renders in the browser OK, the console.log has identified a deeper issue causing downstream issues.

Why is this a circular structure?

Body:
I was not able to reproduce that error either, but there is a few things that I can guess:

Circular structure is a structure that references the parent structure, so I think that changing the original array may create duplicate references for the same structure. I would suggest you to use .map instead:

let myArray = ["a", "b", "c"];

myArray = myArray.map((item) => (item === "b" ? <span>b</span> : item));

console.log(JSON.stringify(myArray, null, 2));

That should work, but, going further, i have seen problems with those "self mapping" due to the way javascript reference types works. I suggest to use a new constant:

const myArray = ["a", "b", "c"];

const myArrayMap = myArray.map((item) =>
  item === "b" ? <span>b</span> : item
);

console.log(JSON.stringify(myArrayMap, null, 2));


问:
How to override WindowsPhone dark theme by light
Any idea on over-riding the dark theme without copy the default design/ThemeResources.xml file?</p>

答:
If you don't want  to override the resources file the alternative is to create your own styles for every control that you use and apply that to each instance of each control.

Overriding the resources fiel is easier. ;)


问:
Passing props and mapping data in React
I'm working on a project that requires me to pass data to two functional components.

My axios call to the API seems to work, as well as setting the state with hooks, but I keep receiving these two errors:

Error Cannot convert undefined or null to object I tried checking if the array is empty but that didn't seem to solve the problem

summaryMetrics is not defined - This I don't understand because summartMetrics is defined. Could it be that the elements are being displayed before the data is fetched ?

Here are the files in a codesandbox
Included the API's so people can see the structure of how the JSON is being returned.
Im not sure if I'm passing and mapping the data correctly.

Here are the files in a codesandbox

Any help is very much appreciated

答:
Since your state has this form :

```<code>const [summary, setSummaryData] = useState({
  summaryMetrics: null,
  platformsData: null
});
</code>```

...you should access your state like this :

```<code><SummaryMetrics
  uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
  positiveScore={summary.summaryMetrics[0]["positiveScore"]}
  riskScore={summary.summaryMetrics[0]["riskScore"]}
/>

[...]
</code>```

Note the "summary." before "summaryMetrics" :

```<code>summary.summaryMetrics[0]["uniqueSocialMediaPost"]
</code>```

Fixed Fixed Code Sandbox <s>(other things seems to go wrong though, white screen, but syntax error is fixed)</s> :

Previous errors were :

mocky.io serves content over HTTP, Code Sandbox over HTTPS so mixed content issue : Chrome does not allow this kind of mix in protocols, fixed by using HTTPS protocol to grab infos from mocky.io,

no unique keys for SummaryByPlatform component in map function

Chrome dev tools is your friend when nothing happens as expected :).

By the way you could just

```<code>summary.summaryMetrics.map(s => <SummaryByPlatform summaryMetrics={s} />)
</code>```

...instead of gettings keys, and you could simply pass whole summaryMetrics object to SummaryByPlatform and have only one props. But that's another subject.

Good luck with it.

Title: Passing props and mapping data in React

Body:
Since your state has this form :

const [summary, setSummaryData] = useState({
  summaryMetrics: null,
  platformsData: null
});

...you should access your state like this :

<SummaryMetrics
  uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
  positiveScore={summary.summaryMetrics[0]["positiveScore"]}
  riskScore={summary.summaryMetrics[0]["riskScore"]}
/>

[...]

Note the "summary." before "summaryMetrics" :

summary.summaryMetrics[0]["uniqueSocialMediaPost"]

Fixed Fixed Code Sandbox <s>(other things seems to go wrong though, white screen, but syntax error is fixed)</s> :

Previous errors were :

mocky.io serves content over HTTP, Code Sandbox over HTTPS so mixed content issue : Chrome does not allow this kind of mix in protocols, fixed by using HTTPS protocol to grab infos from mocky.io,

no unique keys for SummaryByPlatform component in map function

Chrome dev tools is your friend when nothing happens as expected :).

By the way you could just

summary.summaryMetrics.map(s => <SummaryByPlatform summaryMetrics={s} />)

...instead of gettings keys, and you could simply pass whole summaryMetrics object to SummaryByPlatform and have only one props. But that's another subject.

Good luck with it.


问:
Getting error on running ***pyspark --conf spark.jars.packages=com.amazon.deequ:deequ:1.0.2*** in apache spark
I have installed apache-spark 2.4.4 version on ubuntu:16.04 and all it's dependencies. After installation I am running below mentioned pyspark command

pyspark --conf spark.jars.packages=com.amazon.deequ:deequ:1.0.2

after running this I am getting a file missing error in this dir - /home/username/.ivy2/

```<code>java.io.FileNotFoundException: File file:/home/streamflux/.ivy2/jars/net.sourceforge.f2j_arpack_combined_all-0.1.jar does not exist
        at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:611)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:824)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:601)
        at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:421)
        at org.apache.spark.SparkContext.addFile(SparkContext.scala:1544)
        at org.apache.spark.SparkContext.addFile(SparkContext.scala:1508)
        at org.apache.spark.SparkContext$$anonfun$13.apply(SparkContext.scala:462)
        at org.apache.spark.SparkContext$$anonfun$13.apply(SparkContext.scala:462)
        at scala.collection.immutable.List.foreach(List.scala:392)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:462)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:238)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
20/05/23 09:43:14 INFO server.AbstractConnector: Stopped Spark@bb24d4c{HTTP/1.1,[http/1.1]}{0.0.0.0:4040}
20/05/23 09:43:14 INFO ui.SparkUI: Stopped Spark web UI at http://0babaa1d999c:4040
20/05/23 09:43:14 INFO spark.MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
20/05/23 09:43:14 INFO memory.MemoryStore: MemoryStore cleared
20/05/23 09:43:14 INFO storage.BlockManager: BlockManager stopped
20/05/23 09:43:14 INFO storage.BlockManagerMaster: BlockManagerMaster stopped
20/05/23 09:43:14 WARN metrics.MetricsSystem: Stopping a MetricsSystem that is not running
20/05/23 09:43:14 INFO scheduler.OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
20/05/23 09:43:14 INFO spark.SparkContext: Successfully stopped SparkContext

</code>```

I am tried with removing the cache. one thing that I have noticed that there is a file with a similar name - net.sourceforge.f2j_arpack_combined_all-0.1-javadoc.jar

Please help me with this error

答:
Just encountered this while testing a job.

There's a JIRA issue that mentions this happens on similar calls and suggests dependency resolution is affected.

Seems like it wasn't fixed as the original version was considered EOL when it resolved.

However, it still surfaces on 2.4.4 / 2.4.5 as far as I can see ( we're on 2.4.5 )

In our case, as we usually add dependencies directly to our docker builds via sbt, all jars are available and loaded locally.

We just explicitly added the affected package

libraryDependencies += "com.github.fommil.netlib" % "all" % "1.1.2" pomOnly ()
```

You can either use a similar approach or add any relevant jars directly to $SPARK_HOME/jars or the ivy folder and it should work.

Body:
I have installed apache-spark 2.4.4 version on ubuntu:16.04 and all it's dependencies. After installation I am running below mentioned pyspark command

pyspark --conf spark.jars.packages=com.amazon.deequ:deequ:1.0.2

after running this I am getting a file missing error in this dir - /home/username/.ivy2/

java.io.FileNotFoundException: File file:/home/streamflux/.ivy2/jars/net.sourceforge.f2j_arpack_combined_all-0.1.jar does not exist
        at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:611)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:824)
        at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:601)
        at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:421)
        at org.apache.spark.SparkContext.addFile(SparkContext.scala:1544)
        at org.apache.spark.SparkContext.addFile(SparkContext.scala:1508)
        at org.apache.spark.SparkContext$$anonfun$13.apply(SparkContext.scala:462)
        at org.apache.spark.SparkContext$$anonfun$13.apply(SparkContext.scala:462)
        at scala.collection.immutable.List.foreach(List.scala:392)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:462)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:238)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.lang.Thread.run(Thread.java:748)
20/05/23 09:43:14 INFO server.AbstractConnector: Stopped Spark@bb24d4c{HTTP/1.1,[http/1.1]}{0.0.0.0:4040}
20/05/23 09:43:14 INFO ui.SparkUI: Stopped Spark web UI at http://0babaa1d999c:4040
20/05/23 09:43:14 INFO spark.MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
20/05/23 09:43:14 INFO memory.MemoryStore: MemoryStore cleared
20/05/23 09:43:14 INFO storage.BlockManager: BlockManager stopped
20/05/23 09:43:14 INFO storage.BlockManagerMaster: BlockManagerMaster stopped
20/05/23 09:43:14 WARN metrics.MetricsSystem: Stopping a MetricsSystem that is not running
20/05/23 09:43:14 INFO scheduler.OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
20/05/23 09:43:14 INFO spark.SparkContext: Successfully stopped SparkContext

I am tried with removing the cache. one thing that I have noticed that there is a file with a similar name - net.sourceforge.f2j_arpack_combined_all-0.1-javadoc.jar

Please help me with this error

Body:
Just encountered this while testing a job.

There's a JIRA issue that mentions this happens on similar calls and suggests dependency resolution is affected.

Seems like it wasn't fixed as the original version was considered EOL when it resolved.

However, it still surfaces on 2.4.4 / 2.4.5 as far as I can see ( we're on 2.4.5 )

In our case, as we usually add dependencies directly to our docker builds via sbt, all jars are available and loaded locally.

We just explicitly added the affected package

libraryDependencies += "com.github.fommil.netlib" % "all" % "1.1.2" pomOnly ()

You can either use a similar approach or add any relevant jars directly to $SPARK_HOME/jars or the ivy folder and it should work.


问:
Pandas pivot dataframe where values are a function of two columns
Suppose we have a dataframe

```<code>df = pd.DataFrame({'A': [1, 2], 'A_values': [3, 4], 'B': [5, 6],  'B_values': [7, 8]})
</code>```

I want to sort of pivot this dataframe so that we have columns A and B suffixed with their values as index and column names in a new dataframe (i.e. index = ['A_1', 'A_2'], columns = ['B_5', 'B_6']), and the values of this new dataframe would be a result of a function on columns A_values and B_values. Suppose the function is a simple sum. For A = 1 we have A_values = 3, for B = 5 we have B_values = 7, therefore in the new dataframe at the intersection of A_1 and B_5 we would have 3+7=10. Complete resulting dataframe below:

```<code>df_pivoted = pd.DataFrame([[3+7, 3+8], [4+7, 4+8]], index = ['A_1', 'A_2'], columns = ['B_5', 'B_6'])
</code>```

After searching for a while I did not find the functionality in .pivot_table() that would allow to pass a function of multiple columns as values. Maybe there is a more suitable method for this situation? Any help is appreciated.

答:
We can do filter with index , then merge  (which also know as cross join in SQL) with new key and pivot . here I am using groupby with unstack which is equal to pivot_table

```<code>A=df.filter(like='A').assign(key=1)
B=df.filter(like='B').assign(key=1)
s=A.merge(B)
s=s.assign(value=s.A_values+s.B_values).groupby(['A','B'])['value'].sum().unstack()
s
B   5   6
A
1  10  11
2  11  12
</code>```

Body:
Suppose we have a dataframe

df = pd.DataFrame({'A': [1, 2], 'A_values': [3, 4], 'B': [5, 6],  'B_values': [7, 8]})

I want to sort of pivot this dataframe so that we have columns A and B suffixed with their values as index and column names in a new dataframe (i.e. index = ['A_1', 'A_2'], columns = ['B_5', 'B_6']), and the values of this new dataframe would be a result of a function on columns A_values and B_values. Suppose the function is a simple sum. For A = 1 we have A_values = 3, for B = 5 we have B_values = 7, therefore in the new dataframe at the intersection of A_1 and B_5 we would have 3+7=10. Complete resulting dataframe below:

df_pivoted = pd.DataFrame([[3+7, 3+8], [4+7, 4+8]], index = ['A_1', 'A_2'], columns = ['B_5', 'B_6'])

After searching for a while I did not find the functionality in .pivot_table() that would allow to pass a function of multiple columns as values. Maybe there is a more suitable method for this situation? Any help is appreciated.

Body:
We can do filter with index , then merge  (which also know as cross join in SQL) with new key and pivot . here I am using groupby with unstack which is equal to pivot_table

A=df.filter(like='A').assign(key=1)
B=df.filter(like='B').assign(key=1)
s=A.merge(B)
s=s.assign(value=s.A_values+s.B_values).groupby(['A','B'])['value'].sum().unstack()
s
B   5   6
A
1  10  11
2  11  12


问:
Setting up a cron Job
Please I am new to cron jobs and only heard of it recently.

The thing is I am trying to send a message to myself via a phpscript.

I need the cron job to read the php cript and send the appropriate message.

here is the php self mailer I have in place.

```<code><?php
    $recipient = "*******@gmail.com";
    $subject = "Flight Status";
    $body = "Flight has just landed.";
    if(mail($recipient, $subject, $body))
    {
        echo("<p>Message successfully sent</p>");
    }
    else
    {
        echo("<p>Message Delivery failed </p>");
    }
?>
</code>```

答:
you can read the manual for cron with man 5 crontab. It contain example as well.
for example,

# run at 2:15pm on the first of every month -- output mailed to paul

15 14 1 * *     $HOME/bin/flight.php

Title: Setting up a cron Job

Body:
Please I am new to cron jobs and only heard of it recently.

The thing is I am trying to send a message to myself via a phpscript.

I need the cron job to read the php cript and send the appropriate message.

here is the php self mailer I have in place.

<?php
    $recipient = "*******@gmail.com";
    $subject = "Flight Status";
    $body = "Flight has just landed.";
    if(mail($recipient, $subject, $body))
    {
        echo("
Message successfully sent
");
    }
    else
    {
        echo("
Message Delivery failed
");
    }
?>


问:
How to train multiple inputs for Perceptron in C#?
I recently just coded a perceptron that takes in an OR gate as it's value. However, currently my code can only train 1 point whereas I want it to train 4 point of the OR gate. Here's my attached code, I am still learning how to program so please excuse me for some of my errors.

using System;
using ActivationFunction;
namespace Perceptron
{
    class Point
    {

        private double input1; //creates private field
        public double Input1 { get => input1; set => input1 = value; } //creates public property (important for encapsulation of data)
        private double input2;
        public double Input2 { get => input2; set => input2 = value; }
        private double desiredOutput;
        public double DesiredOutput { get => desiredOutput; set => desiredOutput = value; }

        public Point() /*Creates an empty constructor so that the object of the
                       class can be instantiated to refer variables*/
        {

        }

        public Point(int input1, int input2, int desiredOutput) //Takes in the inputs for the perceptron
        {

            this.input1 = input1;
            this.input2 = input2;
            this.desiredOutput = desiredOutput;

            Console.WriteLine("INPUT 1 => " + Input1);
            Console.WriteLine("INPUT 2 => " + Input2);
            Console.WriteLine("DESIRED OUTPUT => " + desiredOutput);
        }
    }

    class NeuralNetwork
    {
        readonly Point point = new Point(); //used for referring variables from point to class

        private double[] weights = new double[3];

        private double output;

        private const double bias = 1; //creates constant bias

        private double error;

        private const double learningRate = 0.25; //constant learningRate

        public NeuralNetwork(Point point) //Might be unnecessary...
        {
            this.point = point;
        }

        public void RandomiseWeightsAndBias()
        {
            Random rand = new Random();

            for (int i = 0; i < weights.Length; i++) //loops through the weights
            {
                weights[i] = rand.NextDouble();

                weights[i] -= 0.5; // expected range now -0.5 to +0.5
                weights[i] *= 2; //expected range now -1 to 1

                Console.WriteLine("STARTING SYNAPTIC WEIGHTS => " + weights[i]);

            }

            Console.WriteLine("BIAS IS => " + bias);
        }

        public double DotProductBias() //Sums up the inputs and weights together
        {

            return point.Input1 * weights[0] + point.Input2 * weights[1] + bias * weights[2];
        }

        public double ActivationFunction() //Applies activation function
        {
            DotProductBias();
            output = ActivationFunctions.StepActivation(DotProductBias()); //The Activation Function is in part of another class, there is a built in static function that takes in a static double as input
            return output;
        }

        public void CalculateError() //Calculate Error
        {
            error = point.DesiredOutput - output;
            Console.WriteLine("ERROR IS => " + error);
        }

        public void AdjustWeights() //Perform gradient descent
        {

            weights[0] += learningRate * weights[0] + error * point.Input1; //I know I can use for loops to make it more concise and clean but it works for now
            weights[1] += learningRate * weights[1] + error * point.Input2;
            weights[2] += learningRate * weights[2] + error * bias;

            for (int i = 0; i < weights.Length; i++)
            {
                Console.WriteLine("ADJUSTED WEIGHTS ARE => " + weights[i]);
            }

        }

        public void Train(int epochs) //Training or "backpropagating the weights"
        {

            for (int i = 0; i < epochs; i++)
            {
                AdjustWeights();
            }
        }

    }

    class Program
    {

        static void Main(string[] args)
        {

            var point = new Point(0, 1, 1);

            /*
            var point2 = new Point(0, 1, 0);
            var point3 = new Point(1, 0, 0);
            var point4 = new Point(1, 1, 1);
            */

            var neuralNetwork = new NeuralNetwork(point);

            neuralNetwork.RandomiseWeightsAndBias();
            neuralNetwork.ActivationFunction();
            neuralNetwork.CalculateError();
            neuralNetwork.Train(8);

            Console.WriteLine("THE FINAL OUTPUT IS " + neuralNetwork.ActivationFunction());

        }
    }

}
```

Looking at the code, it's clear that I need to change the values of the constructors in the Point class, perhaps change the inputs to an array or a list? Please help!

答:
In my opinion, there are several possible troubles here, first it looks that the points you want to train are not OR gate but XOR gate and a single perceptron can't implement XOR. The reason is that the classes in XOR are not linearly separable. You cannot draw a straight line to separate the points (0,0),(1,1) from the points (0,1),(1,0). OR gate would be [0,0,0] [1,0,1] [1,1,1] [0,1,1] , read more about it here https://en.wikipedia.org/wiki/OR_gate.

Second, to me it looks like your weight adjustment is wrong - to adjust weights in perception we use this formula NEW WEIGHT = WEIGHT + ERROR * INPUT * LEARNING RATE, and in your example, you did multiply it by your weight once more.

In such simple example it's convinient to use threshold activation function which is basically - If output < 0 return 0 else return 1.

Body:
I recently just coded a perceptron that takes in an OR gate as it's value. However, currently my code can only train 1 point whereas I want it to train 4 point of the OR gate. Here's my attached code, I am still learning how to program so please excuse me for some of my errors.

using System;
using ActivationFunction;
namespace Perceptron
{
    class Point
    {

        private double input1; //creates private field
        public double Input1 { get => input1; set => input1 = value; } //creates public property (important for encapsulation of data)
        private double input2;
        public double Input2 { get => input2; set => input2 = value; }
        private double desiredOutput;
        public double DesiredOutput { get => desiredOutput; set => desiredOutput = value; }

        public Point() /*Creates an empty constructor so that the object of the
                       class can be instantiated to refer variables*/
        {

        }

        public Point(int input1, int input2, int desiredOutput) //Takes in the inputs for the perceptron
        {

            this.input1 = input1;
            this.input2 = input2;
            this.desiredOutput = desiredOutput;

            Console.WriteLine("INPUT 1 => " + Input1);
            Console.WriteLine("INPUT 2 => " + Input2);
            Console.WriteLine("DESIRED OUTPUT => " + desiredOutput);
        }
    }

    class NeuralNetwork
    {
        readonly Point point = new Point(); //used for referring variables from point to class

        private double[] weights = new double[3];

        private double output;

        private const double bias = 1; //creates constant bias

        private double error;

        private const double learningRate = 0.25; //constant learningRate

        public NeuralNetwork(Point point) //Might be unnecessary...
        {
            this.point = point;
        }

        public void RandomiseWeightsAndBias()
        {
            Random rand = new Random();

            for (int i = 0; i < weights.Length; i++) //loops through the weights
            {
                weights[i] = rand.NextDouble();

                weights[i] -= 0.5; // expected range now -0.5 to +0.5
                weights[i] *= 2; //expected range now -1 to 1

                Console.WriteLine("STARTING SYNAPTIC WEIGHTS => " + weights[i]);

            }

            Console.WriteLine("BIAS IS => " + bias);
        }

        public double DotProductBias() //Sums up the inputs and weights together
        {

            return point.Input1 * weights[0] + point.Input2 * weights[1] + bias * weights[2];
        }

        public double ActivationFunction() //Applies activation function
        {
            DotProductBias();
            output = ActivationFunctions.StepActivation(DotProductBias()); //The Activation Function is in part of another class, there is a built in static function that takes in a static double as input
            return output;
        }

        public void CalculateError() //Calculate Error
        {
            error = point.DesiredOutput - output;
            Console.WriteLine("ERROR IS => " + error);
        }

        public void AdjustWeights() //Perform gradient descent
        {

            weights[0] += learningRate * weights[0] + error * point.Input1; //I know I can use for loops to make it more concise and clean but it works for now
            weights[1] += learningRate * weights[1] + error * point.Input2;
            weights[2] += learningRate * weights[2] + error * bias;

            for (int i = 0; i < weights.Length; i++)
            {
                Console.WriteLine("ADJUSTED WEIGHTS ARE => " + weights[i]);
            }

        }

        public void Train(int epochs) //Training or "backpropagating the weights"
        {

            for (int i = 0; i < epochs; i++)
            {
                AdjustWeights();
            }
        }

    }

    class Program
    {

        static void Main(string[] args)
        {

            var point = new Point(0, 1, 1);

            /*
            var point2 = new Point(0, 1, 0);
            var point3 = new Point(1, 0, 0);
            var point4 = new Point(1, 1, 1);
            */

            var neuralNetwork = new NeuralNetwork(point);

            neuralNetwork.RandomiseWeightsAndBias();
            neuralNetwork.ActivationFunction();
            neuralNetwork.CalculateError();
            neuralNetwork.Train(8);

            Console.WriteLine("THE FINAL OUTPUT IS " + neuralNetwork.ActivationFunction());

        }
    }

}

Looking at the code, it's clear that I need to change the values of the constructors in the Point class, perhaps change the inputs to an array or a list? Please help!


问:
Live updating Node.js logging configuration
What I'm trying to accomplish:

Update the logging level on a node micro service, without stopping the existing running service, by detecting the saving of a change to the config file.

The reason: work policies demand different levels of approval based on what gets changed.

Updating a config file is a "standard change" (considered "safe", requiring low ceremony to accomplish.)

Changing the config file, and restarting the service is a "normal change" (considered "not safe", requiring vp approval).

This capability will go a long way towards allowing us to improve the logging in our services.

The technical challenge:

Both node-config and bunyan appear to require a restart in order to accept changes.

Results of attempting to do proper research prior to submitting a question:

Live updating Node.js server

Can node-config reload configurations without restarting Node?

(This last post has a solution that worked for someone, but I couldn't get it to work.)

In theory, I should be able to delete both the app level objects using the lines:

delete require.cache[require.resolve('config')];

delete require.cache[require.resolve('logging')];

and then recreate both objects with the new configurations read from the changed config file.

Deleting the config and logging object may work, but I'm still a node nube so every way that I attempted to use this magical line failed for me.

(Caveat: I was able to delete the objects I just couldn't get them recreated in such a way that my code would use the newly created objects.)

The horrifically ugly attempt of what I'm doing can be found on my github in the "spike_LiveUpdate" directory of:

https://github.com/MalcolmAnderson/uService_stub

The only thing we are attempting to change is the log level of the application so that, if we needed to, we could:

bounce the logging level "to 11" for a small handful of minutes,

have the user demonstrate their error,

and the put it back to the normal logging level.

(It would also be a useful tool to have in our back pocket so when the dealers of FUD say, "But if you get the logging level wrong, we will have to use an emergency change to fix it.  Sorry, we appreciate your desire to get a better picture of what's happening in the application, but we just can't justify the risk you're proposing.")

Research prior to writing question:

Attempt to solve the problem.

Search for "node live update", "node live configuration update", "node no restart configuration change"

Search for the above but replacing the word "live update" with "rolling update" (this got a lot of Kubernetes hits, which may be the way I have to go with this.)

Bottom line:  Attempting to be able to change both Node-config, and Bunyan logging without a restart.

[For all I know, there's a security reason for not allowing live updates.]

答:
If I understand truly, you need to change log level of your application but without restart it

According to this, there are couple of ways I can suggest.

You can create a second server which includes the new deployment of your changed code and route new traffic to the new server and stop routing new traffic to the old server. When old server drains the processes it currently has, you can shut it down and go with a new one, or re-deploy your application for normal status.

You can create a second application layer in the same server with different port which I do not recommend it and do the same thing with first bullet that I mentioned.

If you're not running on Kubernetes, you need to make your own rolling update strategy (k8s is doing it automatically).


问:
Unity LWPR does not see some layers
I have 2D Unity project with two cameras: the main one and one designed for parallax effect.
After I installed LWPR for setting lights the second camera stopped showing its layer in game.

Is there a way to fix this?

答:
The practice of rendering two cameras at the same time as you are describing, "camera stacking", is not currently supported on LWRP or URP. There is some discussion about adding support for it again.

You could try using a camera to render onto a render texture and display that as your background.

For the 2D light, it is present but is greyed out. You should be able to enable experimental feature use in the player settings for the project.

Title: Unity LWPR does not see some layers


问:
Detect multiple strings in one df from strings in another df and, if detected, return the strings detected
I'm learning to use R, so please bear with me.

I have a dataset of google play store apps (master_tib). Each row is a play store app. There's a column titled description that contains text on what the app does.

```<code>master_tib

App     Description
App1    Reduce your depression and anxiety
App2    Help your depression
App3    This app helps with Anxiety
App4    Dog walker app 3000
</code>```

I also have a df of tags (master_tags) that contains words of importance I've predefined. There is a single column titled tag and each row contains a single tag.

```<code>master_tag

Tag
Depression
Anxiety
Stress
Mood
</code>```

My goal is to tag apps from the master_tib df with the tags in master_tags df based on the presence of the tag in the description. It will then print the tags in a new column.
The final result would be a master_tib df that looks like this:

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
App2    Help your depression                   depression
App3    This app helps with anxiety            anxiety
App4    Dog walker app 3000                    FALSE
</code>```

Below is what I've done so far using a combination of str_detect and mapply:

```<code># define function to use in mapply

detect_tag <- function(description, tag){
  if(str_detect(description, tag, FALSE)) {
    return (tag)
  } else {
    return (FALSE)
  }
}

index <-  mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)

master_tib[index,]
</code>```

Unfortunately, only the first tag is being passed through.

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression
</code>```

Instead of the desired:

```<code>App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
</code>```

I haven't gotten as far as printing the results into a new column. Would love to hear anyone's insight or thoughts and apologize in advance for my poor R skills.

答:
Using several packages from tidyverse(dplyr, stringr, tidyr) and the data shown in @Ronak Shah's answer.
First transform the tags into a pattern:

pattern <- master_tags$Tag %>%
  tolower() %>%
  str_c(collapse="|")
```

<p>Then find all matches and create the desired output:</p>

```master_tib %>%
  mutate(Tag = str_extract_all(tolower(Description), pattern)) %>%
  unnest(Tag, keep_empty = TRUE) %>%
  group_by(App, Description) %>%
  summarise(Tag = str_c(Tag, collapse=", "))
```

<p>This yields</p>

```# A tibble: 4 x 3
# Groups:   App [4]
  App   Description                        Tag
  <chr> <chr>                              <chr>
1 App1  Reduce your depression and anxiety depression, anxiety
2 App2  Help your depression               depression
3 App3  This app helps with Anxiety        anxiety
4 App4  Dog walker app 3000                NA
```

Body:
I'm learning to use R, so please bear with me.

I have a dataset of google play store apps (master_tib). Each row is a play store app. There's a column titled description that contains text on what the app does.

master_tib

App     Description
App1    Reduce your depression and anxiety
App2    Help your depression
App3    This app helps with Anxiety
App4    Dog walker app 3000

I also have a df of tags (master_tags) that contains words of importance I've predefined. There is a single column titled tag and each row contains a single tag.

master_tag

Tag
Depression
Anxiety
Stress
Mood

My goal is to tag apps from the master_tib df with the tags in master_tags df based on the presence of the tag in the description. It will then print the tags in a new column.
The final result would be a master_tib df that looks like this:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety
App2    Help your depression                   depression
App3    This app helps with anxiety            anxiety
App4    Dog walker app 3000                    FALSE

Below is what I've done so far using a combination of str_detect and mapply:

# define function to use in mapply

detect_tag <- function(description, tag){
  if(str_detect(description, tag, FALSE)) {
    return (tag)
  } else {
    return (FALSE)
  }
}

index <-  mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)

master_tib[index,]

Unfortunately, only the first tag is being passed through.

App     Description                            Tag
App1    Reduce your depression and anxiety     depression

Instead of the desired:

App     Description                            Tag
App1    Reduce your depression and anxiety     depression, anxiety

I haven't gotten as far as printing the results into a new column. Would love to hear anyone's insight or thoughts and apologize in advance for my poor R skills.

Body:
Using several packages from tidyverse(dplyr, stringr, tidyr) and the data shown in @Ronak Shah's answer.
First transform the tags into a pattern:

pattern <- master_tags$Tag %>%
  tolower() %>%
  str_c(collapse="|")

Then find all matches and create the desired output:

master_tib %>%
  mutate(Tag = str_extract_all(tolower(Description), pattern)) %>%
  unnest(Tag, keep_empty = TRUE) %>%
  group_by(App, Description) %>%
  summarise(Tag = str_c(Tag, collapse=", "))

This yields

# A tibble: 4 x 3
# Groups:   App [4]
  App   Description                        Tag
  <chr> <chr>                              <chr>
1 App1  Reduce your depression and anxiety depression, anxiety
2 App2  Help your depression               depression
3 App3  This app helps with Anxiety        anxiety
4 App4  Dog walker app 3000                NA


问:
I get the error (fortran runtime error end of file) on Fortran, does anyone has an idea how can I solve it?
I work at gFortran. I encoded a file that will read data from a CSV file. The data is about matrix 1000000*10. I tried to compile it, unfortunately I get this error (Fortran runtime error: end of file) when I try to reduce the data size to 1000*100. It works fine. Does anyone have an idea how to fix this error?</p>

答:
End of file errors mean that you're trying to keep reading past the end of the file.

With the little information you're giving us, this is all the help we can give.


问:
Sending json as html over wordpress api
i am trying to send json as raw (html) to wordpress api but its not working for me

```<code>$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

$query = http_build_query([
'title' => $titleFile,
'content' => json_decode(stripslashes($json))
]);
$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();
</code>```

its working fine, but the post is made with json in the body format if I don't decode and if I decode the post is empty as its an array how can I send the value of the key in raw (html) not Json?

wordpress api endpoint https://developer.wordpress.org/rest-api/reference/posts/

output with json_decode()

```<code>stdClass Object ( [key1] => value1 [key2] => value2 [key3] => value3 )
</code>```

答:
I dont think its the best way to do this but worked for me </p>

```<code>$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

 $data = json_decode($json, TRUE);
 $data = implode(',', $data);
 $data = str_replace(',', '', $data);

$query = http_build_query([
'title' => $titleFile,
'content' => $data
]);

$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();
</code>```

Title: Sending json as html over wordpress api

Body:
i am trying to send json as raw (html) to wordpress api but its not working for me

$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

$query = http_build_query([
'title' => $titleFile,
'content' => json_decode(stripslashes($json))
]);
$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();

its working fine, but the post is made with json in the body format if I don't decode and if I decode the post is empty as its an array how can I send the value of the key in raw (html) not Json?

wordpress api endpoint https://developer.wordpress.org/rest-api/reference/posts/

output with json_decode()

stdClass Object ( [key1] => value1 [key2] => value2 [key3] => value3 )

Body:
I dont think its the best way to do this but worked for me

$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

 $data = json_decode($json, TRUE);
 $data = implode(',', $data);
 $data = str_replace(',', '', $data);

$query = http_build_query([
'title' => $titleFile,
'content' => $data
]);

$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();


问:
Problem with Login control of ASP.NET
I set up a website to use SqlMembershipProvider as written on this page.

I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.

I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in.

I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.

I already tried to handle the events by myself and check, what is happening in them, but no success.

I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.

Any ideas?

Resolution: After some mailing with Rob we have the ideal solution, which is now the accepted answer.

答: If you are overriding the events, are you calling the default implementation? If you are overriding them to confirm their execution, then the actual code will not be getting executed either, which may be the break in the plumbing..

OwnerDisplayName: Biri

ContentLicense: CC BY-SA 2.5

Title: Problem with Login control of ASP.NET

LastEditorDisplayName: Biri

OwnerDisplayName: Rob Cooper


问:
Detect cycles in a genealogy graph during a Depth-first search
I'm loading horse genealogical data recursively.
For some wrong sets of data my recursion never stops... and that is because  there are cycles in the data.

How can I detect those cycles to stop recurring?

I thought of while recurring maintain a hashTable with all "visited" horses.
But that will find some false positives, because a horse CAN be twice in a tree.

What cannot happen is that a horse appear as a father or grandfather or great grandfather of ITSELF.

答:
Pseudo code:

```<code>void ProcessTree(GenTreeNode currentNode, Stack<GenTreeNode> seen)
{
   if(seen.Contains(currentNode)) return;
   // Or, do whatever needs to be done when a cycle is detected

   ProcessHorse(currentNode.Horse); // Or whatever processing you need

   seen.Push(currentNode);

   foreach(GenTreeNode childNode in currentNode.Nodes)
   {
      ProcessTree(childNode, seen);
   }

   seen.Pop();
}
</code>```

The basic idea is to keep a list of all of the nodes that we've already seen on our way down to the current node; if was get back to a node that we already went through, then you know that we've formed a cycle (and we should skip the value, or do whatever needs to be done)

OwnerDisplayName: Romias

Body:
Pseudo code:

void ProcessTree(GenTreeNode currentNode, Stack<GenTreeNode> seen)
{
   if(seen.Contains(currentNode)) return;
   // Or, do whatever needs to be done when a cycle is detected

   ProcessHorse(currentNode.Horse); // Or whatever processing you need

   seen.Push(currentNode);

   foreach(GenTreeNode childNode in currentNode.Nodes)
   {
      ProcessTree(childNode, seen);
   }

   seen.Pop();
}

The basic idea is to keep a list of all of the nodes that we've already seen on our way down to the current node; if was get back to a node that we already went through, then you know that we've formed a cycle (and we should skip the value, or do whatever needs to be done)

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
Angular 7 error RangeError: Maximum call stack size exceeded
I am trying to learn angular by following the official tutorial but when following steps for hero component and hero detail component, it raises an error "RangeError: Maximum call stack size exceeded".

The hero.component.html:

```<code><ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

<!--
<app-hero-detail [hero]="selectedHero"></app-hero-detail> -->

<app-heroes></app-heroes>
</code>```

The detail component:

```<code><div *ngIf="hero">

  <h2>{{hero.name}} Details</h2>
  <div><span>id: </span>{{hero.id}}</div>
  <div>
    <label>name:
      <input [(ngModel)]="hero.name" placeholder="name"/>
    </label>
  </div>

</div>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>
</code>```

The hero component

```<code>import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroes = this.heroService.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }

}
</code>```

The hero.detail component

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;
  constructor() { }

  ngOnInit() {
  }

}
</code>```

one thing to mention is that when <app-heroes></app-heroes> is commented, the list page is loaded without an error

any help is appreciated

答:
I named two modules similarly and didn't pay attention to which I imported.
If you import a module inside itself it will cause circular import till maximum call stack is reached.</p>

Body:
I am trying to learn angular by following the official tutorial but when following steps for hero component and hero detail component, it raises an error "RangeError: Maximum call stack size exceeded".

The hero.component.html:

    {{hero.id}} {{hero.name}}

<app-heroes></app-heroes>

The detail component:

{{hero.name}} Details

id: {{hero.id}}

    name:
      <input [(ngModel)]="hero.name" placeholder="name"/>

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

The hero component

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HEROES } from '../mock-heroes';
import { HeroService } from '../hero.service';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];

  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroes = this.heroService.getHeroes();
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }

}

The hero.detail component

import { Component, OnInit, Input } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero: Hero;
  constructor() { }

  ngOnInit() {
  }

}

one thing to mention is that when <app-heroes></app-heroes> is commented, the list page is loaded without an error

any help is appreciated


问:
Flutter APK build android resource linking failed vibrate package
I'm trying to build an apk for my app but I get a resource linking fail on the vibrate package.
I can run my app in release mode and I can also build an app bundle without failure.
I already did a successful apk build two days ago, what I changed since this build:
-upgrading to Android studio 4.0
-run a pub cache repair (due to an other error resolved now)

Error I get:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':vibrate:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontStyle not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/font not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontWeight not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

Running Gradle task 'assembleRelease'...                           24,3s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin cloud_firestore...
Running Gradle task 'assembleAarRelease'...
The plugin cloud_firestore could not be built due to the issue above.
Process finished with exit code 1
</code>```

My flutter doctor is good and a flutter clean doesn't change anything.
I can't access the flutter panel when right click on the android panel.

EDIT:
if I run with verbose I get this in my log

```<code>[  +17 ms] > Task :vibrate:extractDebugAnnotations UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugGeneratedProguardFiles UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugConsumerProguardFiles UP-TO-DATE
[   +1 ms] > Task :vibrate:prepareLintJarForPublish UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugJavaResource UP-TO-DATE
[   +1 ms] > Task :vibrate:transformClassesAndResourcesWithSyncLibJarsForDebug UP-TO-DATE
[   +2 ms] > Task :vibrate:transformNativeLibsWithSyncJniLibsForDebug UP-TO-DATE
[   +1 ms] > Task :vibrate:bundleDebugAar UP-TO-DATE
[   +1 ms] > Task :vibrate:compileDebugSources UP-TO-DATE
[   +1 ms] > Task :vibrate:assembleDebug UP-TO-DATE
[ +253 ms] > Task :app:mergeDebugNativeLibs
[   +1 ms] Unable to strip library
'C:\Users\plest\StudioProjects\the_spot\build\app\intermediates\merged_native_libs\debug\out\lib\x86\libflutter.so' due to
missing strip tool for ABI 'X86'. Packaging it as is.
[  +97 ms] > Task :app:stripDebugDebugSymbols
[   +1 ms] Compatible side by side NDK version was not found.
[   +1 ms] Unable to strip library
'C:\Users\plest\StudioProjects\the_spot\build\app\intermediates\merged_native_libs\debug\out\lib\x86_64\libflutter.so' due
to missing strip tool for ABI 'X86_64'. Packaging it as is.
</code>```

答: I resolved my issue upgrading vibrate 0.0.4 to flutter_vibrate 1.0.0</p>

Body:
I'm trying to build an apk for my app but I get a resource linking fail on the vibrate package.
I can run my app in release mode and I can also build an app bundle without failure.
I already did a successful apk build two days ago, what I changed since this build:
-upgrading to Android studio 4.0
-run a pub cache repair (due to an other error resolved now)

Error I get:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':vibrate:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontStyle not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/font not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontWeight not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     C:\Users\plest\.gradle\caches\transforms-2\files-2.1\1aeb117cf01e0e03a347b2b45aacb6fb\core-1.1.0\res\values\values.xml:142:5-173:25: AAPT: error: resource android:attr/ttcIndex not found.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

Running Gradle task 'assembleRelease'...                           24,3s
The built failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetfier to solve the incompatibility.
Building plugin cloud_firestore...
Running Gradle task 'assembleAarRelease'...
The plugin cloud_firestore could not be built due to the issue above.
Process finished with exit code 1

My flutter doctor is good and a flutter clean doesn't change anything.
I can't access the flutter panel when right click on the android panel.

EDIT:
if I run with verbose I get this in my log

[  +17 ms] > Task :vibrate:extractDebugAnnotations UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugGeneratedProguardFiles UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugConsumerProguardFiles UP-TO-DATE
[   +1 ms] > Task :vibrate:prepareLintJarForPublish UP-TO-DATE
[   +1 ms] > Task :vibrate:mergeDebugJavaResource UP-TO-DATE
[   +1 ms] > Task :vibrate:transformClassesAndResourcesWithSyncLibJarsForDebug UP-TO-DATE
[   +2 ms] > Task :vibrate:transformNativeLibsWithSyncJniLibsForDebug UP-TO-DATE
[   +1 ms] > Task :vibrate:bundleDebugAar UP-TO-DATE
[   +1 ms] > Task :vibrate:compileDebugSources UP-TO-DATE
[   +1 ms] > Task :vibrate:assembleDebug UP-TO-DATE
[ +253 ms] > Task :app:mergeDebugNativeLibs
[   +1 ms] Unable to strip library
'C:\Users\plest\StudioProjects\the_spot\build\app\intermediates\merged_native_libs\debug\out\lib\x86\libflutter.so' due to
missing strip tool for ABI 'X86'. Packaging it as is.
[  +97 ms] > Task :app:stripDebugDebugSymbols
[   +1 ms] Compatible side by side NDK version was not found.
[   +1 ms] Unable to strip library
'C:\Users\plest\StudioProjects\the_spot\build\app\intermediates\merged_native_libs\debug\out\lib\x86_64\libflutter.so' due
to missing strip tool for ABI 'X86_64'. Packaging it as is.


问:
Retrieving Google User Photo
I am able to retrieve the thumbnailPhotoUrl from the user.list api of the google admin SDK.  However, whenever I try to render the image, Google is redirecting to a static silhouette image.  The URL that is retrieved via the API looks like

```<code>https://plus.google.com/_/focus/photos/private/AIbEiAIA....
</code>```

As mentioned, this ends up getting redirected to:

```<code>https://ssl.gstatic.com/s2/profiles/images/silhouette200.png
</code>```

However, with a little bit of reverse engineering, I can see the photo by adding /u/1/ to the beginning of the URL path, like this:

```<code>https://plus.google.com/u/1/_/focus/photos/private/AIbEiAIA...
</code>```

From my research the /u/1 has something to do with multiple google accounts, so I'm afraid I wouldn't be able to rely on this method.  Can anyone help me understand what's happening here?

答:
Here are my 10 cents...

Recently I've been working on building a G Suite User Picker for Angular and I ran into the same problem. Nonetheless, I kept testing and researching and in one of my tests I decided to call the directory api users list endpoint with a NON-ADMIN user. (Head Explodes ) To my surprise, google permits this type of requests, although it provides non super admin data but enough to get a private thumbnail url for the user. At first I thought it was an unintended behaviour, some kind of bug if you will. That is when I ran into this documentation.

While user accounts can only be modified by administrators, any user on the domain can read user profiles. A non-admin user can make a users.get or users.list request with the viewType parameter equal to domain_public to retrieve a user's public profile. The scope https://www.googleapis.com/auth/admin.directory.user.readonly is ideal for this use case.

So it is an intended behaviour. That is when it hit me. The private url generated when retrieving the user data is intended to be used only by the requesting user. If you provide the url to other user, it will redirect to the anonymous silhouette.

From this I was able to conclude that if I need to retrieve a list of users and need the ability to view their photos, I need to call the directory api endpoint using the credentials of the user that needs to view the respective data. This serves my purpose with the G Suite User Picker widget I am building.

Title: Retrieving Google User Photo

Body:
I am able to retrieve the thumbnailPhotoUrl from the user.list api of the google admin SDK.  However, whenever I try to render the image, Google is redirecting to a static silhouette image.  The URL that is retrieved via the API looks like

https://plus.google.com/_/focus/photos/private/AIbEiAIA....

As mentioned, this ends up getting redirected to:

https://ssl.gstatic.com/s2/profiles/images/silhouette200.png

However, with a little bit of reverse engineering, I can see the photo by adding /u/1/ to the beginning of the URL path, like this:

https://plus.google.com/u/1/_/focus/photos/private/AIbEiAIA...

From my research the /u/1 has something to do with multiple google accounts, so I'm afraid I wouldn't be able to rely on this method.  Can anyone help me understand what's happening here?


问:
How to navigate to sections in different pages
Hello thank you for your time in advance. I am trying to navigate to section in home page from another .html page.  My problem is that it always jumps to top of the page no matter which section I specify.

Code in index.html (home/main page for features)

```<code>        <section id="features" class="s-features target-section">
</code>```

Code in "other".html page

```<code>        <nav class="header-nav-wrap">
            <ul class="header-main-nav">
                <li><a href="index.html">Home</a></li>
                <li><a href="index.html#about">About</a></li>
                <li><a href="index.html#features">Features</a></li>
</code>```

The main page uses a class="smoothscroll" if that may be causing issues or is helpful.
Thank you very much for your time and patience.

答: I am using Hero, however after removing the smooth scrolling feature I am still just being directed to the home page.  The URL does register my section call but the page does not follow this.</p>

Body:
Hello thank you for your time in advance. I am trying to navigate to section in home page from another .html page.  My problem is that it always jumps to top of the page no matter which section I specify.

Code in index.html (home/main page for features)

Code in "other".html page

Home

About

Features

The main page uses a class="smoothscroll" if that may be causing issues or is helpful.
Thank you very much for your time and patience.


问:
Is there a string math evaluator in .NET?
If I have a string with a valid math expression such as:

```<code>String s = "1 + 2 * 7";
</code>```

Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.

答:
You can use Math-Expression-Evaluator library that I am author of. It supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:

```<code>var a = 6;
var b = 4.32m;
var c = 24.15m;
var engine = new ExpressionEvaluator();
engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});
</code>```

You can also pass parameters as named variables:

```<code>dynamic dynamicEngine = new ExpressionEvaluator();

var a = 6;
var b = 4.5m;
var c = 2.6m;

dynamicEngine.Evaluate("(c+b)*a", a: 6, b: 4.5, c: 2.6);
</code>```

It supports .Net Standard 2.0 so can be used from .Net Core as well as .Net Full Framework projects and it doesn't have any external dependencies.

OwnerDisplayName: Guy

Body:
If I have a string with a valid math expression such as:

String s = "1 + 2 * 7";

Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.

Body:
You can use Math-Expression-Evaluator library that I am author of. It supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:

var a = 6;
var b = 4.32m;
var c = 24.15m;
var engine = new ExpressionEvaluator();
engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});

You can also pass parameters as named variables:

dynamic dynamicEngine = new ExpressionEvaluator();

var a = 6;
var b = 4.5m;
var c = 2.6m;

dynamicEngine.Evaluate("(c+b)*a", a: 6, b: 4.5, c: 2.6);

It supports .Net Standard 2.0 so can be used from .Net Core as well as .Net Full Framework projects and it doesn't have any external dependencies.