问:
Having issues writing unit test for an endpoint that uses a service, how to write it correctly?
I did not write the endpoint or the service. I am needing to use this endpoint for an application I am building and I was asked to write a unit test on it. I'm having some issues correctly writing the test. Here is what I have so far in my test:

```<code>public void GetExceptionReportSessionData_ReturnsSessionData()
        {
            //Arrange
            var response = new RetrieveExceptionReportSessionDatesResponse();
            var serviceClient = new Mock<WorkflowService.WorkflowService>();
            serviceClient
                .Setup(x => x.RetrieveExceptionReportSessionDatesAsync(It.IsAny<RetrieveExceptionReportSessionDatesRequest>()))
               .ReturnsAsync(response);

            var loggerMock = new Mock<ILogger>();
            loggerMock.Setup(x => x.LogInfo(null));

            var controller = new ExceptionReportController(loggerMock.Object);

            var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext() };
            ctx.HttpContext.Request.Headers["token"] = "fake_token_here"; //Set header
            controller.ControllerContext = ctx;

            //Act
            var result = controller.GetExceptionReportSessionData();

            //Assert
            var viewResult = Assert.IsType<OkObjectResult>(result);

            Assert.Equal(StatusCodes.Status200OK, viewResult.StatusCode);

        }
</code>```

Here is the endpoint logic:

```<code>RetrieveExceptionReportSessionDatesResponse response
                = await ResolveServiceClient().RetrieveExceptionReportSessionDatesAsync(new RetrieveExceptionReportSessionDatesRequest());

            List<ExceptionReportSessionDataModel> result
                = GetSessionData(response.RetrieveExceptionReportSessionDatesResult);

            if (result != null && result.Count > 0)
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.EditSession,
                                "Get Exception Report Session Data", "Exception Report Session Data retrieved successfully.");
                logger.LogInfo(logText);
            }
            else
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get exception report session data", "Exception report session data is null or empty.");
                logger.LogWarn(logText);
            }
            return Ok(result);
</code>```

Here is the GetSessionData method called in the endpoint:

```<code>private List<ExceptionReportSessionDataModel> GetSessionData(string sessionData)
    {
        List<ExceptionReportSessionDataModel> reports = new List<ExceptionReportSessionDataModel>();
        if (!string.IsNullOrWhiteSpace(sessionData))
        {
            string[] splitString = sessionData.Split("\n", StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in splitString)
            {
                string[] temp = s.Split(",", StringSplitOptions.RemoveEmptyEntries);

                List<string> files = new List<string>();

                for (int index = 1; index < temp.Length; index++)
                {
                    files.Add(temp[index]);
                }
                reports.Add(new ExceptionReportSessionDataModel()
                {
                    ReportFiles = files,
                    SessionName = temp[0]
                });
            }
        }
        return reports;
    }
</code>```

How do I finish writing a successful test?

答:
You have not provided definition of ResolveServiceClient() method.

Follow below steps to write a Unit Test.

Learn Unit Testing. No jokes here. Before writing any unit test you need to have some understanding of how it works and why to write them. Understanding of SOLID principles would help in this process.

Analyze the SUT or the method you are testing and list down all the dependencies. External Dependencies are classes that perform some tasks for your method. You are testing current method so, everything that does not belong to your class needs to be decoupled. In other words, you cannot Unit test a class which calls static methods and initializes external dependencies in the method code. Here, in your code LogFormatter and WebUtilities seems like they are static classes.

Analyze the method and note down all the exit points. For e.g. return statements, exceptions, etc. You have to write at least one unit test for each exit statement.

Analyze the method and note down all the if-else conditions. You have to write a unit test for each condition.

Apart from all the theory, your controller seems like a simple case.
Here, if the LogFormatter does not throw any error then you don't have to decouple it.
But the WebUtility seems problematic. So, I would suggest creating a service for it and injecting it in the controller so that you can pass Mock or Stub of it from the Unit test.

There is nothing problematic in the GetSessions() method just write cases for each condition and you will be good to go.

One little tip here, I try to keep the controllers as light as possible. Generally, my controllers are just converting the DTO to service DTO and calling the service. So I don't write unit tests for controllers. But I am not sure everybody does this.

Body:
I did not write the endpoint or the service. I am needing to use this endpoint for an application I am building and I was asked to write a unit test on it. I'm having some issues correctly writing the test. Here is what I have so far in my test:

public void GetExceptionReportSessionData_ReturnsSessionData()
        {
            //Arrange
            var response = new RetrieveExceptionReportSessionDatesResponse();
            var serviceClient = new Mock<WorkflowService.WorkflowService>();
            serviceClient
                .Setup(x => x.RetrieveExceptionReportSessionDatesAsync(It.IsAny<RetrieveExceptionReportSessionDatesRequest>()))
               .ReturnsAsync(response);

            var loggerMock = new Mock<ILogger>();
            loggerMock.Setup(x => x.LogInfo(null));

            var controller = new ExceptionReportController(loggerMock.Object);

            var ctx = new ControllerContext() { HttpContext = new DefaultHttpContext() };
            ctx.HttpContext.Request.Headers["token"] = "fake_token_here"; //Set header
            controller.ControllerContext = ctx;

            //Act
            var result = controller.GetExceptionReportSessionData();

            //Assert
            var viewResult = Assert.IsType<OkObjectResult>(result);

            Assert.Equal(StatusCodes.Status200OK, viewResult.StatusCode);

        }

Here is the endpoint logic:

RetrieveExceptionReportSessionDatesResponse response
                = await ResolveServiceClient().RetrieveExceptionReportSessionDatesAsync(new RetrieveExceptionReportSessionDatesRequest());

            List<ExceptionReportSessionDataModel> result
                = GetSessionData(response.RetrieveExceptionReportSessionDatesResult);

            if (result != null && result.Count > 0)
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.EditSession,
                                "Get Exception Report Session Data", "Exception Report Session Data retrieved successfully.");
                logger.LogInfo(logText);
            }
            else
            {
                logText = LogFormatter.Format(
                                WebUtilities.GetUser((ClaimsIdentity)HttpContext.User.Identity),
                                startTime, DateTime.Now, Privilege.ViewOrderExceptionReport,
                                "Get exception report session data", "Exception report session data is null or empty.");
                logger.LogWarn(logText);
            }
            return Ok(result);

Here is the GetSessionData method called in the endpoint:

private List<ExceptionReportSessionDataModel> GetSessionData(string sessionData)
    {
        List<ExceptionReportSessionDataModel> reports = new List<ExceptionReportSessionDataModel>();
        if (!string.IsNullOrWhiteSpace(sessionData))
        {
            string[] splitString = sessionData.Split("\n", StringSplitOptions.RemoveEmptyEntries);

            foreach (string s in splitString)
            {
                string[] temp = s.Split(",", StringSplitOptions.RemoveEmptyEntries);

                List<string> files = new List<string>();

                for (int index = 1; index < temp.Length; index++)
                {
                    files.Add(temp[index]);
                }
                reports.Add(new ExceptionReportSessionDataModel()
                {
                    ReportFiles = files,
                    SessionName = temp[0]
                });
            }
        }
        return reports;
    }

How do I finish writing a successful test?


来源: stackexchange

问:
Refactor Java Program
Problem: I have list of houses in an Array. I need to make sure atleast one list consist of only houses with cat and atleast one list consist of only houses with dog. A list should only contain one kind of houses (i.e no mixed case). It is assumed that a house can either have a cat or a dog.

I tried writing the code, but it does not look good and would appreciate your help on refactoring or improving the design.

```<code>    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){
       Boolean isHousesWithCat = true;
       Boolean isHousesWithDog = true;
       for(House house: houseList){
          if(house.hasCat()){
             isHousesWithDog = false;
          }else{
             isHousesWithCat = false;
          }
       }
       if(!isHousesWithDog && ! isHousesWithCat){
          return false; //This is mixed case. The list contains both of kind of houses
       }
       isListWithHouseAndCatExist=isHousesWithCat?true:isListWithHouseAndCatExist;
       isListWithHouseAndDogExist=isHousesWithDog?true:isListWithHouseAndDogExist;
    }

    // Now to check that we have atleast one list with all House-Cat and atleast one list with all
    // House-Dog
    if(!isListWithHouseAndCatExist || !isListWithHouseAndDogExist){
      return false;
   }
   return true;
</code>```

As you can see I had to use four Boolean variable to validate conditions. Could you please help to improve the code.

答:
If you don't want to use streams and only want to iterate once, you could do something like this:

```<code>    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){

        Set<Boolean> hasCatFlags = new HashSet<>();
        for(House house: houseList){
            hasCatFlags.add(house.hasCat());
        }
        if(hasCatFlags.size() > 1){
            return false; //This is mixed case. The list contains both of kind of houses
        }
        if (hasCatFlags.contains(true)) {
            isListWithHouseAndCatExist = true;
        } else if (hasCatFlags.contains(false)) {
            isListWithHouseAndDogExist = true;
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;
</code>```

If you can use streams but want to iterate only once, you could do something like this:

```<code>    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){

        Set<Boolean> hasCatFlags = houseList.stream().map(House::hasCat).collect(Collectors.toSet());
        if(hasCatFlags.size() > 1){
            return false; //This is mixed case. The list contains both of kind of houses
        }

        if (hasCatFlags.contains(true)) {
            isListWithHouseAndCatExist = true;
        } else if (hasCatFlags.contains(false)) {
            isListWithHouseAndDogExist = true;
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;
</code>```

And if you can use streams and don't mind iterating twice, you could do this:

```<code>    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    for(List<House> houseList : getArrOfHouseList()){
        if (houseList.stream().allMatch(House::hasCat)) {
            isListWithHouseAndCatExist = true;
        } else if (houseList.stream().noneMatch(House::hasCat)) {
            isListWithHouseAndDogExist = true;
        } else {
            return false;//mixed case
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Refactor Java Program

Body:
Problem: I have list of houses in an Array. I need to make sure atleast one list consist of only houses with cat and atleast one list consist of only houses with dog. A list should only contain one kind of houses (i.e no mixed case). It is assumed that a house can either have a cat or a dog.

I tried writing the code, but it does not look good and would appreciate your help on refactoring or improving the design.

    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){
       Boolean isHousesWithCat = true;
       Boolean isHousesWithDog = true;
       for(House house: houseList){
          if(house.hasCat()){
             isHousesWithDog = false;
          }else{
             isHousesWithCat = false;
          }
       }
       if(!isHousesWithDog && ! isHousesWithCat){
          return false; //This is mixed case. The list contains both of kind of houses
       }
       isListWithHouseAndCatExist=isHousesWithCat?true:isListWithHouseAndCatExist;
       isListWithHouseAndDogExist=isHousesWithDog?true:isListWithHouseAndDogExist;
    }

    // Now to check that we have atleast one list with all House-Cat and atleast one list with all
    // House-Dog
    if(!isListWithHouseAndCatExist || !isListWithHouseAndDogExist){
      return false;
   }
   return true;

As you can see I had to use four Boolean variable to validate conditions. Could you please help to improve the code.

Body:
If you don't want to use streams and only want to iterate once, you could do something like this:

    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){

        Set<Boolean> hasCatFlags = new HashSet<>();
        for(House house: houseList){
            hasCatFlags.add(house.hasCat());
        }
        if(hasCatFlags.size() > 1){
            return false; //This is mixed case. The list contains both of kind of houses
        }
        if (hasCatFlags.contains(true)) {
            isListWithHouseAndCatExist = true;
        } else if (hasCatFlags.contains(false)) {
            isListWithHouseAndDogExist = true;
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;

If you can use streams but want to iterate only once, you could do something like this:

    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    List<House>[] arrOfHouseList = getArrOfHouseList();
    for(List<House> houseList : arrOfHouseList){

        Set<Boolean> hasCatFlags = houseList.stream().map(House::hasCat).collect(Collectors.toSet());
        if(hasCatFlags.size() > 1){
            return false; //This is mixed case. The list contains both of kind of houses
        }

        if (hasCatFlags.contains(true)) {
            isListWithHouseAndCatExist = true;
        } else if (hasCatFlags.contains(false)) {
            isListWithHouseAndDogExist = true;
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;

And if you can use streams and don't mind iterating twice, you could do this:

    Boolean isListWithHouseAndCatExist = false;
    Boolean isListWithHouseAndDogExist = false;
    for(List<House> houseList : getArrOfHouseList()){
        if (houseList.stream().allMatch(House::hasCat)) {
            isListWithHouseAndCatExist = true;
        } else if (houseList.stream().noneMatch(House::hasCat)) {
            isListWithHouseAndDogExist = true;
        } else {
            return false;//mixed case
        }
    }

    return isListWithHouseAndCatExist && isListWithHouseAndDogExist;


问:
How to add active class to link on click
I have below code and i want make the clicked link active. I tried different approaches but did not work.</p>

```<code> <div id="collapse1" class="panel-collapse collapse">
    <ul class="list-group">
      <a><li class="list-group-item active" style="background-color: #394263;color: white">A</li></a>
      <a><li class="list-group-item" style="background-color: #394263;color: white">B</li></a>
        <a><li class="list-group-item" style="background-color: #394263;color: white">C</li></a>
    </ul>
  </div>
</code>```

答:
The generally recommended way to handle browser events in JavaScript is with event listeners, and the best way I know to add/remove a class is with the classList property.

This simple demo shows how you can use them.

(See the in-code comments, and possibly the linked MDN resources, for more info)

// Identifies an HTML element
const myDiv = document.getElementById("my-div");

// Calls the `toggleBlue` function whenever the element is clicked
myDiv.addEventListener("click", toggleBlue);

// Defines the `toggleBlue` function
function toggleBlue(event){ // Listeners can access their triggering events
  const clickedThing = event.target; // Events have a `target` property

  // DOM elements have a `classList` property, which includes the
  //   methods `.contains`, `.remove`, and `.add`
  if(clickedThing.classList.contains("blue")){
    clickedThing.classList.remove("blue");
  }
  else{
    clickedThing.classList.add("blue");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#my-div{ width: 20ch; border: 1px solid grey; font-weight: bold; }
.blue{ color: blue; }</code>```

Some content
```

Body:
I have below code and i want make the clicked link active. I tried different approaches but did not work.

A

B

C

Body:
The generally recommended way to handle browser events in JavaScript is with event listeners, and the best way I know to add/remove a class is with the classList property.

This simple demo shows how you can use them.

(See the in-code comments, and possibly the linked MDN resources, for more info)

// Identifies an HTML element
const myDiv = document.getElementById("my-div");

// Calls the `toggleBlue` function whenever the element is clicked
myDiv.addEventListener("click", toggleBlue);

// Defines the `toggleBlue` function
function toggleBlue(event){ // Listeners can access their triggering events
  const clickedThing = event.target; // Events have a `target` property

  // DOM elements have a `classList` property, which includes the
  //   methods `.contains`, `.remove`, and `.add`
  if(clickedThing.classList.contains("blue")){
    clickedThing.classList.remove("blue");
  }
  else{
    clickedThing.classList.add("blue");
  }
}

#my-div{ width: 20ch; border: 1px solid grey; font-weight: bold; }
.blue{ color: blue; }

<div id="my-div">Some content</div>


问:
Map the value of a new column by searching another dataframe
I have two dataframes: df_geo and df_event. I want to create two new columns in df_event.  The data frames resemble the following, although additional columns have been removed for the sake of simplicity:

```<code>data_geo =  [['040','01','000','00000','00000','00000','Alabama'],
             ['050','01','001','00000','00000','00000','Autauga County'],
             ['050','01','097','00000','00000','00000','Mobile County'],
             ['050','01','101','00000','00000','00000','Montgomery County'],
             ['050','01','115','00000','00000','00000','St. Clair County'],
             ['040','09','000','00000','00000','00000','Connecticut'],
             ['061','09','001','04720','00000','00000','Bethel town'],
             ['040','17','000','00000','00000','00000','Illinois'],
             ['061','17','109','05638','00000','00000','Bethel township'],
             ['050','17','163','00000','00000','00000','St. Clair County']]

dfgeo = pd.DataFrame(data_geo, columns = ['summary_level', 'state_fips','county_fips','subdivision_code_fips','place_code_fips','city_code_fips','area_name'])

df_geo.info()

RangeIndex: 43847 entries, 0 to 43846
Data columns (total 7 columns):
summary_level            43847 non-null object
state_fips               43847 non-null object
county_fips              43847 non-null object
subdivision_code_fips    43847 non-null object
place_code_fips          43847 non-null object
city_code_fips           43847 non-null object
area_name                43847 non-null object
</code>```

```<code>data_event = [['event_id','_','Alabama'],
              ['event_id','_','Connecticut'],
              ['event_id','Autauga County','Alabama'],
              ['event_id','Fairfield County','Connecticut'],
              ['event_id','Fairbanks North Star Borough','Alaska']]

df_event = pd.DataFrame(data_event, columns = ['event_id','county','state'])

df_event.info()

RangeIndex: 1261 entries, 0 to 1260
Data columns (total 3 columns):
event_id                1261 non-null object
county                   999 non-null object
state                   1261 non-null object
dtypes: object(3)

</code>```

GOAL to create a function that can take the county and state inputs from df_event and in order to create two new columns in the same dataframe.  The new columns are based on the values of state_fips and county_fips in df_geo.  An example of this would look like the following:

```<code>inputA fun('df_geo','Connecticut','Fairfield County'):

resultA = ['event_id','Connecticut','Fairfield County','09','001']
                                                       ^New columns

inputB fun('df_geo','Alaska','Fairbanks North Star Borough'):

resultB = ['event_id','Alaska','Fairbanks North Star Borough','02','090']
                                                              ^New columns

</code>```

This is a PROBLEM because I also need to use this function on a list of 1,200 (and growing) events the function would have to work within a lamba function or something else that can map it across the entire dataframe.

This is complicated by identical County names like "St. Clair County" that appear in several states.  Although their area_names are identical the value of state_fips will be different.

The state_fips of St. Clair Illinois is 17, the same as all other counties in Illinois and the state itself.  The state_fips of St. Clair Alabama is 01, the same as all other counties in Alabama, and so on...

I would like to use the same search and map function all the way down to city_code_fips.  At that level any search terms have to be exactly the same to avoid picking up "Bethel town" when I intend to find "Bethel township".  Exact inputs are also important because some states, like Louisiana, call their county level geographies by another name.

In df_event a '_' indicates that the county is unknown.

df_event['event_id'] is a unique string.  There are rows in the dataframe that are nearly identical but with different ids indicating that an event has occurred on multiple occasions.  This has no affect on the. state_fips or county_fips.

I know this is a multi step process but all help is appreciated. Thank you.

答:
You can do this using df.merge:

```<code>In [289]: df_event['state_fips'] = df_event.merge(dfgeo[['state_fips','area_name']], left_on='state', right_on='area_name', how='left')['state_fips']
In [290]: df_event['county_fips'] = df_event.merge(dfgeo[['county_fips','area_name']], left_on='county', right_on='area_name', how='left')['county_fips']

In [291]: df_event
Out[291]:
  unique_str                        county        state state_fips county_fips
0   Event Id                             _      Alabama         01         NaN
1   Event Id                             _  Connecticut         09         NaN
2   Event Id                Autauga County      Alabama         01         001
3   Event Id              Fairfield County  Connecticut         09         001
4   Event Id  Fairbanks North Star Borough       Alaska         02         090
</code>```

Body:
I have two dataframes: df_geo and df_event. I want to create two new columns in df_event.  The data frames resemble the following, although additional columns have been removed for the sake of simplicity:

data_geo =  [['040','01','000','00000','00000','00000','Alabama'],
             ['050','01','001','00000','00000','00000','Autauga County'],
             ['050','01','097','00000','00000','00000','Mobile County'],
             ['050','01','101','00000','00000','00000','Montgomery County'],
             ['050','01','115','00000','00000','00000','St. Clair County'],
             ['040','09','000','00000','00000','00000','Connecticut'],
             ['061','09','001','04720','00000','00000','Bethel town'],
             ['040','17','000','00000','00000','00000','Illinois'],
             ['061','17','109','05638','00000','00000','Bethel township'],
             ['050','17','163','00000','00000','00000','St. Clair County']]

dfgeo = pd.DataFrame(data_geo, columns = ['summary_level', 'state_fips','county_fips','subdivision_code_fips','place_code_fips','city_code_fips','area_name'])

df_geo.info()

RangeIndex: 43847 entries, 0 to 43846
Data columns (total 7 columns):
summary_level            43847 non-null object
state_fips               43847 non-null object
county_fips              43847 non-null object
subdivision_code_fips    43847 non-null object
place_code_fips          43847 non-null object
city_code_fips           43847 non-null object
area_name                43847 non-null object

data_event = [['event_id','_','Alabama'],
              ['event_id','_','Connecticut'],
              ['event_id','Autauga County','Alabama'],
              ['event_id','Fairfield County','Connecticut'],
              ['event_id','Fairbanks North Star Borough','Alaska']]

df_event = pd.DataFrame(data_event, columns = ['event_id','county','state'])

df_event.info()

RangeIndex: 1261 entries, 0 to 1260
Data columns (total 3 columns):
event_id                1261 non-null object
county                   999 non-null object
state                   1261 non-null object
dtypes: object(3)

GOAL to create a function that can take the county and state inputs from df_event and in order to create two new columns in the same dataframe.  The new columns are based on the values of state_fips and county_fips in df_geo.  An example of this would look like the following:

inputA fun('df_geo','Connecticut','Fairfield County'):

resultA = ['event_id','Connecticut','Fairfield County','09','001']
                                                       ^New columns

inputB fun('df_geo','Alaska','Fairbanks North Star Borough'):

resultB = ['event_id','Alaska','Fairbanks North Star Borough','02','090']
                                                              ^New columns

This is a PROBLEM because I also need to use this function on a list of 1,200 (and growing) events the function would have to work within a lamba function or something else that can map it across the entire dataframe.

This is complicated by identical County names like "St. Clair County" that appear in several states.  Although their area_names are identical the value of state_fips will be different.

The state_fips of St. Clair Illinois is 17, the same as all other counties in Illinois and the state itself.  The state_fips of St. Clair Alabama is 01, the same as all other counties in Alabama, and so on...

I would like to use the same search and map function all the way down to city_code_fips.  At that level any search terms have to be exactly the same to avoid picking up "Bethel town" when I intend to find "Bethel township".  Exact inputs are also important because some states, like Louisiana, call their county level geographies by another name.

In df_event a '_' indicates that the county is unknown.

df_event['event_id'] is a unique string.  There are rows in the dataframe that are nearly identical but with different ids indicating that an event has occurred on multiple occasions.  This has no affect on the. state_fips or county_fips.

I know this is a multi step process but all help is appreciated. Thank you.

Body:
You can do this using df.merge:

In [289]: df_event['state_fips'] = df_event.merge(dfgeo[['state_fips','area_name']], left_on='state', right_on='area_name', how='left')['state_fips']
In [290]: df_event['county_fips'] = df_event.merge(dfgeo[['county_fips','area_name']], left_on='county', right_on='area_name', how='left')['county_fips']

In [291]: df_event
Out[291]:
  unique_str                        county        state state_fips county_fips
0   Event Id                             _      Alabama         01         NaN
1   Event Id                             _  Connecticut         09         NaN
2   Event Id                Autauga County      Alabama         01         001
3   Event Id              Fairfield County  Connecticut         09         001
4   Event Id  Fairbanks North Star Borough       Alaska         02         090


问:
Unknown custom element in Vuetify
I am new to Vuetify and vue. I am using vue and vuetify but due some reason I am not able open my page.The error I am getting when I run my project:

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

found in

--->  at resources/js/components/appContainer.vue

My code:

```<code>appContainer.vue

<template>
  <v-app id="inspire">
    <v-navigation-drawer
      v-model="drawer"
      app
    >
      <v-list dense>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-home</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Home</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-contact-mail</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Contact</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>

    <v-app-bar
      app
      color="indigo"
      dark
    >
      <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
      <v-toolbar-title>Application</v-toolbar-title>
    </v-app-bar>

    <v-content>
      <v-container
        class="fill-height"
        fluid
      >
        <v-row
          align="center"
          justify="center"
        >
          <v-col class="text-center">
            <v-tooltip left>
              <template v-slot:activator="{ on }">
                <v-btn
                  :href="source"
                  icon
                  large
                  target="_blank"
                  v-on="on"
                >
                  <v-icon large>mdi-code-tags</v-icon>
                </v-btn>
              </template>
              <span>Source</span>
            </v-tooltip>
          </v-col>
        </v-row>
      </v-container>
    </v-content>
    <v-footer
      color="indigo"
      app
    >
      <span class="white--text">© 2019</span>
    </v-footer>
  </v-app>
</template>

<script>
  export default {
    props: {
      source: String,
    },
    data: () => ({
      drawer: null,
    }),
  }
</script>
</code>```

app.js

```<code>require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'

import Vuetify from './plugins/vuetify'

Vue.use(Vuetify);

Vue.component('app-container', require('./components/appContainer.vue').default);

const app = new Vue({
    Vuetify,
    Vue,
    el: '#app',
});
</code>```

spa.blade.php

```<code><!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <app-container></app-container>

    </div>
</body>
</html>
</code>```

vuetify.js

```<code>import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

const opts = {}

export default new Vuetify(opts)
</code>```

答:
Seems like you haven't given an export name for your app-container element. Try the below.

appContainer.vue

```<code><template>
  ...
</template>
<script>
  export default {
    name: 'app-container'
    props: {
      source: String,
    },
    data: () => ({
      drawer: null,
    }),
  }
</script>
</code>```

Title: Unknown custom element in Vuetify

Body:
I am new to Vuetify and vue. I am using vue and vuetify but due some reason I am not able open my page.The error I am getting when I run my project:

[Vue warn]: Unknown custom element:  - did you register the
  component correctly? For recursive components, make sure to provide
  the "name" option.

found in

--->  at resources/js/components/appContainer.vue

My code:

appContainer.vue

<template>
  <v-app id="inspire">
    <v-navigation-drawer
      v-model="drawer"
      app
    >
      <v-list dense>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-home</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Home</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
        <v-list-item link>
          <v-list-item-action>
            <v-icon>mdi-contact-mail</v-icon>
          </v-list-item-action>
          <v-list-item-content>
            <v-list-item-title>Contact</v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list>
    </v-navigation-drawer>

    <v-app-bar
      app
      color="indigo"
      dark
    >
      <v-app-bar-nav-icon @click.stop="drawer = !drawer"></v-app-bar-nav-icon>
      <v-toolbar-title>Application</v-toolbar-title>
    </v-app-bar>

    <v-content>
      <v-container
        class="fill-height"
        fluid
      >
        <v-row
          align="center"
          justify="center"
        >
          <v-col class="text-center">
            <v-tooltip left>
              <template v-slot:activator="{ on }">
                <v-btn
                  :href="source"
                  icon
                  large
                  target="_blank"
                  v-on="on"
                >
                  <v-icon large>mdi-code-tags</v-icon>
                </v-btn>
              </template>
              Source
            </v-tooltip>
          </v-col>
        </v-row>
      </v-container>
    </v-content>
    <v-footer
      color="indigo"
      app
    >
      © 2019
    </v-footer>
  </v-app>
</template>

app.js

require('./bootstrap');

window.Vue = require('vue');

import Vue from 'vue'

import Vuetify from './plugins/vuetify'

Vue.use(Vuetify);

Vue.component('app-container', require('./components/appContainer.vue').default);

const app = new Vue({
    Vuetify,
    Vue,
    el: '#app',
});

spa.blade.php

<!doctype html>
getLocale()) }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">

    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

        <app-container></app-container>

vuetify.js

import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

const opts = {}

export default new Vuetify(opts)

Body:
Seems like you haven't given an export name for your app-container element. Try the below.

appContainer.vue

<template>
  ...
</template>
<script>
  export default {
    name: 'app-container'
    props: {
      source: String,
    },
    data: () => ({
      drawer: null,
    }),
  }
</script>


问:
Corrupted virtual environments after update to Python 3.7
I have recently upgraded my conda distribution to Python 3.7 from Python 3.6 (using the conda install python=3.7 command).

I didn't realize that this upgrade corrupted all of my existing virtual environments that I created using virtualenv. I naively thought that the virtual environments included all the python libraries needed to run, even if I upgraded my distribution.

If I run 'source venv/bin/activate' I am able to run the virtual environment, but if I try to start python I get an error:

```<code>Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007fff92b5f380 (most recent call first):
Abort trap: 6
</code>```

I think the problem is that the virtualenv libraries link to bin/python3.6, but that folder does not exist anymore. How can I solve this problem? I really don't want to recreate the virtual environments, since some of them took a very long time to build and use libraries that took forever to build from source.

I tried to revert back to conda 3.6, but that failed because there were way too many conflicts.

Thank you for your help!

答:
Try cloning the environment to a new one with command:
conda create --clone cur_env_name --name new_env_name

Body:
I have recently upgraded my conda distribution to Python 3.7 from Python 3.6 (using the conda install python=3.7 command).

I didn't realize that this upgrade corrupted all of my existing virtual environments that I created using virtualenv. I naively thought that the virtual environments included all the python libraries needed to run, even if I upgraded my distribution.

If I run 'source venv/bin/activate' I am able to run the virtual environment, but if I try to start python I get an error:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007fff92b5f380 (most recent call first):
Abort trap: 6

I think the problem is that the virtualenv libraries link to bin/python3.6, but that folder does not exist anymore. How can I solve this problem? I really don't want to recreate the virtual environments, since some of them took a very long time to build and use libraries that took forever to build from source.

I tried to revert back to conda 3.6, but that failed because there were way too many conflicts.

Thank you for your help!


问:
Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"
I am using Android studio 1.0.1. I have a java module referred by other modules in my project. I have checked it out from SVN But now every

Unsupported Modules Detected: Compilation is not supported for following modules: . Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project.

After getting this error AS stop compilation of this module so that I am not able to compile/run my project any more.

答:
The above solution I've tried but didn't work for me.

I deleted the .idea folder from project directory.

Invalidate caches using Android Studio menu File -> Invalidate Caches / Restart

Deleted .gradle folder from user profile directory of Windows 10 operating system. (i.e., C:\Users\YourUserName\.gradle)

Try this solution if the above not working.

ContentLicense: CC BY-SA 3.0


问:
Trying to Get a Twitter Bot to Tweet Two Images at Once
I'm working on a twitter bot that has the goal of posting two images along with a string of text. I'm using node.js (for the first time, I should probably add) and the Twit package.

I'm having a variety of issues, many of which are likely just due to me being a novice, but I genuinely can't figure out how to make the dang thing output correctly. I've managed to get text and a single image to output, but I'm trying to spit out two images at once.

The main bot chunk uses the following code to build and schedule a tweet:

```<code>function mainPostBot() {
console.log("Now assembling a new tweet.");

var leftCard = getRandomNumber(1, 36);
    console.log("The left card is #" + leftCard + ", " + cardNames[leftCard] + ".");
    // Generates a random number for the left card.
var leftImagePath = path.join(__dirname, '/leftImage/' + imageArray[leftCard]);
    console.log("The left image's path is " + leftImagePath);
    // Gives the file path to access the correct image for the left.

var rightCard = getRandomNumber(1, 36);
    console.log("The right card is #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card.
while (leftCard == rightCard) {
    var rightCard = getRandomNumber(1, 36);
    console.log("Whoops! The right card is now #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card in the case of doubles.
}
var rightImagePath = path.join(__dirname, '/rightImage/' + imageArray[rightCard]);
    console.log("The right image's path is " + rightImagePath);
    // Gives the file path to access the correct image for the left.

console.log('Encoding the images...');
    var b64contentLeft = fs.readFileSync(leftImagePath, { encoding: 'base64' });
    var b64contentRight = fs.readFileSync(rightImagePath, { encoding: 'base64' });
    var bothImages = (b64contentLeft + "," + b64contentRight);
    // This encodes the images in base64, which twitter needs. I guess. I dunno, man.

var tweetText = (jsUcfirst(cardNames[leftCard]) + ' and ' + cardNames[rightCard] + '. (#' + leftCard + " " + cardCorrespond[leftCard] + "/#" + rightCard + " " + cardCorrespond[rightCard] + ")");
// This constructs the grammar of the tweet.
// jsUcfirst capitalizes the first letter of a string so it lets me cheat a sentence start.

var tweetTime = getRandomNumber(1000*60*60*4, 1000*60*60*24*3+1);
    // Generates an amount of time before the next tweet.

sendTweet(tweetText, bothImages, tweetTime);

setTimeout(mainPostBot, tweetTime);
}

mainPostBot();
</code>```

cardNames, cardCorrespond, and imageArray are just big arrays at the top of the program that list the names of the images, some info about them, and their filenames, respectively:

```<code>var cardNames = new Array(
    "the Fool", //This one will never be called bc of the number generator and it's fun bc, y'know, Tarot
    "the Rider","the Clover","the Ship","the House","the Tree","the Clouds","the Snake","the Coffin","the Bouquet","the Scythe","the Whip", //"the Nae Nae",
    "the Birds","the Child","the Fox","the Bear","the Stars","the Stork","the Dog","the Tower","the Garden","the Mountain","the Crossroads",
    "the Mice","the Heart","the Ring","the Book","the Letter","the Gentleman","the Lady","the Lily","the Sun","the Moon","the Key","the Fish",
    "the Anchor","the Cross"
    );

var cardCorrespond = new Array(
    " ","9♥","6♦","10♠","K♥","7♥","K♣","Q♣","9♦","Q♠","J♦","J♣","7♦","J♠","9♣","10♣","6♥","Q♥","10♥",
    "6♠","8♠","8♣","Q♦","7♣","J♥","A♣","10♦","7♠","A♥","A♠","K♠","A♦","8♥","8♦","K♦","9♠","6♣"
    );

var imageArray = new Array(
    " ","01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png","12.png","13.png",
    "14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png","22.png","23.png","24.png","25.png","26.png",
    "27.png","28.png","29.png","30.png","31.png","32.png","33.png","34.png","35.png","36.png"
    );
</code>```

And once mainPostBot has the tweet fully constructed, it's delivered to sendTweet:

```<code>function sendTweet(text, images, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: images }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the images.");
            console.log(err);
        } else {
            console.log('Images uploaded!');
            console.log("Now tweeting...")

            T.post('statuses/update', {
                status: text,
                media_ids: new Array(data.media_id_string)
            }, function(err, data, response){
                if (err) {
                    console.log("An error has occurred during posting.");
                    console.log(err);
                } else {
                    console.log("Post successful!");
                    console.log("The tweet says:" + text);
                    console.log("The next tweet will send in " + msToTime(time) + "!");
                }
            });
        }
    });
}
</code>```

Any ideas? I'm open to using other npm packages, for sure, but I just can't figure out why this doesn't work as it is. Thanks for reading, and let me know if you need any other bits of the code.

EDIT 1: My roommate who also dabbles in this sort of stuff found a potentially useful link on github for another package, node-twitter. In that link, a poster explains that the images should be delivered as a string, separated by commas, so I added some edits to mainPostBot and sendTweet, mostly in the passing of b64 image data.

EDIT 2: Those edits are now reflected in the code above, as well as some other fixes I've made to the project as a whole. I got to a point where things are running smoothly again (found a missing bracket, I suck at this coding stuff), and there's tweets posting successfully, but just as before I'm not getting the second image through. Roommate who helped earlier is suggesting to just pump out static single images for every possible card combination but there's gotta be a more elegant solution. Again, any ideas could save a week of my weird bedroom tinkering, and I appreciate any eyes on this.

答:
It took a lot of tinkering, but I figured it out. Each image has to be uploaded to twitter individually, so after loading the image, I save it's data.media_id_string to a variable, and then load those values into the tweet in an array.

I've removed the line from mainPostBot where I combined b64contentLeft and b64contentRight and added it into the sendTweet code, using the returned data strings. Now, I call sendTweet() with:

```<code>sendTweet(tweetText, b64contentLeft, b64contentRight, tweetTime);
</code>```

And sendTweet() is now looking like this:

```<code>function sendTweet(text, leftimage, rightimage, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: leftimage }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the left image.");
            console.log(err);
        } else {
            console.log('Left image uploaded!');
            var leftID = data.media_id_string;

            T.post('media/upload', { media_data: rightimage }, function (err, data, response){
                if (err){
                    console.log("There's an issue uploading the right image.");
                    console.log(err);
                } else {
                    console.log('Right image uploaded!');
                    var rightID = data.media_id_string;
                    var bothImages = ( leftID + "," + rightID );

                    console.log("Now tweeting...")

                    T.post('statuses/update', {
                        status: text,
                        media_ids: new Array(bothImages)
                    }, function(err, data, response){
                        if (err) {
                            console.log("An error has occurred during posting.");
                            console.log(err);
                        } else {
                            console.log("Post successful!");
                            console.log("The tweet says: " + text);
                            console.log("The next tweet will send in " + msToTime(time) + "!");
                        }
                    });
                }
            });
        }
    });
}
</code>```

Essentially, if the left image uploads correctly, it'll save that ID, then try for the right image. IF that's successful, it'll save that ID as well, then combine the two into a string separated with a comma, which is loaded into the media_ids array as bothImages.

This was kind of a nightmare to solve, but I wanted to make sure it's documented in case anyone else stumbles here looking for the same answer.

Body:
I'm working on a twitter bot that has the goal of posting two images along with a string of text. I'm using node.js (for the first time, I should probably add) and the Twit package.

I'm having a variety of issues, many of which are likely just due to me being a novice, but I genuinely can't figure out how to make the dang thing output correctly. I've managed to get text and a single image to output, but I'm trying to spit out two images at once.

The main bot chunk uses the following code to build and schedule a tweet:

function mainPostBot() {
console.log("Now assembling a new tweet.");

var leftCard = getRandomNumber(1, 36);
    console.log("The left card is #" + leftCard + ", " + cardNames[leftCard] + ".");
    // Generates a random number for the left card.
var leftImagePath = path.join(__dirname, '/leftImage/' + imageArray[leftCard]);
    console.log("The left image's path is " + leftImagePath);
    // Gives the file path to access the correct image for the left.

var rightCard = getRandomNumber(1, 36);
    console.log("The right card is #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card.
while (leftCard == rightCard) {
    var rightCard = getRandomNumber(1, 36);
    console.log("Whoops! The right card is now #" + rightCard + ", " + cardNames[rightCard] + ".");
    // Generates a random number for the right card in the case of doubles.
}
var rightImagePath = path.join(__dirname, '/rightImage/' + imageArray[rightCard]);
    console.log("The right image's path is " + rightImagePath);
    // Gives the file path to access the correct image for the left.

console.log('Encoding the images...');
    var b64contentLeft = fs.readFileSync(leftImagePath, { encoding: 'base64' });
    var b64contentRight = fs.readFileSync(rightImagePath, { encoding: 'base64' });
    var bothImages = (b64contentLeft + "," + b64contentRight);
    // This encodes the images in base64, which twitter needs. I guess. I dunno, man.

var tweetText = (jsUcfirst(cardNames[leftCard]) + ' and ' + cardNames[rightCard] + '. (#' + leftCard + " " + cardCorrespond[leftCard] + "/#" + rightCard + " " + cardCorrespond[rightCard] + ")");
// This constructs the grammar of the tweet.
// jsUcfirst capitalizes the first letter of a string so it lets me cheat a sentence start.

var tweetTime = getRandomNumber(1000*60*60*4, 1000*60*60*24*3+1);
    // Generates an amount of time before the next tweet.

sendTweet(tweetText, bothImages, tweetTime);

setTimeout(mainPostBot, tweetTime);
}

mainPostBot();

cardNames, cardCorrespond, and imageArray are just big arrays at the top of the program that list the names of the images, some info about them, and their filenames, respectively:

var cardNames = new Array(
    "the Fool", //This one will never be called bc of the number generator and it's fun bc, y'know, Tarot
    "the Rider","the Clover","the Ship","the House","the Tree","the Clouds","the Snake","the Coffin","the Bouquet","the Scythe","the Whip", //"the Nae Nae",
    "the Birds","the Child","the Fox","the Bear","the Stars","the Stork","the Dog","the Tower","the Garden","the Mountain","the Crossroads",
    "the Mice","the Heart","the Ring","the Book","the Letter","the Gentleman","the Lady","the Lily","the Sun","the Moon","the Key","the Fish",
    "the Anchor","the Cross"
    );

var cardCorrespond = new Array(
    " ","9♥","6♦","10♠","K♥","7♥","K♣","Q♣","9♦","Q♠","J♦","J♣","7♦","J♠","9♣","10♣","6♥","Q♥","10♥",
    "6♠","8♠","8♣","Q♦","7♣","J♥","A♣","10♦","7♠","A♥","A♠","K♠","A♦","8♥","8♦","K♦","9♠","6♣"
    );

var imageArray = new Array(
    " ","01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png","12.png","13.png",
    "14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png","22.png","23.png","24.png","25.png","26.png",
    "27.png","28.png","29.png","30.png","31.png","32.png","33.png","34.png","35.png","36.png"
    );

And once mainPostBot has the tweet fully constructed, it's delivered to sendTweet:

function sendTweet(text, images, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: images }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the images.");
            console.log(err);
        } else {
            console.log('Images uploaded!');
            console.log("Now tweeting...")

            T.post('statuses/update', {
                status: text,
                media_ids: new Array(data.media_id_string)
            }, function(err, data, response){
                if (err) {
                    console.log("An error has occurred during posting.");
                    console.log(err);
                } else {
                    console.log("Post successful!");
                    console.log("The tweet says:" + text);
                    console.log("The next tweet will send in " + msToTime(time) + "!");
                }
            });
        }
    });
}

Any ideas? I'm open to using other npm packages, for sure, but I just can't figure out why this doesn't work as it is. Thanks for reading, and let me know if you need any other bits of the code.

EDIT 1: My roommate who also dabbles in this sort of stuff found a potentially useful link on github for another package, node-twitter. In that link, a poster explains that the images should be delivered as a string, separated by commas, so I added some edits to mainPostBot and sendTweet, mostly in the passing of b64 image data.

EDIT 2: Those edits are now reflected in the code above, as well as some other fixes I've made to the project as a whole. I got to a point where things are running smoothly again (found a missing bracket, I suck at this coding stuff), and there's tweets posting successfully, but just as before I'm not getting the second image through. Roommate who helped earlier is suggesting to just pump out static single images for every possible card combination but there's gotta be a more elegant solution. Again, any ideas could save a week of my weird bedroom tinkering, and I appreciate any eyes on this.

Body:
It took a lot of tinkering, but I figured it out. Each image has to be uploaded to twitter individually, so after loading the image, I save it's data.media_id_string to a variable, and then load those values into the tweet in an array.

I've removed the line from mainPostBot where I combined b64contentLeft and b64contentRight and added it into the sendTweet code, using the returned data strings. Now, I call sendTweet() with:

sendTweet(tweetText, b64contentLeft, b64contentRight, tweetTime);

And sendTweet() is now looking like this:

function sendTweet(text, leftimage, rightimage, time){

    console.log('Uploading the images...');

    T.post('media/upload', { media_data: leftimage }, function (err, data, response){
        if (err){
            console.log("There's an issue uploading the left image.");
            console.log(err);
        } else {
            console.log('Left image uploaded!');
            var leftID = data.media_id_string;

            T.post('media/upload', { media_data: rightimage }, function (err, data, response){
                if (err){
                    console.log("There's an issue uploading the right image.");
                    console.log(err);
                } else {
                    console.log('Right image uploaded!');
                    var rightID = data.media_id_string;
                    var bothImages = ( leftID + "," + rightID );

                    console.log("Now tweeting...")

                    T.post('statuses/update', {
                        status: text,
                        media_ids: new Array(bothImages)
                    }, function(err, data, response){
                        if (err) {
                            console.log("An error has occurred during posting.");
                            console.log(err);
                        } else {
                            console.log("Post successful!");
                            console.log("The tweet says: " + text);
                            console.log("The next tweet will send in " + msToTime(time) + "!");
                        }
                    });
                }
            });
        }
    });
}

Essentially, if the left image uploads correctly, it'll save that ID, then try for the right image. IF that's successful, it'll save that ID as well, then combine the two into a string separated with a comma, which is loaded into the media_ids array as bothImages.

This was kind of a nightmare to solve, but I wanted to make sure it's documented in case anyone else stumbles here looking for the same answer.


问:
excel find row based on current day
Hello I am new to excel macros

I am trying to create a simple macro which based on the current day (as I am asking this question today is Friday), find "Friday" in any row and then copy all these rows to a new sheet, I have reached this point, Any help is appreciated.

```<code>With ActiveSheet
With Range(“A1”, Range(“A” & Rows.Count).End(xlUp))
.AutoFilter 1, “Friday”
On Error Resume Next
End With
End With
</code>```

答:
You can use below logic to work this out. You need to write appropriate logic to copy the data as per your needs in the commented line.</p>

```<code>Dim lngLastRow As Long, lngLastCol As Long, i As Long, j As Long
With ActiveSheet
    lngLastRow = .Cells.Find("*", .Range("A1"), , , xlByRows, xlPrevious).Row
    lngLastCol = .Cells.Find("*", .Range("A1"), , , xlByColumns, xlPrevious).Column
    For i = 1 To lngLastRow
        For j = 1 To lngLastCol
            If .Cells(i, j).Value = Format(Now, "dddd") Then
                '\\ Write Cell / Row Copying Code Here
                Exit For
            End If
        Next j
    Next i
End With
</code>```

Title: excel find row based on current day

Body:
Hello I am new to excel macros

I am trying to create a simple macro which based on the current day (as I am asking this question today is Friday), find "Friday" in any row and then copy all these rows to a new sheet, I have reached this point, Any help is appreciated.

With ActiveSheet
With Range(“A1”, Range(“A” & Rows.Count).End(xlUp))
.AutoFilter 1, “Friday”
On Error Resume Next
End With
End With

Body:
You can use below logic to work this out. You need to write appropriate logic to copy the data as per your needs in the commented line.

Dim lngLastRow As Long, lngLastCol As Long, i As Long, j As Long
With ActiveSheet
    lngLastRow = .Cells.Find("*", .Range("A1"), , , xlByRows, xlPrevious).Row
    lngLastCol = .Cells.Find("*", .Range("A1"), , , xlByColumns, xlPrevious).Column
    For i = 1 To lngLastRow
        For j = 1 To lngLastCol
            If .Cells(i, j).Value = Format(Now, "dddd") Then
                '\\ Write Cell / Row Copying Code Here
                Exit For
            End If
        Next j
    Next i
End With


问:
How to host a .NET Core 3.1 API web application as windows service?
I have an existing .NET Core 3.1 API web application which I'd like to host as a windows service.
What is the best way to achieve this?

I've found several tutorials stating that adding the nuget package Microsoft.Extensions.Hosting.WindowsServices and using the UseWindowsService() function should be enough to host it as windows service.
This doesn't work for me. I'll get Error 1053: The service did not respond to the start or control request in a timely fashion.

I've also read about worker services but I have no idea how this would work with an existing API project.

My Program.cs looks like this:

```<code> public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .Build();

            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls(config.GetSection("Hosting:Url").Value);
                    webBuilder.UseStartup<Startup>();
                }).UseWindowsService();
        }
    }
</code>```

答:
I think that by downloading the Microsoft.Extensions.Hosting.WindowsServices package, and then adding UseWindowsService() at the end of CreateHostBuilder in Program.cs, then publishing will be the easiest way. (It should be your current plan.)

I'll get Error 1053: The service did not respond to the start or
  control request in a timely fashion.

As for the error you are currently encountering, please refer to this document to resolve.

You can publish your application completely by reading this article and turn it into a windows service.(By reading this article, I successfully fulfilled your needs.)

There are two points to note.

When executing the cmd command, you need to right-click and select Run as Administrator, and then execute the sc command.

The executed command statement binPath and "=" can not have spaces, but the "=" and quotation marks must be separated, here is an example :

```<code>C:\WINDOWS\system32>sc create MyService binPath= "C:\Projects\WindowsServiceDemo\bin\Release\netcoreapp3.1\win-x64\WindowsServiceDemo.exe"
</code>```

Body:
I have an existing .NET Core 3.1 API web application which I'd like to host as a windows service.
What is the best way to achieve this?

I've found several tutorials stating that adding the nuget package Microsoft.Extensions.Hosting.WindowsServices and using the UseWindowsService() function should be enough to host it as windows service.
This doesn't work for me. I'll get Error 1053: The service did not respond to the start or control request in a timely fashion.

I've also read about worker services but I have no idea how this would work with an existing API project.

My Program.cs looks like this:

 public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .Build();

            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseUrls(config.GetSection("Hosting:Url").Value);
                    webBuilder.UseStartup<Startup>();
                }).UseWindowsService();
        }
    }

Body:
I think that by downloading the Microsoft.Extensions.Hosting.WindowsServices package, and then adding UseWindowsService() at the end of CreateHostBuilder in Program.cs, then publishing will be the easiest way. (It should be your current plan.)

I'll get Error 1053: The service did not respond to the start or
  control request in a timely fashion.

As for the error you are currently encountering, please refer to this document to resolve.

You can publish your application completely by reading this article and turn it into a windows service.(By reading this article, I successfully fulfilled your needs.)

There are two points to note.

When executing the cmd command, you need to right-click and select Run as Administrator, and then execute the sc command.

The executed command statement binPath and "=" can not have spaces, but the "=" and quotation marks must be separated, here is an example :

C:\WINDOWS\system32>sc create MyService binPath= "C:\Projects\WindowsServiceDemo\bin\Release\netcoreapp3.1\win-x64\WindowsServiceDemo.exe"


问:
Angular Material 5: how to call a function when a tab is selected (clicked)?
I have the following html code

```<code><mat-tab label="Regular" (selectChange)="tabClick()"
                 (click)="tabClick()">
   <h1>Some more tab content</h1>
</mat-tab>
</code>```

and this is the function,

```<code>tabClick(){
    console.log('Tab clicked...');
}
</code>```

but it doesn't seems to be called, why? No one of the above events are fired?

答:
```<code><mat-tab-group (selectedTabChange)="onChange($event)">
    <mat-tab label="Tab 1">Content 1</mat-tab>
    <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>
</code>```

Selected tab will trigger out the tabChange Event and get the active tab.

And in the .ts file:

```<code>onChange(event: MatTabChangeEvent) {
    const tab = event.tab.textLabel;
    console.log(tab);
    if(tab===" Tab 1")
     {
       console.log("function want to implement");
      }
  }
</code>```

Body:
I have the following html code

<mat-tab label="Regular" (selectChange)="tabClick()"
                 (click)="tabClick()">

Some more tab content

</mat-tab>

and this is the function,

tabClick(){
    console.log('Tab clicked...');
}

but it doesn't seems to be called, why? No one of the above events are fired?

Body:
<mat-tab-group (selectedTabChange)="onChange($event)">
    <mat-tab label="Tab 1">Content 1</mat-tab>
    <mat-tab label="Tab 2">Content 2</mat-tab>
</mat-tab-group>

Selected tab will trigger out the tabChange Event and get the active tab.

And in the .ts file:

onChange(event: MatTabChangeEvent) {
    const tab = event.tab.textLabel;
    console.log(tab);
    if(tab===" Tab 1")
     {
       console.log("function want to implement");
      }
  }


问:
Converting some text within an element to an element itself using JavaScript
Is this possible using JavaScript or JQuery, or anything else?

Say I have an HTML file like this

```<code><div>
    <p>Hello World</p>
</div>
</code>```

And I want to turn "World" into a span element itself, like so (so that I can style just "World")

```<code><div>
    <p>Hello <span>World</span></p>
</div>
</code>```

答:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3

str.replace solves the job.  The comment of @Umer Hassan is correct.

Body:
Is this possible using JavaScript or JQuery, or anything else?

Say I have an HTML file like this

Hello World

And I want to turn "World" into a span element itself, like so (so that I can style just "World")

Hello World


问:
IIS return 404 error, suspect problem is with RouteConfig
Locally my solution is working fine, but after deploying the published to the server, it returns 404 error on all my ASPX pages despite the resources are all there. My solution is .NET Framework Web Forms based and I have this RouteConfig.cs file in my App_Start folder. I haven't configured anything in this section yet.

```<code>public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}
</code>```

I can't find IIS log files as it's not self managed, might need to take some time on that.

答: The server only support .NET Framework till version 4.61 instead of targeted 4.8 in my projects.</p>

Body:
Locally my solution is working fine, but after deploying the published to the server, it returns 404 error on all my ASPX pages despite the resources are all there. My solution is .NET Framework Web Forms based and I have this RouteConfig.cs file in my App_Start folder. I haven't configured anything in this section yet.

public static class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }
}

I can't find IIS log files as it's not self managed, might need to take some time on that.


问:
is there a function to convert sha-1 into sha256
is there a way to convert sha-1 to sha256 for a file. suppose SHA-1 of a files is a14bab81de06e9b590f6cfcd400f90fb5b667eff

Func(a14bab81de06e9b590f6cfcd400f90fb5b667eff) = SHA-256

Here I don't have the original file, else Get-FileHash in powershell would have solved my problem. Thank you.

答: No, that's not possible. SHA algorithms need to see all the data in the original files.</p>


问:
Stored procedure hangs on statement.execute()
Why would a Snowflake stored procedure hang on a statement that, when executed outside the stored procedure, works? Further info: I remove that statement from the stored procedure, then the SP also runs properly. How can this sort of thing be debugged?

(One more piece of info: running as a different user on a different schema, the SP works as intended.)

Update: running the SP on a different warehouse worked, so it might be a problem with the warehouse, not the schema.

答:
Why would a Snowflake stored procedure hang on a statement that, when executed outside the stored procedure, works?

There can be multiple reasons: Query gets queued due to lack of resources, is awaiting a lock to free (if its a transactional query), etc.

How can this sort of thing be debugged?

Check the Query History UI page on Snowflake. If your procedure-executed statement is showing a queued status, you're likely running into a warehouse size limit or a maximum concurrency limit, which can be resolved by reconfiguring your warehouse (via auto-scaling and/or using higher warehouse sizes).


问:
Regular expression syntax
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

```<code>Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30
</code>```

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

```<code>Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....
</code>```

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

答:
I'm not totally sure I understand your problem, but I'll give this a shot. It looks like you want:

```<code>/(^T\d+$(^X[-A-Z\d]+$)+)*/g
</code>```

This will have to be run under multiline mode so that ^ and $ match after and before newlines. Word of caution: I don't have much practice with mulitline regex, so you might want to do a sanity check on the use of ^ and $.

Also, I notice you didn't include the lines similar to T01C0.025 in your sample results, so I made the T\d+ assumption based on that.

Title: Regular expression syntax

Body:
I have a similar problem, to a previously asked question. But similar practices apparently do not produce similar results.

Previous Question

New question - I want to match the lines beginning in T as the first match, and the following lines beginning with X as the second match (as a whole string, to be later matched by another regex)

What I have so far is (^T(\d+)\n(.*?)(?:the_problem)/m) I don't know what to replace "the_problem" with, or even if that is the issue. I assumed some rendition (?:\n|\z), but apparently not. Everything I tried, would not count the next occurrence of ^T(\d+) as the start of a new group, and continue to capture all of the lines between each occurrence, at the same time.

Sample text;
T01C0.025
T02C0.035
T03C0.055
T04C0.150
T05C0.065
T06C0.075
%
G05
G90
T01
X011200Y004700
X011200Y009700
X018500Y011200
X013500Y-011200
X023800Y019500
T02
X034800Y017800
X-033800Y-017800
X032800Y017800
T03
X036730Y003000
X038700Y003000
X040668Y-003000
X059230Y003000
T04
X110580Y017800
X023800Y027300
X095500Y028500
X005500Y-006500
X021500Y-006500
T05
X003950Y002000
X003950Y004500
X003950Y007000
T06
X026300Y027300
M30

I only want to capture the shorter version of T01, T02,...T0n, not the longer version at the top, then the entire collection of ^X(-?\d+)Y(-?\d+) that follows it, as another match.

Result 1.
Match 1. T01
Match 2. X011200Y004700
         X011200Y009700
         X018500Y011200
         X013500Y-011200
         X023800Y019500

Result 2.
Match 1. T02
Match 2. X034800Y017800
         X-033800Y-017800
         X032800Y017800

Result 3.
Match 1. T03
Match 2. X036730Y003000
         X038700Y003000

         ....etc....

Thanks in advance for any help ;-) Note: I prefer to use raw Ruby, without extensions or plugins. My version of ruby is 1.8.6.

Body:
I'm not totally sure I understand your problem, but I'll give this a shot. It looks like you want:

/(^T\d+$(^X[-A-Z\d]+$)+)*/g

This will have to be run under multiline mode so that ^ and $ match after and before newlines. Word of caution: I don't have much practice with mulitline regex, so you might want to do a sanity check on the use of ^ and $.

Also, I notice you didn't include the lines similar to T01C0.025 in your sample results, so I made the T\d+ assumption based on that.


问:
Counting word frequency and making a dictionary from it
I want to take every word from a text file, and count the word frequency in a dictionary.

Example: 'this is the textfile, and it is used to take words and count'

```<code>d = {'this': 1, 'is': 2, 'the': 1, ...}
</code>```

I am not that far, but I just can't see how to complete it. My code so far:

```<code>import sys

argv = sys.argv[1]
data = open(argv)
words = data.read()
data.close()
wordfreq = {}
for i in words:
    #there should be a counter and somehow it must fill the dict.
</code>```

答:
```<code>wordList = 'this is the textfile, and it is used to take words and count'.split()
wordFreq = {}

# Logic: word not in the dict, give it a value of 1. if key already present, +1.
for word in wordList:
    if word not in wordFreq:
        wordFreq[word] = 1
    else:
        wordFreq[word] += 1

print(wordFreq)
</code>```

Body:
I want to take every word from a text file, and count the word frequency in a dictionary.

Example: 'this is the textfile, and it is used to take words and count'

d = {'this': 1, 'is': 2, 'the': 1, ...}

I am not that far, but I just can't see how to complete it. My code so far:

import sys

argv = sys.argv[1]
data = open(argv)
words = data.read()
data.close()
wordfreq = {}
for i in words:
    #there should be a counter and somehow it must fill the dict.


问:
clearInterval()-Method in JavaScript - How does it exactly work?
I have a script which waits for specific DOM-Elements to be loaded and when loaded it appends another HTML-Element:

```<code>var checkExistVOID = setInterval(function() {
   if( $('#voidDocumentsAwaitingMyApproval').length && $('#voidDocumentsAwaitingMySignature').length ) {
    $("#loadingBarPolarion1").hide();
    $('<span style="font-size: 14px;"><i style="color: lightgreen; padding-right: 10px;" class="fas fa-check"></i>Currently no Document Actions required</span>').appendTo('#voidDocumentsAwaitingMyApproval');
    clearInterval(checkExistVOID);
 }
}, 500);
</code>```

My aim was to only trigger this function once, that's why I used the Method:

```<code>clearInterval()
</code>```

It seems to work fine at first glance, but if the site where the page is executed stays opened for about ~30 minutes without any user action, the append-function is all of a sudden executed every 500 ms on a loop:

I was wondering, what can be the issue of this? Is it possible that clearInterval() suddenly isn't "stored anymore"?

Can you suggest me what to change in my function in order to not run into this problem?

I was thinking about an additional check for the already exiting -ELement and use that in the if-Function, but I guess that's not a professional solution :)

答:
You're conditionally clearing the interval. If the condition is not met, the interval will not be cleared.

My aim was to only trigger this function once

You should use setTimeout() instead.

Body:
I have a script which waits for specific DOM-Elements to be loaded and when loaded it appends another HTML-Element:

var checkExistVOID = setInterval(function() {
   if( $('#voidDocumentsAwaitingMyApproval').length && $('#voidDocumentsAwaitingMySignature').length ) {
    $("#loadingBarPolarion1").hide();
    $('Currently no Document Actions required').appendTo('#voidDocumentsAwaitingMyApproval');
    clearInterval(checkExistVOID);
 }
}, 500);

My aim was to only trigger this function once, that's why I used the Method:

clearInterval()

It seems to work fine at first glance, but if the site where the page is executed stays opened for about ~30 minutes without any user action, the append-function is all of a sudden executed every 500 ms on a loop:

I was wondering, what can be the issue of this? Is it possible that clearInterval() suddenly isn't "stored anymore"?

Can you suggest me what to change in my function in order to not run into this problem?

I was thinking about an additional check for the already exiting -ELement and use that in the if-Function, but I guess that's not a professional solution :)


问:
Azure Functions Database Connection String
How do I add or access an app.config file in Azure functions to add a database connection string?

If you're not supposed to add an app.config and there is a better way to access an external database to execute the function please let me know best practices.  Thanks!

答:
The Best way to handle connection strings is by using "Azure Key Vault". You can store all the important secrets in Key Vault and consume in the Application.
As suggested by other members you can use Application Settings.

help full links: https://learn.microsoft.com/en-us/azure-stack/user/azure-stack-key-vault-manage-portal?view=azs-2002

https://learn.microsoft.com/en-us/aspnet/core/security/key-vault-configuration?view=aspnetcore-3.1


问:
Python : Call list attribute from a list of defined attributes
I have a list with list operations, For example ["insert", "append"], For now I am doing like if list says insert then I am calling .insert.

Check below code

In [31]: list_ops = [ "insert" , "append" ]

In [32]: list1 = [ 1 , 3 , 5 ]

In [33]: if list_ops[0] == "insert" :
    ...:     list1.insert(3, 7)
    ...:

In [34]: list1
Out[34]: [1, 3, 5, 7]

In [35]: list1.list_ops[0](4, 9 )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-5db0dcceeac1> in <module>
----> 1 list1.list_ops[0](4, 9 )

AttributeError: 'list' object has no attribute 'list_ops'

In [36]:
```

How can I choose the operation from list_ops itself instead of doing if-else matching.

Thank you.

答:
You could use exec and f-Strings if you really wanted to do it:

operation = "append"
list1 = [1, 2, 3]

exec(f"list1.{operation}(4)")
print(list1) # [1, 2, 3, 4]
```

But to be honest, I think it's a better idea to create an operation dictionary like Prune suggested.

Body:
I have a list with list operations, For example ["insert", "append"], For now I am doing like if list says insert then I am calling .insert.

Check below code

In [31]: list_ops = [ "insert" , "append" ]

In [32]: list1 = [ 1 , 3 , 5 ]

In [33]: if list_ops[0] == "insert" :
    ...:     list1.insert(3, 7)
    ...:

In [34]: list1
Out[34]: [1, 3, 5, 7]

In [35]: list1.list_ops[0](4, 9 )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-5db0dcceeac1> in <module>
----> 1 list1.list_ops[0](4, 9 )

AttributeError: 'list' object has no attribute 'list_ops'

In [36]:

How can I choose the operation from list_ops itself instead of doing if-else matching.

Thank you.

Body:
You could use exec and f-Strings if you really wanted to do it:

operation = "append"
list1 = [1, 2, 3]

exec(f"list1.{operation}(4)")
print(list1) # [1, 2, 3, 4]

But to be honest, I think it's a better idea to create an operation dictionary like Prune suggested.


问:
CSS alignment: flexbox/ tailwind alignment issues
Currently I'm using tailwind to align data in react, I've tried adding flexbox but it appears im off with a few things

This is my expected outcome:

I would love if someone can explain what im doing wrong as well.

Current outcome:

My last attempt was this:

```<code>import React from "react";
import ReactDOM from "react-dom";

const SummaryPerPlatform = () => {
  return (
    <div>
      <div className="max-w-md overflow-hidden bg-white m-4">
        <div className="flex flex-col min-h-full">
          <div className="flex flex-col flex-grow">
            <div className="px-6 py-3 border-b">
              <div className="text-xl font-bold"> Twitter </div>
            </div>
            <div className="px-6 py-3 border-b">
              <span className="">Avg. sentigment(0.0 -1.0)</span>
              <span className="">0.31</span>
            </div>
            <div className="px-6 py-3 border-b">
              <div className="text-xl font-bold"> Instagram </div>
              <span className="">Post analyzed</span>
              <span className="">5,670</span>
            </div>
            <div className="px-6 py-3 border-b">
              <div className="text-xl font-bold"> LinkedIn </div>
              <span className="">Positive posts (>0.66)</span>
              <span className="">1,849</span>
            </div>
            <div className="px-6 py-3 border-b">
              <span className="">Negative posts (0.33)</span>
              <span className="">1,981</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
export default SummaryPerPlatform;

const rootElement = document.getElementById("root");
ReactDOM.render(<SummaryPerPlatform />, rootElement);
</code>```

Any help is very much appreciated.

答:
You should use flex-row instead of flex-col for whole container. Otherwise I would suggest for using an extra div for differentiating these sections and using Grid to arrange these div in a similar width.

You can try like this:

```<code>// ...
return (
    <div>
        <div className="max-w-md overflow-hidden bg-white m-4">
            <div className="grid grid-cols-4 gap-1">
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> Twitter </div>
                    </div>
                    <div className="px-6 py-3 border-b">
                        <span className="">Avg. sentigment(0.0 -1.0)</span>
                        <span className="">0.31</span>
                    </div>
                </div>
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> Instagram </div>
                        <span className="">Post analyzed</span>
                        <span className="">5,670</span>
                    </div>
                </div>
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> LinkedIn </div>
                        <span className="">Positive posts (>0.66)</span>
                        <span className="">1,849</span>
                    </div>
                    <div className="px-6 py-3 border-b">
                        <span className="">Negative posts (0.33)</span>
                        <span className="">1,981</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
)
// ...
</code>```

Body:
Currently I'm using tailwind to align data in react, I've tried adding flexbox but it appears im off with a few things

This is my expected outcome:

I would love if someone can explain what im doing wrong as well.

Current outcome:

My last attempt was this:

import React from "react";
import ReactDOM from "react-dom";

const SummaryPerPlatform = () => {
  return (

 Twitter

              Avg. sentigment(0.0 -1.0)
              0.31

 Instagram

              Post analyzed
              5,670

 LinkedIn

              Positive posts (>0.66)
              1,849

              Negative posts (0.33)
              1,981

  );
};
export default SummaryPerPlatform;

const rootElement = document.getElementById("root");
ReactDOM.render(<SummaryPerPlatform />, rootElement);

Any help is very much appreciated.

Body:
You should use flex-row instead of flex-col for whole container. Otherwise I would suggest for using an extra div for differentiating these sections and using Grid to arrange these div in a similar width.

You can try like this:

// ...
return (
    <div>
        <div className="max-w-md overflow-hidden bg-white m-4">
            <div className="grid grid-cols-4 gap-1">
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> Twitter </div>
                    </div>
                    <div className="px-6 py-3 border-b">
                        <span className="">Avg. sentigment(0.0 -1.0)</span>
                        <span className="">0.31</span>
                    </div>
                </div>
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> Instagram </div>
                        <span className="">Post analyzed</span>
                        <span className="">5,670</span>
                    </div>
                </div>
                <div>
                    <div className="px-6 py-3 border-b">
                        <div className="text-xl font-bold"> LinkedIn </div>
                        <span className="">Positive posts (>0.66)</span>
                        <span className="">1,849</span>
                    </div>
                    <div className="px-6 py-3 border-b">
                        <span className="">Negative posts (0.33)</span>
                        <span className="">1,981</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
)
// ...


问:
Reactjs render component without importing the navbar and style
I am using react-dom-router to routes between my app components ,
I want to create a component (SeperatePageCompoenet) that when user navigate to the URL (http://localhost:3000/seperatePage), the compoenet will be rendered without using the imported "App.css" file, and does not include the  compoenet that is rendered in App.js component.

This is my index.js compoenet:-

```<code>import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap-v4-rtl/dist/css/bootstrap-rtl.css";
import "bootstrap-v4-rtl/dist/js/bootstrap.js";
import "./App.css";
import { BrowserRouter } from "react-router-dom";
//import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);
</code>```

App.js File:-

```<code>import React from "react";
import Header from "./components/Header";
import Home from "./pages/Home";
import About from "./pages/About";
import Login from "./pages/Login";
import Account from "./pages/Account";
import Contact from "./pages/Contact";
import NewPost from "./pages/NewPost";
import Test from "./pages/Test";
import { Switch, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import Signup from "./pages/Signup";
import Post from "./pages/Post";

function App() {
  return (
    <div>
      <Header />
      <NavBar />
      <div className="container rtl">
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/create-new" component={NewPost} />
          <Route path="/contact-us" component={Contact} />
          <Route path="/login" component={Login} />
          <Route path="/signup" component={Signup} />
          <Route path="/account" component={Account} />
          <Route path="/post/:id" component={Post} />
          <Route path="/test" component={Test} />
        </Switch>
      </div>
    </div>
  );
}
export default App;
</code>```

The purpose of this, i want to view a text with full view page, without using the background-color that has been set in App.css file, and without including the navbar in the page.

答:
You can wrap it in a higher-order-component. See How to hide navbar in login page in react router or How to hide Nav bar in some react components

Since your css is available for all or your app, I suggest to simply overwrite the style for your SeperatePageComponent

Body:
I am using react-dom-router to routes between my app components ,
I want to create a component (SeperatePageCompoenet) that when user navigate to the URL (http://localhost:3000/seperatePage), the compoenet will be rendered without using the imported "App.css" file, and does not include the  compoenet that is rendered in App.js component.

This is my index.js compoenet:-

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import "bootstrap-v4-rtl/dist/css/bootstrap-rtl.css";
import "bootstrap-v4-rtl/dist/js/bootstrap.js";
import "./App.css";
import { BrowserRouter } from "react-router-dom";
//import * as serviceWorker from './serviceWorker';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

App.js File:-

import React from "react";
import Header from "./components/Header";
import Home from "./pages/Home";
import About from "./pages/About";
import Login from "./pages/Login";
import Account from "./pages/Account";
import Contact from "./pages/Contact";
import NewPost from "./pages/NewPost";
import Test from "./pages/Test";
import { Switch, Route } from "react-router-dom";
import NavBar from "./components/NavBar";
import Signup from "./pages/Signup";
import Post from "./pages/Post";

function App() {
  return (

      <NavBar />

        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/create-new" component={NewPost} />
          <Route path="/contact-us" component={Contact} />
          <Route path="/login" component={Login} />
          <Route path="/signup" component={Signup} />
          <Route path="/account" component={Account} />
          <Route path="/post/:id" component={Post} />
          <Route path="/test" component={Test} />
        </Switch>

  );
}
export default App;

The purpose of this, i want to view a text with full view page, without using the background-color that has been set in App.css file, and without including the navbar in the page.


问:
Counting SFTP files matching certain criteria using SSH.NET
I have a working program that deletes log files from a remote server (based on a certain pattern). Now when I want to get the count of files that match my criteria I am getting problems. It turns I cannot directly get the count from the SftpFile file object. I can only get the count of the files after setting a breakpoint.

I am able to delete the files using :

```<code>private void ListDirectory(SftpClient client, String dirName)
{
    var fileext = ".log";
    var fileextension = fileext.ToString();

    foreach (SftpFile file in client.ListDirectory(dirName))
    {
        var logFilePath = file.FullName;
        var fileCount = client.ListDirectory(dirName).GetEnumerator();

        if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
        {
            Console.WriteLine(file.FullName);
            client.Delete(logFilePath);
            Console.ReadKey();
        }
    }
}
</code>```

And when I do set a breakpoint I can get the count from a nested object of this line:

```<code>var fileCount = client.ListDirectory(dirName).GetEnumerator();
</code>```

I have a snapshot of the debug:

Now I need a way to directly access the count of files for my pattern i.e this line:

```<code>if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
</code>```

When I  try to apply some Linq as below:

```<code> var fileCount = client.ListDirectory(dirName).Where((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension)).Count();
</code>```

I get further exception saying

Cannot convert from 'bool' to 'system.func

答:
The syntax you have in Where method argument is not a valid lambda function, you miss the parameter list. It should be:

```<code>.Where(file => (file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
</code>```

Also, do not call ListDirectory repeatedly, let alone in every iteration.

```<code>var files = client.ListDirectory(dirName);
files =
    files.Where(
        file => (file.Name != ".") && (file.Name != "..") &&
        file.Name.EndsWith(fileextension));

int count = files.Count();
foreach (SftpFile file in files)
{
    // ...
}
</code>```

Body:
I have a working program that deletes log files from a remote server (based on a certain pattern). Now when I want to get the count of files that match my criteria I am getting problems. It turns I cannot directly get the count from the SftpFile file object. I can only get the count of the files after setting a breakpoint.

I am able to delete the files using :

private void ListDirectory(SftpClient client, String dirName)
{
    var fileext = ".log";
    var fileextension = fileext.ToString();

    foreach (SftpFile file in client.ListDirectory(dirName))
    {
        var logFilePath = file.FullName;
        var fileCount = client.ListDirectory(dirName).GetEnumerator();

        if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))
        {
            Console.WriteLine(file.FullName);
            client.Delete(logFilePath);
            Console.ReadKey();
        }
    }
}

And when I do set a breakpoint I can get the count from a nested object of this line:

var fileCount = client.ListDirectory(dirName).GetEnumerator();

I have a snapshot of the debug:

Now I need a way to directly access the count of files for my pattern i.e this line:

if ((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))

When I  try to apply some Linq as below:

 var fileCount = client.ListDirectory(dirName).Where((file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension)).Count();

I get further exception saying

Cannot convert from 'bool' to 'system.func

Body:
The syntax you have in Where method argument is not a valid lambda function, you miss the parameter list. It should be:

.Where(file => (file.Name != ".") && (file.Name != "..") && file.Name.EndsWith(fileextension))

Also, do not call ListDirectory repeatedly, let alone in every iteration.

var files = client.ListDirectory(dirName);
files =
    files.Where(
        file => (file.Name != ".") && (file.Name != "..") &&
        file.Name.EndsWith(fileextension));

int count = files.Count();
foreach (SftpFile file in files)
{
    // ...
}