问:
Struggling to manually create relations with gorm / migrate
I have an sql structure like so:

CREATE TABLE resources (
  id SERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL,
  deleted_at TIMESTAMPTZ
);

CREATE TABLE tags (
    name TEXT PRIMARY KEY
);
```

<p>What sql do I need to write, how can I tell <code>gorm</code> that I want a <code>Resource</code> to have many <code>Tag</code>s? This is what I have currently go-wise:</p>

<pre class="lang-golang prettyprint-override"><code>package models

import (
    "github.com/jinzhu/gorm"
)

type Tag struct {
    Name string `gorm:"PRIMARY_KEY"`
}

type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:""`
}
</code>```

Note that I explicitly do not want to auto-migrate via gorm. I am using the migrate tool to handle migrations and want to specifically handle them manually, not with go.

答:
To define a has many relationship, a foreign key must exist.

So for your case Tag should be:

```<code>type Tag struct {
    gorm.Model
    Name string `gorm:"PRIMARY_KEY"`
    ResourceID int
}
</code>```

and Resource:

```<code>type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:"foreignkey:ResourceID"`
}
</code>```

And your sql structure should have that foreign key ResourceID column.

Not sure if you have already checked this but it contains more details in case you need them: https://gorm.io/docs/has_many.html#Foreign-Key

Body:
I have an sql structure like so:

CREATE TABLE resources (
  id SERIAL PRIMARY KEY,
  title TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL,
  deleted_at TIMESTAMPTZ
);

CREATE TABLE tags (
    name TEXT PRIMARY KEY
);

What sql do I need to write, how can I tell gorm that I want a Resource to have many Tags? This is what I have currently go-wise:

package models

import (
    "github.com/jinzhu/gorm"
)

type Tag struct {
    Name string `gorm:"PRIMARY_KEY"`
}

type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:""`
}

Note that I explicitly do not want to auto-migrate via gorm. I am using the migrate tool to handle migrations and want to specifically handle them manually, not with go.

Body:
To define a has many relationship, a foreign key must exist.

So for your case Tag should be:

type Tag struct {
    gorm.Model
    Name string `gorm:"PRIMARY_KEY"`
    ResourceID int
}

and Resource:

type Resource struct {
    gorm.Model
    Title       string
    Tags        []Tag        `gorm:"foreignkey:ResourceID"`
}

And your sql structure should have that foreign key ResourceID column.

Not sure if you have already checked this but it contains more details in case you need them: https://gorm.io/docs/has_many.html#Foreign-Key


来源: stackexchange

问:
Defining the same Spring bean twice with same name
Is having two definition for a bean (with same name and class) valid in Spring IOC ?

I am having two bean definition files included in web.xml. See the sample below.

applicationContext-beans1.xml

<bean name="myWao"
    class="com.beans.myBean">
</bean>
```

<p><strong>applicationContext-beans2.xml</strong></p>

<pre class="lang-xml prettyprint-override"><code><bean name="myWao"
    class="com.beans.myBean">
</bean>
</code>```

I am not facing any issue till now. But, will this possibly impact in the real environment which will be multi threaded and clustered ?

Note: Both the XMLs are loaded as I am able to use the other beans defined(only once) in both the XMLs

答:
From Spring Boot version 2.1 it is disabled by default. (link)

Bean Overriding: Bean overriding has been disabled by default to
  prevent a bean being accidentally overridden. If you are relying on
  overriding, you will need to set
  spring.main.allow-bean-definition-overriding to true.

ContentLicense: CC BY-SA 3.0

Body:
Is having two definition for a bean (with same name and class) valid in Spring IOC ?

I am having two bean definition files included in web.xml. See the sample below.

applicationContext-beans1.xml

<bean name="myWao"
    class="com.beans.myBean">
</bean>

applicationContext-beans2.xml

<bean name="myWao"
    class="com.beans.myBean">
</bean>

I am not facing any issue till now. But, will this possibly impact in the real environment which will be multi threaded and clustered ?

Note: Both the XMLs are loaded as I am able to use the other beans defined(only once) in both the XMLs

ContentLicense: CC BY-SA 4.0


问:
php, how to run a link when check box checked?
```<code><input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';
</code>```

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

```<code>if ($('#checket:checked').val() !== undefined) {
</code>```

// Insert code here.
}

答:
Without using a JS library like jquery or mootools, here's how to do it in barebones JS:

```<code><input
    type="checkbox"
    value="<?php echo htmlspecialchars($url) ?>"
    name="checket"
    onClick="if (this.checked) { window.location = this.value; }"
/>
</code>```

Note that I've split the tag across multiple lines so it's easier to read. basically, embed the desired url into the checkbox's value field, then put an onclick handler that'll read out that URL and feed it to window.location when the checkbox becomes checked.

Body:
<input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

if ($('#checket:checked').val() !== undefined) {

// Insert code here.
}

Body:
Without using a JS library like jquery or mootools, here's how to do it in barebones JS:

<input
    type="checkbox"
    value="<?php echo htmlspecialchars($url) ?>"
    name="checket"
    onClick="if (this.checked) { window.location = this.value; }"
/>

Note that I've split the tag across multiple lines so it's easier to read. basically, embed the desired url into the checkbox's value field, then put an onclick handler that'll read out that URL and feed it to window.location when the checkbox becomes checked.


问:
Kotlin Exposed Sum on condition (CaseWhenElse)
I have a table with data structure like :

```<code>id    type   cityName   regDate
1249     0   City1      2019-10-01
</code>```

I want to get result output of unique cities and the number of registrations in it per month as a list of data class objects of

```<code>data class NewClientsNumberCityMonth(
    val cityName: String = "",
    val januaryNewClientsNumber :Int = 0,
    val februaryNewClientsNumber :Int = 0,
    val marchNewClientsNumber :Int = 0,
    val aprilNewClientsNumber :Int = 0,
    val mayNewClientsNumber :Int = 0,
    val juneNewClientsNumber :Int = 0,
    val julyNewClientsNumber :Int = 0,
    val augustNewClientsNumber :Int = 0,
    val septemberNewClientsNumber :Int = 0,
    val octoberNewClientsNumber :Int = 0,
    val novemberNewClientsNumber :Int = 0,
    val decemberNewClientsNumber :Int = 0
    val total :Int = 0
)
</code>```

and use this objects as the strings to fill the table (we dont know the number of unique cities),
result should be like :

```<code>City1     5    8    3    1    2    1    4    1    2    1    0    0
City2    69   23    7    5    3   10   24   14   12   23   25   10
...
</code>```

im trying this

```<code>val tempMutList = mutableListOf<NewClientsNumberCityMonthModel>()

transaction(Connection.TRANSACTION_SERIALIZABLE, 2) {
                        addLogger(StdOutSqlLogger)

                        ClientsDataExposed
                            .slice(ClientsDataExposed.cityName)
                            .selectAll()
                            .groupBy(ClientsDataExposed.cityName)
                            .map { it[ClientsDataExposed.cityName] }
                            .toList().forEach {

                              val regsInCity = ClientsDataExposed
                                .slice(
                                        ClientsDataExposed.id,
                                        ClientsDataExposed.cityName,
                                        ClientsDataExposed.type,
                                        ClientsDataExposed.regDate,
                                        ClientsDataExposed.regDate.month()

                                    )
                                    .selectAll()
                                    .andWhere { ClientsDataExposed.cityName.eq(it) }
                                    .andWhere {
                                        ClientsDataExposed.regDate.between(
                                            Date.valueOf("2019-01-01".toString()),
                                            Date.valueOf("2020-01-01".toString())
                                        )
                                    }
                                    .andWhere {
                                        (ClientsDataExposed.type.inList(contracterTypeSelectedCheckboxes.filterValues { it }.keys.toList())) and (ClientsDataExposed.cityName.inList(
                                            citiesSelectedChekboxes.filterValues { it }.keys.toList()
                                        ))
                                    }
                                    .map { it[ClientsDataExposed.regDate.month()] }
                                    .toList()

                        val cityClientsPerMonth = NewClientsNumberCityMonthModel(
                            it,
                            regsInCity.count { it == 1 },
                            regsInCity.count { it == 2 },
                            regsInCity.count { it == 3 },
                            regsInCity.count { it == 4 },
                            regsInCity.count { it == 5 },
                            regsInCity.count { it == 6 },
                            regsInCity.count { it == 7 },
                            regsInCity.count { it == 8 },
                            regsInCity.count { it == 9 },
                            regsInCity.count { it == 10 },
                            regsInCity.count { it == 11 },
                            regsInCity.count { it == 12 },
                            regsInCity.count()
                            )
                               tempMutList.add(cityClientsPerMonth)

                                //obj of dataclass
                            }

               viewTableTabOfnewClientsNumberCityMonth.value = tempMutList.map { it }
}
</code>```

i know, that i should use Sum() and CaseWhenElse , like here , with check on
ClientsDataExposed.regDate.month()
which gives a month number (1-12), to assign the sum() result to my data class property, but i can't find any examples of CaseWhenElse syntax and i can't figure out it myself,
or may be there is another way of getting it whithout using of CaseWhenElse ?

答:
Please check that code:</p>

```<code>    val monthExpr = ClientsDataExposed.regDate.month()

    fun sumByMonth(monthNum: Int) = Expression.build {
        val caseExpr = case().
            When(monthExpr eq intLiteral(monthNum), intLiteral(1)).
            Else(intLiteral(0))
        Sum(caseExpr, IntegerColumnType())
    }

    val janSumExp = sumByMonth(1)
    val febSumExp = sumByMonth(2)
    ClientsDataExposed.
        slice(ClientsDataExposed.cityName, janSumExp, febSumExp).
        selectAll().
        groupBy(ClientsDataExposed.id).map {
          val janSum = it[janSumExp]
          val febSum = it[febSumExp]
          ...
        }
</code>```

Body:
I have a table with data structure like :

id    type   cityName   regDate
1249     0   City1      2019-10-01

I want to get result output of unique cities and the number of registrations in it per month as a list of data class objects of

data class NewClientsNumberCityMonth(
    val cityName: String = "",
    val januaryNewClientsNumber :Int = 0,
    val februaryNewClientsNumber :Int = 0,
    val marchNewClientsNumber :Int = 0,
    val aprilNewClientsNumber :Int = 0,
    val mayNewClientsNumber :Int = 0,
    val juneNewClientsNumber :Int = 0,
    val julyNewClientsNumber :Int = 0,
    val augustNewClientsNumber :Int = 0,
    val septemberNewClientsNumber :Int = 0,
    val octoberNewClientsNumber :Int = 0,
    val novemberNewClientsNumber :Int = 0,
    val decemberNewClientsNumber :Int = 0
    val total :Int = 0
)

and use this objects as the strings to fill the table (we dont know the number of unique cities),
result should be like :

City1     5    8    3    1    2    1    4    1    2    1    0    0
City2    69   23    7    5    3   10   24   14   12   23   25   10
...

im trying this

val tempMutList = mutableListOf<NewClientsNumberCityMonthModel>()

transaction(Connection.TRANSACTION_SERIALIZABLE, 2) {
                        addLogger(StdOutSqlLogger)

                        ClientsDataExposed
                            .slice(ClientsDataExposed.cityName)
                            .selectAll()
                            .groupBy(ClientsDataExposed.cityName)
                            .map { it[ClientsDataExposed.cityName] }
                            .toList().forEach {

                              val regsInCity = ClientsDataExposed
                                .slice(
                                        ClientsDataExposed.id,
                                        ClientsDataExposed.cityName,
                                        ClientsDataExposed.type,
                                        ClientsDataExposed.regDate,
                                        ClientsDataExposed.regDate.month()

                                    )
                                    .selectAll()
                                    .andWhere { ClientsDataExposed.cityName.eq(it) }
                                    .andWhere {
                                        ClientsDataExposed.regDate.between(
                                            Date.valueOf("2019-01-01".toString()),
                                            Date.valueOf("2020-01-01".toString())
                                        )
                                    }
                                    .andWhere {
                                        (ClientsDataExposed.type.inList(contracterTypeSelectedCheckboxes.filterValues { it }.keys.toList())) and (ClientsDataExposed.cityName.inList(
                                            citiesSelectedChekboxes.filterValues { it }.keys.toList()
                                        ))
                                    }
                                    .map { it[ClientsDataExposed.regDate.month()] }
                                    .toList()

                        val cityClientsPerMonth = NewClientsNumberCityMonthModel(
                            it,
                            regsInCity.count { it == 1 },
                            regsInCity.count { it == 2 },
                            regsInCity.count { it == 3 },
                            regsInCity.count { it == 4 },
                            regsInCity.count { it == 5 },
                            regsInCity.count { it == 6 },
                            regsInCity.count { it == 7 },
                            regsInCity.count { it == 8 },
                            regsInCity.count { it == 9 },
                            regsInCity.count { it == 10 },
                            regsInCity.count { it == 11 },
                            regsInCity.count { it == 12 },
                            regsInCity.count()
                            )
                               tempMutList.add(cityClientsPerMonth)

                                //obj of dataclass
                            }

               viewTableTabOfnewClientsNumberCityMonth.value = tempMutList.map { it }
}

i know, that i should use Sum() and CaseWhenElse , like here , with check on
ClientsDataExposed.regDate.month()
which gives a month number (1-12), to assign the sum() result to my data class property, but i can't find any examples of CaseWhenElse syntax and i can't figure out it myself,
or may be there is another way of getting it whithout using of CaseWhenElse ?

Body:
Please check that code:

    val monthExpr = ClientsDataExposed.regDate.month()

    fun sumByMonth(monthNum: Int) = Expression.build {
        val caseExpr = case().
            When(monthExpr eq intLiteral(monthNum), intLiteral(1)).
            Else(intLiteral(0))
        Sum(caseExpr, IntegerColumnType())
    }

    val janSumExp = sumByMonth(1)
    val febSumExp = sumByMonth(2)
    ClientsDataExposed.
        slice(ClientsDataExposed.cityName, janSumExp, febSumExp).
        selectAll().
        groupBy(ClientsDataExposed.id).map {
          val janSum = it[janSumExp]
          val febSum = it[febSumExp]
          ...
        }


问:
Not able to store the values dynamically in batch file while searching for a list of files in a directory
I am searching for file named file.txt and want to store the path of these files in a variable which should be in dynamic nature.
I am using arrays but not able to increment the value of i</p>

```<code>@echo on
D:
cd D:\study\
setlocal enableDelayedExpansion

set /a i=1
for /r %%G in (find.*txt) do (
    set /a i=%i%+1
    echo %i%
    set obj[%i%]=%%G
    )
</code>```

答:
You had enabled delayed expansion, but weren't using it.

The variables you're delaying the expansion of should be referenced with exclamation marks, not percent characters.

For example:

@Echo Off
CD /D "D:\study" 2>NUL || Exit /B 1

SetLocal EnableDelayedExpansion
Set "i=0"
For /F "Delims=" %%G in ('Dir /B/S/A-D "find.txt" 2>NUL') Do (
    Set /A i +=1
    Echo !i!
    Set "obj[!i!]=%%G"
)
```

Body:
I am searching for file named file.txt and want to store the path of these files in a variable which should be in dynamic nature.
I am using arrays but not able to increment the value of i

@echo on
D:
cd D:\study\
setlocal enableDelayedExpansion

set /a i=1
for /r %%G in (find.*txt) do (
    set /a i=%i%+1
    echo %i%
    set obj[%i%]=%%G
    )


问:
Specflow could not detect my tests VS 2017
I have been trying since long but no success yet. I created fresh unit test project and added the following :

Packages :

```<code>Nunit - 3.10.0
Nunit3TestAdapter - 3.11.0
SpecFlow - 2.3.2
SpecFlow.Assist.Dynamic - 1.3.1
</code>```

App.Config :

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="specFlow"
             type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow"/>
  </configSections>
  <specFlow>
    <unitTestProvider name="MsTest" />
  </specFlow>
</configuration>
</code>```

I tried with Nunit as well for above config.

Also added specflow default feature file and step definition file. But still VS 2017 can not detect any of my tests.

always getting as output :  NUnit couldn't find any tests in ....

I have already installed Specflow for Visual Studio 2017.

答:
There is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2

A workaround is to edit your .csproj and add a section after AfterUpdateFeatureFilesInProject.

```<code><Target Name="AfterUpdateFeatureFilesInProject">
  <ItemGroup>
    <Compile Include="@(SpecFlowGeneratedFiles)" />
  </ItemGroup>
</Target>

<!-- Workaround Specflow 2.3 MSBuild bug. SpecFlowGeneratedFiles is not set if UpdateFeatureFilesInProject is up-to-date
   causing tests not to be discovered, as they are not included in the project -->
<ItemGroup>
  <Compile Include="**/*.feature.cs" Exclude="@(SpecFlowGeneratedFiles)">
    <DependentUpon>%(Filename)</DependentUpon>
  </Compile>
</ItemGroup>
</code>```

Body:
I have been trying since long but no success yet. I created fresh unit test project and added the following :

Packages :

Nunit - 3.10.0
Nunit3TestAdapter - 3.11.0
SpecFlow - 2.3.2
SpecFlow.Assist.Dynamic - 1.3.1

App.Config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <specFlow>
    <unitTestProvider name="MsTest" />
  </specFlow>
</configuration>

I tried with Nunit as well for above config.

Also added specflow default feature file and step definition file. But still VS 2017 can not detect any of my tests.

always getting as output :  NUnit couldn't find any tests in ....

I have already installed Specflow for Visual Studio 2017.

Body:
There is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2

A workaround is to edit your .csproj and add a section after AfterUpdateFeatureFilesInProject.

<Target Name="AfterUpdateFeatureFilesInProject">
  <ItemGroup>
    <Compile Include="@(SpecFlowGeneratedFiles)" />
  </ItemGroup>
</Target>

<!-- Workaround Specflow 2.3 MSBuild bug. SpecFlowGeneratedFiles is not set if UpdateFeatureFilesInProject is up-to-date
   causing tests not to be discovered, as they are not included in the project -->
<ItemGroup>
  <Compile Include="**/*.feature.cs" Exclude="@(SpecFlowGeneratedFiles)">
    <DependentUpon>%(Filename)</DependentUpon>
  </Compile>
</ItemGroup>


问:
IndexErrors in python
```<code>#To Find the first occurance of a substring
def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))
</code>```

In the above code the letter e is present at index 9 so when I do string[i+1:(i+1+len(sequence)-1)] equivalent to string[10:13] shouldn't it be throwing an IndexError since the index 12 doesnt exist in the string?

答:
I don't understand why you have to write a custom function for finding the index of substring. python's string has the method index that does that.

e.g.

```<code>s="telephone"
print(s.index("phone"))
</code>```

gives you 4

by the way I run your code and it is returning not found

Title: IndexErrors in python

Body:
#To Find the first occurance of a substring
def getIndex(string, sequence):
    for i in range(len(string)):
        if string[i] == sequence[0]:
            try:
                if string[i+1:(i+1+len(sequence)-1)] == sequence[1:]:
                    return i
                else:
                    continue
            except IndexError:
                print('Array out of bounds substring doesnt exist')
    else:
        return 'not found'

print(getIndex('skyscrapper', 'erss'))

In the above code the letter e is present at index 9 so when I do string[i+1:(i+1+len(sequence)-1)] equivalent to string[10:13] shouldn't it be throwing an IndexError since the index 12 doesnt exist in the string?

Body:
I don't understand why you have to write a custom function for finding the index of substring. python's string has the method index that does that.

e.g.

s="telephone"
print(s.index("phone"))

gives you 4

by the way I run your code and it is returning not found


答:
List slicing works differently than accessing value of the list in given index. </p>

<p>List slicing actually won't never return IndexError - in worst case it would return [] </p>

```<code>foo = []
print(foo[5:12])
# Above prints []
</code>```

Title: IndexErrors in python

Body:
List slicing works differently than accessing value of the list in given index.

List slicing actually won't never return IndexError - in worst case it would return []

foo = []
print(foo[5:12])
# Above prints []


问:
Replace an image resource on a jasperserver via Java REST API v7.2.0
I am trying to upload reports and resources for these reports via the java rest api v7.2.0 on a jasperserver.

I found that upload an image could be done like so :

```<code>RestClientConfiguration configuration = new RestClientConfiguration("http://127.0.0.1:8082/jasperserver");
configuration.setLogHttp(true);
configuration.setLogHttpEntity(true);
configuration.setJrsVersion(JRSVersion.v6_1_0);
configuration.setRestrictedHttpMethods(false);

JasperserverRestClient client = new JasperserverRestClient(configuration);
Session session = client.authenticate("jasperadmin", "jasperadmin");

session.resourcesService().resource("/images").uploadFile(new File("logo.png"), ClientFile.FileType.img, "logo.png", "logo.png"));
</code>```

But this exact same code fail if the image already exists, but I would like to overwrite the image, in case it must be updated.

The problem is that I can't delete then upload again the image as if it is referenced in a report it will generate and error.

How can I replace an already present image via the rest api ?

答:
Ok, I found how to « update » a resource file on a jasper server using the rest api.

If someone go check the definition of the rest api, you could see that they use POST for creation and PUT for update.

The problem is that the java rest client library only provide a method that will only use POST, you have to find a way to had a method to switch the call of post by a call for put.

Body:
I am trying to upload reports and resources for these reports via the java rest api v7.2.0 on a jasperserver.

I found that upload an image could be done like so :

RestClientConfiguration configuration = new RestClientConfiguration("http://127.0.0.1:8082/jasperserver");
configuration.setLogHttp(true);
configuration.setLogHttpEntity(true);
configuration.setJrsVersion(JRSVersion.v6_1_0);
configuration.setRestrictedHttpMethods(false);

JasperserverRestClient client = new JasperserverRestClient(configuration);
Session session = client.authenticate("jasperadmin", "jasperadmin");

session.resourcesService().resource("/images").uploadFile(new File("logo.png"), ClientFile.FileType.img, "logo.png", "logo.png"));

But this exact same code fail if the image already exists, but I would like to overwrite the image, in case it must be updated.

The problem is that I can't delete then upload again the image as if it is referenced in a report it will generate and error.

How can I replace an already present image via the rest api ?


问:
Error in open.connection(x, "rb") : HTTP error 404 in R
I am trying to scrape data using R to obtain details about some of the listings in the below website but I am getting an error that I am unsure how to resolve: Error in open.connection(x, "rb") : HTTP error 404
I tried using httr package and try function as seen in similar posts but cant resolve it. Am I doing something wrong?</p>

```<code>library(XML)
library(RCurl)
library(curl)
library(rvest)
library(tidyverse)
library(dplyr)
library(httr)

url <- "https://www.sgcarmart.com/new_cars/index.php"
cardetails <- read_html(url)

listing <- html_nodes(cardetails, "#nc_popular_car")
popularcars <- html_nodes(listing,".link")
count<-length(popularcars)

info <- data.frame(CarName=NA, Distributer=NA, Hotline= NA, CountryBuilt= NA, Predecessor= NA, stringsAsFactors = F )

for(i in 1:count)
{
  h <- popularcars[[i]]

details_url <- paste0("https://www.sgcarmart.com/new_cars",html_attr(h,"href"))

details <- read_html(details_url)

info[i,]$CarName <- html_node(details,".link_redbanner")

}

info
</code>```

答:
TL;DR

Add a slash:

  details_url <- paste0("https://www.sgcarmart.com/new_cars/",html_attr(h,"href"))
  # --->          --->          --->          --->         ^
```

<h1>The Journey</h1>

<ol>
<li><p>I ran your source far enough to get the <code>popularcars</code>, and looked at the first one:</p>

<pre class="lang-r prettyprint-override"><code>h <- popularcars[[1]]
h
# {html_node}
#
# [1] <div style="position:relative; padding-bottom:6px;">\r\n                                < ...
# [2] <div style="padding-bottom:3px;" class="limittwolines">Toyota Corolla Altis</div>
details_url <- paste0("https://www.sgcarmart.com/new_cars",html_attr(h,"href"))
details_url
# [1] "https://www.sgcarmart.com/new_carsnewcars_overview.php?CarCode=12618"
</code>```

Like you, for me that URL returned 404.

I navigated (in a boring, normal, browser) to the main URL, looked at the source for the page, and searched for 12618:

Toyota Corolla Altis

$91,888

```</li>
<li><p>I right-clicked on the <code>href="newcars_overview.php?CarCode=12618" class="link"></code> portion and copied the "link location. I found that it was:</p>

```https://www.sgcarmart.com/new_cars/newcars_overview.php?CarCode=12618 <-- from the source
https://www.sgcarmart.com/new_carsnewcars_overview.php?CarCode=12618  <-- from your code
```</li>
</ol>

<hr>

<p>BTW, you might find this a little easier to manage than a <code>for</code> loop. Iteratively building a frame is horribly inefficient, and while it may not be bad for the 18 entries I found it, it's not good in the long run (if you can avoid it).</p>

<pre class="lang-r prettyprint-override"><code>info <- lapply(popularcars, function(h) {
    details_url <- paste0("https://www.sgcarmart.com/new_cars/", html_attr(h,"href"))
    details <- read_html(details_url)
    html_text(html_node(details,".link_redbanner"))
  })

str(info)
# List of 18
#  $ : chr "Toyota Corolla Altis"
#  $ : chr "Hyundai Venue"
#  $ : chr "Hyundai Avante"
#  $ : chr "SKODA Octavia"
#  $ : chr "Honda Civic"
#  $ : chr "Mazda 3 Sedan Mild Hybrid"
#  $ : chr "Honda Jazz"
#  $ : chr "Kia Cerato"
#  $ : chr "Mazda CX-5"
#  $ : chr "Mercedes-Benz GLA-Class(Parallel Imported)"
#  $ : chr "Toyota Raize(Parallel Imported)"
#  $ : chr "Toyota Camry Hybrid(Parallel Imported)"
#  $ : chr "Mercedes-Benz A-Class Hatchback(Parallel Imported)"
#  $ : chr "Mercedes-Benz A-Class Saloon(Parallel Imported)"
#  $ : chr "Honda Fit(Parallel Imported)"
#  $ : chr "Mercedes-Benz C-Class Saloon(Parallel Imported)"
#  $ : chr "Mercedes-Benz CLA-Class(Parallel Imported)"
#  $ : chr "Honda Freed Hybrid(Parallel Imported)"
</code>```

Last point: while this is a worthwhile learning endeavor, that website's href="https://www.sgcarmart.com/main/tos.php" rel="nofollow noreferrer">Terms of Service are clear to state: "You agree that you will not: ... engage in mass automated, systematic or any form of extraction of the material ("the Content") on our Website". I assume your efforts are under that limit.

Body:
I am trying to scrape data using R to obtain details about some of the listings in the below website but I am getting an error that I am unsure how to resolve: Error in open.connection(x, "rb") : HTTP error 404
I tried using httr package and try function as seen in similar posts but cant resolve it. Am I doing something wrong?

library(XML)
library(RCurl)
library(curl)
library(rvest)
library(tidyverse)
library(dplyr)
library(httr)

url <- "https://www.sgcarmart.com/new_cars/index.php"
cardetails <- read_html(url)

listing <- html_nodes(cardetails, "#nc_popular_car")
popularcars <- html_nodes(listing,".link")
count<-length(popularcars)

info <- data.frame(CarName=NA, Distributer=NA, Hotline= NA, CountryBuilt= NA, Predecessor= NA, stringsAsFactors = F )

for(i in 1:count)
{
  h <- popularcars[[i]]

details_url <- paste0("https://www.sgcarmart.com/new_cars",html_attr(h,"href"))

details <- read_html(details_url)

info[i,]$CarName <- html_node(details,".link_redbanner")

}

info

Body:
TL;DR

Add a slash:

  details_url <- paste0("https://www.sgcarmart.com/new_cars/",html_attr(h,"href"))
  # --->          --->          --->          --->         ^

The Journey

I ran your source far enough to get the popularcars, and looked at the first one:

h <- popularcars[[1]]
h
# {html_node}
# <a href="newcars_overview.php?CarCode=12618" class="link">
# [1] <div style="position:relative; padding-bottom:6px;">\r\n                                < ...
# [2] <div style="padding-bottom:3px;" class="limittwolines">Toyota Corolla Altis</div>
details_url <- paste0("https://www.sgcarmart.com/new_cars",html_attr(h,"href"))
details_url
# [1] "https://www.sgcarmart.com/new_carsnewcars_overview.php?CarCode=12618"

Like you, for me that URL returned 404.

I navigated (in a boring, normal, browser) to the main URL, looked at the source for the page, and searched for 12618:

<div style="padding:10px 10px 5px 10px;" id="nc_popular_car">
                                        <div class="floatleft" style="text-align:center;width:136px;padding-right:22px;">
                        <a href="newcars_overview.php?CarCode=12618" class="link">
                            <div style="position:relative; padding-bottom:6px;">
                                <div style="position:absolute; border:1px solid #B9B9B9; width:134px; height:88px;"><img src="https://i.i-sgcm.com/images/spacer.gif" width="1" height="1" alt="spacer" /></div>
                                <img src="https://i.i-sgcm.com/new_cars/cars/12618/12618_m.jpg" width="136" height="90" border="0" alt="Toyota Corolla Altis" />
                            </div>
                            <div style="padding-bottom:3px;" class="limittwolines">Toyota Corolla Altis</div>
                        </a>
                        <div style="padding-bottom:14px;" class="font_black">$91,888</div>
                    </div>

I right-clicked on the <a href="newcars_overview.php?CarCode=12618" class="link"> portion and copied the "link location. I found that it was:

https://www.sgcarmart.com/new_cars/newcars_overview.php?CarCode=12618 <-- from the source
https://www.sgcarmart.com/new_carsnewcars_overview.php?CarCode=12618  <-- from your code

BTW, you might find this a little easier to manage than a for loop. Iteratively building a frame is horribly inefficient, and while it may not be bad for the 18 entries I found it, it's not good in the long run (if you can avoid it).

info <- lapply(popularcars, function(h) {
    details_url <- paste0("https://www.sgcarmart.com/new_cars/", html_attr(h,"href"))
    details <- read_html(details_url)
    html_text(html_node(details,".link_redbanner"))
  })

str(info)
# List of 18
#  $ : chr "Toyota Corolla Altis"
#  $ : chr "Hyundai Venue"
#  $ : chr "Hyundai Avante"
#  $ : chr "SKODA Octavia"
#  $ : chr "Honda Civic"
#  $ : chr "Mazda 3 Sedan Mild Hybrid"
#  $ : chr "Honda Jazz"
#  $ : chr "Kia Cerato"
#  $ : chr "Mazda CX-5"
#  $ : chr "Mercedes-Benz GLA-Class(Parallel Imported)"
#  $ : chr "Toyota Raize(Parallel Imported)"
#  $ : chr "Toyota Camry Hybrid(Parallel Imported)"
#  $ : chr "Mercedes-Benz A-Class Hatchback(Parallel Imported)"
#  $ : chr "Mercedes-Benz A-Class Saloon(Parallel Imported)"
#  $ : chr "Honda Fit(Parallel Imported)"
#  $ : chr "Mercedes-Benz C-Class Saloon(Parallel Imported)"
#  $ : chr "Mercedes-Benz CLA-Class(Parallel Imported)"
#  $ : chr "Honda Freed Hybrid(Parallel Imported)"

Last point: while this is a worthwhile learning endeavor, that website's Terms of Service are clear to state: "You agree that you will not: ... engage in mass automated, systematic or any form of extraction of the material ("the Content") on our Website". I assume your efforts are under that limit.


问:
np.average of word vectors
I have this dictionary that contains words as keys and their vectors as values.

```<code>my_dict = {'new': array([ 6.77980e-02, -2.07800e-02, -1.22845e-01, 1.75853e-01,  1.49210e-02]),
           'its': array([ 7.85300e-03, -8.81160e-02,  2.60125e-01,  1.77740e-02, -1.09075e-011])}
</code>```

I would like to calculate the element-wise average of the vectors for these given words using np.average(). The result should be a np.ndarray.

This is my attempt:

```<code>average = [np.average(my_dict[x], axis=None) for x in self.my_dict]
</code>```

答:
So that you calculate one average over all the values (rather than collect a set of nonsense average for each individual vector), try:

```<code>np.average(list(my_dict.values()))
</code>```

(If it doesn't return the shape you expect, try each explicit axis= possibility.)

Title: np.average of word vectors

Body:
I have this dictionary that contains words as keys and their vectors as values.

my_dict = {'new': array([ 6.77980e-02, -2.07800e-02, -1.22845e-01, 1.75853e-01,  1.49210e-02]),
           'its': array([ 7.85300e-03, -8.81160e-02,  2.60125e-01,  1.77740e-02, -1.09075e-011])}

I would like to calculate the element-wise average of the vectors for these given words using np.average(). The result should be a np.ndarray.

This is my attempt:

average = [np.average(my_dict[x], axis=None) for x in self.my_dict]

Body:
So that you calculate one average over all the values (rather than collect a set of nonsense average for each individual vector), try:

np.average(list(my_dict.values()))

(If it doesn't return the shape you expect, try each explicit axis= possibility.)


问:
How can I destroy a gameobject that is part of a prefab?
I want to use the ModifyPrefab method but not sure how.
The problem is when I'm destroying the oldGameObject :

```<code>DestroyImmediate(oldGameObject);
</code>```

I'm getting exception in the editor :

InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class PrefabSwitch : MonoBehaviour
{
    /// <summary>The new object to instantiate in place of the old object.</summary>
    public GameObject newPrefab;
    /// <summary>The old objects, intended to be swapped out for iterations of
    /// the new object.</summary>
    public GameObject[] oldGameObjects;
    /// <summary>The string tag to use when replacing objects by tag.</summary>
    public string searchByTag;

    /// <summary>Swaps all the game objects in oldGameObjects for
    /// a new newPrefab.</summary>
    public void SwapAllByArray(GameObject[] objectsToSwap)
    {
        // Store a boolean to detect if we intend to swap this game object.
        bool swappingSelf = false;

        // For each game object in the oldGameObjects array,
        for (int i = 0; i < oldGameObjects.Length; i++)
        {
            // If the current game object is this game object,
            if (oldGameObjects[i] == gameObject)
            {
                // Enable the flag to swap this game object at the end, so we
                // do not destroy it before the script an complete its task.
                swappingSelf = true;
            }
            else
            {
                // Else, we are not dealing with the game object local to this
                // script, so we can swap the prefabs, immediately.
                SwapPrefabs(oldGameObjects[i]);
            }
        }

        // If we have flagged the local game object to be swapped,
        if (swappingSelf)
        {
            // Swap the local game object.
            SwapPrefabs(gameObject);
        }
    }

    /// <summary>Swaps all the game objects that use the tag <code>searchByTag</code>.
    /// If empty, we will use the tag of the local game object.</summary>
    public void SwapAllByTag()
    {
        // If searchByTag is null,
        if (searchByTag == "")
        {
            // Set searchByTag to the tag of the local game object.
            searchByTag = gameObject.tag;
        }

        // Find all the game objects using the tag searchByTag,
        // store them in our array, and proceed to swapping them.
        oldGameObjects = GameObject.FindGameObjectsWithTag(searchByTag);
        SwapAllByArray(oldGameObjects);
    }

    /// <summary>Swaps the desired oldGameObject for a newPrefab.</summary>
    /// <param name="oldGameObject">The old game object.</param>
    void SwapPrefabs(GameObject oldGameObject)
    {
        // Determine the rotation and position values of the old game object.
        // Replace rotation with Quaternion.identity if you do not wish to keep rotation.
        Quaternion rotation = oldGameObject.transform.rotation;
        Vector3 position = oldGameObject.transform.position;

        // Instantiate the new game object at the old game objects position and rotation.
        GameObject newGameObject = Instantiate(newPrefab, position, rotation);

        // If the old game object has a valid parent transform,
        // (You can remove this entire if statement if you do not wish to ensure your
        // new game object does not keep the parent of the old game object.
        if (oldGameObject.transform.parent != null)
        {
            // Set the new game object parent as the old game objects parent.
            newGameObject.transform.SetParent(oldGameObject.transform.parent);
        }

        // Destroy the old game object, immediately, so it takes effect in the editor.
        DestroyImmediate(oldGameObject);
    }

    private void ModifyPrefab()
    {
        // Get the Prefab Asset root GameObject and its asset path.
        GameObject assetRoot = Selection.activeObject as GameObject;
        string assetPath = AssetDatabase.GetAssetPath(assetRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        contentsRoot.AddComponent<BoxCollider>();

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(contentsRoot);
    }
}
</code>```

答:
This is heavily discussed here: https://forum.unity.com/threads/destroying-a-gameobject-inside-a-prefab-instance-is-not-allowed.555868/

It is not exactly a bug, but a side effect from the implementation of the PreFab system.

Top solutions are:

```<code>if (UnityEditor.PrefabUtility.IsPartOfPrefabInstance(transform))

   UnityEditor.PrefabUtility.UnpackPrefabInstance(gameObject,
         UnityEditor.PrefabUnpackMode.Completely,
         UnityEditor.InteractionMode.AutomatedAction);

// Then I do DestroyImmediate();
</code>```

And this:

```<code>var rootGO = PrefabUtility.LoadPrefabContents(pathToMyPrefab);
// Destroy child objects or components on rootGO
PrefabUtility.SaveAsPrefabAsset(rootGO, pathToMyPrefab);
prefabUtility.UnloadPrefabContents(rootGO);
</code>```

Body:
I want to use the ModifyPrefab method but not sure how.
The problem is when I'm destroying the oldGameObject :

DestroyImmediate(oldGameObject);

I'm getting exception in the editor :

InvalidOperationException: Destroying a GameObject inside a Prefab instance is not allowed.

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class PrefabSwitch : MonoBehaviour
{
    /// The new object to instantiate in place of the old object.
    public GameObject newPrefab;
    /// The old objects, intended to be swapped out for iterations of
    /// the new object.
    public GameObject[] oldGameObjects;
    /// The string tag to use when replacing objects by tag.
    public string searchByTag;

    /// Swaps all the game objects in oldGameObjects for
    /// a new newPrefab.
    public void SwapAllByArray(GameObject[] objectsToSwap)
    {
        // Store a boolean to detect if we intend to swap this game object.
        bool swappingSelf = false;

        // For each game object in the oldGameObjects array,
        for (int i = 0; i < oldGameObjects.Length; i++)
        {
            // If the current game object is this game object,
            if (oldGameObjects[i] == gameObject)
            {
                // Enable the flag to swap this game object at the end, so we
                // do not destroy it before the script an complete its task.
                swappingSelf = true;
            }
            else
            {
                // Else, we are not dealing with the game object local to this
                // script, so we can swap the prefabs, immediately.
                SwapPrefabs(oldGameObjects[i]);
            }
        }

        // If we have flagged the local game object to be swapped,
        if (swappingSelf)
        {
            // Swap the local game object.
            SwapPrefabs(gameObject);
        }
    }

    /// Swaps all the game objects that use the tag searchByTag.
    /// If empty, we will use the tag of the local game object.
    public void SwapAllByTag()
    {
        // If searchByTag is null,
        if (searchByTag == "")
        {
            // Set searchByTag to the tag of the local game object.
            searchByTag = gameObject.tag;
        }

        // Find all the game objects using the tag searchByTag,
        // store them in our array, and proceed to swapping them.
        oldGameObjects = GameObject.FindGameObjectsWithTag(searchByTag);
        SwapAllByArray(oldGameObjects);
    }

    /// Swaps the desired oldGameObject for a newPrefab.
    /// <param name="oldGameObject">The old game object.</param>
    void SwapPrefabs(GameObject oldGameObject)
    {
        // Determine the rotation and position values of the old game object.
        // Replace rotation with Quaternion.identity if you do not wish to keep rotation.
        Quaternion rotation = oldGameObject.transform.rotation;
        Vector3 position = oldGameObject.transform.position;

        // Instantiate the new game object at the old game objects position and rotation.
        GameObject newGameObject = Instantiate(newPrefab, position, rotation);

        // If the old game object has a valid parent transform,
        // (You can remove this entire if statement if you do not wish to ensure your
        // new game object does not keep the parent of the old game object.
        if (oldGameObject.transform.parent != null)
        {
            // Set the new game object parent as the old game objects parent.
            newGameObject.transform.SetParent(oldGameObject.transform.parent);
        }

        // Destroy the old game object, immediately, so it takes effect in the editor.
        DestroyImmediate(oldGameObject);
    }

    private void ModifyPrefab()
    {
        // Get the Prefab Asset root GameObject and its asset path.
        GameObject assetRoot = Selection.activeObject as GameObject;
        string assetPath = AssetDatabase.GetAssetPath(assetRoot);

        // Load the contents of the Prefab Asset.
        GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

        // Modify Prefab contents.
        contentsRoot.AddComponent<BoxCollider>();

        // Save contents back to Prefab Asset and unload contents.
        PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath);
        PrefabUtility.UnloadPrefabContents(contentsRoot);
    }
}

Body:
This is heavily discussed here: https://forum.unity.com/threads/destroying-a-gameobject-inside-a-prefab-instance-is-not-allowed.555868/

It is not exactly a bug, but a side effect from the implementation of the PreFab system.

Top solutions are:

if (UnityEditor.PrefabUtility.IsPartOfPrefabInstance(transform))

   UnityEditor.PrefabUtility.UnpackPrefabInstance(gameObject,
         UnityEditor.PrefabUnpackMode.Completely,
         UnityEditor.InteractionMode.AutomatedAction);

// Then I do DestroyImmediate();

And this:

var rootGO = PrefabUtility.LoadPrefabContents(pathToMyPrefab);
// Destroy child objects or components on rootGO
PrefabUtility.SaveAsPrefabAsset(rootGO, pathToMyPrefab);
prefabUtility.UnloadPrefabContents(rootGO);


问:
iis7 default mime type behavior
So in IIS 7 if there is no specific MIME definition for a certain extension, it will refuse to serve it (404) even if you can see it in a directory listing.  I'm sure this is a fairly known issue, but is there a way to wildcard or set a default action for unknown file types?  I want everything to be offered for download by default like with every other webserver I've used.</p>

答:
I believe you just need to edit your website in Internet Information Services Manager and double click the Request Filtering icon and edit it however you like there.

The mime type configuration does not allow/disallow downloading files; it just tells IIS what to throw in the header when you do download it.

Title: iis7 default mime type behavior


问:
Cannot resolve symbol 'AndroidJUnit4'
Obviously I need the correct import statment to solve this problem. According to the docs for AndroidJUnit4, this should be

```<code>import android.support.test.runner.AndroidJUnit4;
</code>```

When I do that, Android Studio highlights runner in red and complains "Cannot resolve symbol 'runner'".

Background

I got to this point by following the tutorials on the Android Developer site for setting up tests using UI Automator. The first problem I encountered was that com.android.support:support-v4:22.2.0 and com.android.support.test:runner:0.2 depend on different versions of com.android.support:support-annotations. I followed the suggestions from this Android bug report and added the following to allprojects in my project's build.gradle:

```<code>configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:22.1.0'
}
</code>```

This solved the immediate error, but I suspect it lead to my current problems. Does anyone have any suggestions about how to fix this?

Relevent sections from `./gradlew :app:dependencies

```<code>androidTestCompile - Classpath for compiling the androidTest sources.
+--- com.jayway.android.robotium:robotium-solo:5.2.1
+--- com.squareup:fest-android:1.0.8
|    \--- org.easytesting:fest-assert-core:2.0M10
|         \--- org.easytesting:fest-util:1.2.5
+--- com.android.support.test:runner:0.2
|    +--- junit:junit-dep:4.10
|    |    \--- org.hamcrest:hamcrest-core:1.1
|    +--- com.android.support.test:exposed-instrumentation-api-publish:0.2
|    \--- com.android.support:support-annotations:22.0.0 -> 22.2.0
+--- com.android.support.test:rules:0.2
|    \--- com.android.support.test:runner:0.2 (*)
\--- com.android.support.test.uiautomator:uiautomator-v18:2.1.0

compile - Classpath for compiling the main sources.
+--- com.android.support:appcompat-v7:22.2.0
|    \--- com.android.support:support-v4:22.2.0
|         \--- com.android.support:support-annotations:22.2.0
+--- com.android.support:support-v4:22.2.0 (*)
+--- com.google.android.gms:play-services:6.1.71
|    \--- com.android.support:support-v4:20.0.0 -> 22.2.0 (*)
+--- com.crashlytics.android:crashlytics:1.+ -> 1.1.13
\--- com.jakewharton:butterknife:5.1.2
</code>```

答:
Short Story Version:

Upgrade your Gradle to the latest Version

I am answering this question post on Feb, 15th, 2020.
Unfortunately, I have exhausted every possible solutions mentioned here and elsewhere.

https://github.com/codepath/android_guides/wiki/UI-Testing-with-Espresso

https://github.com/udacity/AdvancedAndroid_TeaTime/issues/14

Android Espresso : cannot resolve symbol AndroidJUnit4.class

Cannot resolve symbol AndroidJUnit4

Android Espresso : cannot resolve symbol AndroidJUnit4.class

Yes, none of them above workes. I use the built-in function, "Migrate to Andoridx", it may remind me that I have to upgrade my target SDK versions and my gradle version. After I upgraded my gradle version from 2.0.2 to 3.5.3. They just works, even the old import statement works.

Title: Cannot resolve symbol 'AndroidJUnit4'

Body:
Obviously I need the correct import statment to solve this problem. According to the docs for AndroidJUnit4, this should be

import android.support.test.runner.AndroidJUnit4;

When I do that, Android Studio highlights runner in red and complains "Cannot resolve symbol 'runner'".

Background

I got to this point by following the tutorials on the Android Developer site for setting up tests using UI Automator. The first problem I encountered was that com.android.support:support-v4:22.2.0 and com.android.support.test:runner:0.2 depend on different versions of com.android.support:support-annotations. I followed the suggestions from this Android bug report and added the following to allprojects in my project's build.gradle:

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:22.1.0'
}

This solved the immediate error, but I suspect it lead to my current problems. Does anyone have any suggestions about how to fix this?

Relevent sections from `./gradlew :app:dependencies

androidTestCompile - Classpath for compiling the androidTest sources.
+--- com.jayway.android.robotium:robotium-solo:5.2.1
+--- com.squareup:fest-android:1.0.8
|    \--- org.easytesting:fest-assert-core:2.0M10
|         \--- org.easytesting:fest-util:1.2.5
+--- com.android.support.test:runner:0.2
|    +--- junit:junit-dep:4.10
|    |    \--- org.hamcrest:hamcrest-core:1.1
|    +--- com.android.support.test:exposed-instrumentation-api-publish:0.2
|    \--- com.android.support:support-annotations:22.0.0 -> 22.2.0
+--- com.android.support.test:rules:0.2
|    \--- com.android.support.test:runner:0.2 (*)
\--- com.android.support.test.uiautomator:uiautomator-v18:2.1.0

compile - Classpath for compiling the main sources.
+--- com.android.support:appcompat-v7:22.2.0
|    \--- com.android.support:support-v4:22.2.0
|         \--- com.android.support:support-annotations:22.2.0
+--- com.android.support:support-v4:22.2.0 (*)
+--- com.google.android.gms:play-services:6.1.71
|    \--- com.android.support:support-v4:20.0.0 -> 22.2.0 (*)
+--- com.crashlytics.android:crashlytics:1.+ -> 1.1.13
\--- com.jakewharton:butterknife:5.1.2


问:
Counting the number of characters in C language
I am a beginner of C language, and now trying to count the number of characters which is input.

```<code>#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%1d\n", nc);
}
</code>```

This is what I wrote just as my textbook writes, but printf function doesn't seem to work.

In addition, this program doesn't seem to finish, because the prompt is not coming up.

I have no idea if the contents of this book are old enough.

Could you tell me what is wrong with this code?

答:
This looks like code from K&R
The C Programming Language, 2nd Edn (1988), Chapter 1, p18.

The problem is that your transcription of the code is misinterpreting %ld as %1d.  Given that nc is of type long, you need %ld (letter ell) and not %1d (digit one).  The book contains an ell and not a one.

With suitable options, compilers like GCC and Clang will give warnings about type mismatches in the format strings.  Use -Wall -Werror to get errors when the code is malformed (or -Wformat if you can't work with -Wall — but I use -Wall -Wextra -Werror plus a few extra fussier options for all my compilations; I won't risk making mistakes that the compiler can tell me about).

The use of main() shows that the book is dated.  C99 requires a return type and prefers void in the argument list — int main(void) — when you don't make use of the command line arguments.

As to the program not finishing, when you're typing at the terminal, you indicate EOF (end of file) to the program by typing Control-D on most Unix-like systems (though it is configurable), and Control-Z on Windows systems.  (If you want to indicate EOF without typing a newline immediately beforehand, you need to type the EOF indicator twice instead of just once.) Or you can feed it a file from the shell: counter < data-file (assuming the program is called counter and you want to count the characters in the file data-file).

Body:
I am a beginner of C language, and now trying to count the number of characters which is input.

#include <stdio.h>

main()
{
    long nc;
    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%1d\n", nc);
}

This is what I wrote just as my textbook writes, but printf function doesn't seem to work.

In addition, this program doesn't seem to finish, because the prompt is not coming up.

I have no idea if the contents of this book are old enough.

Could you tell me what is wrong with this code?


问:
Retrieving records from other table column
I created a view where there are multiple column. I need to retrieve some data from an external table.

```<code>cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName
</code>```

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.

答:
From your comment:

I observed that the correct result should be the lesser values from
  roadName records and those values that are not nulls

I think that you need conditional aggregation:

```<code>SELECT roadName,
  sum(case when roadCrossSection1 is not null then roadLength end) as sumRoadLength,
  max(roadCrossSection1) roadCrossSection1
FROM cte4
group by roadName
order by roadName
</code>```

Body:
I created a view where there are multiple column. I need to retrieve some data from an external table.

cte4 as (
SELECT *,
case
    when roadName=roadNameUserData then sec1
else 'x'
end as roadCrossSection1

FROM dbo.roadSectionAndPavementUserData,cte3
    )

--"roadName" is from cte computed column view
--"roadNameUserData" is from other table("dbo.roadSectionAndPavementUserData") where records are to be extracted
--sec1 is the column in table "dbo.roadSectionAndPavementUserData" where the results coming from

-----final view
SELECT roadName,
sum(roadLength) as sumRoadLength,roadCrossSection1

FROM cte4
group by roadName
order by roadName

When i execute the query, it came with the following error

"Column 'cte4.roadCrossSection1' is invalid in the select list because
  it is not contained in either an aggregate function or the GROUP BY
  clause."

This is the result after adding additional groupby statement. The correct records are the lesser values of sumRoadLength.

Body:
From your comment:

I observed that the correct result should be the lesser values from
  roadName records and those values that are not nulls

I think that you need conditional aggregation:

SELECT roadName,
  sum(case when roadCrossSection1 is not null then roadLength end) as sumRoadLength,
  max(roadCrossSection1) roadCrossSection1
FROM cte4
group by roadName
order by roadName


问:
Make thread sleep until a set date?
I wanted to know how can you make a thread sleep until a set date like for example a set date 14/Feb/2020.

Thread will remain sleep until this date. is there any way to do that in java?.

答:
Executor service

Define a Runnable (or Callable). That means simply having a run method to comply with the contract of the interface.

In lambda syntax:

```<code>Runnable runnable =
    () -> {
        System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() ) ;
    }
;
</code>```

Next, study up on the Executors framework built into modern Java. See Oracle Tutorial. This framework greatly simplifies the tricky work of scheduling work on threads.

Specifically, you want to use ScheduledExecutorService. This interface is for scheduling a task to run once at a specific time (actually, run once after a specific delay expires), or run a task repeatedly. You, of course, want the former.

Get an implementation from the Executors class. For your needs, we need only a single-thread. In other cases, you may want to use a thread pool.

```<code>ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;
</code>```

Specify how long to wait, a delay, until the task is executed. Calculate the elapsed time needed to wait.

Specify your target date. In real work I would verify that date is indeed in the future.

```<code>LocalDate localDate = LocalDate.of( 2020 , Month.FEBRUARY , 23 ) ;
</code>```

We need a specific moment rather than just a date. I suppose you would want the first moment of that day. Do not assume this is 00:00. Some days in some zones on some dates may start at another time, such as 01:00.  Always let java.time determine first moment.

```<code>ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = localDate.atStartOfDay( z ) ;
</code>```

Convert from that time zone to UTC.

```<code>Instant then = zdt.toInstant() ;
</code>```

Capture the current moment as seen in UTC.

```<code>Instant now = Instant.now() ;
</code>```

Calculate elapsed time as a Duration.

```<code>Duration d = Duration.between( now , then ) ;
</code>```

Now schedule our task to be run after the delay expires. I suggest adding a bit of time to make sure all the clocks of any related systems are well into the new day. Plus midnight tends to be the Witching Hour for computing, with many cron jobs, log-rolling, utilities, and reports running then. Maybe add a few minutes or more.

```<code>ses.scheduleWithFixedDelay( runnable , d.plusMinutes( 7 ).toMinutes() , TimeUnit.MINUTES);
</code>```

You may choose to capture the returned ScheduledFuture to monitor your task.

IMPORTANT Be sure to gracefully shutdown your executor service when no longer needed, or when your app is being shut down. Otherwise your threads may continue running in the background, surviving your app's exit.

```<code>ses.shutdown() ;
</code>```

Title: Make thread sleep until a set date?

Body:
Executor service

Define a Runnable (or Callable). That means simply having a run method to comply with the contract of the interface.

In lambda syntax:

Runnable runnable =
    () -> {
        System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() ) ;
    }
;

Next, study up on the Executors framework built into modern Java. See Oracle Tutorial. This framework greatly simplifies the tricky work of scheduling work on threads.

Specifically, you want to use ScheduledExecutorService. This interface is for scheduling a task to run once at a specific time (actually, run once after a specific delay expires), or run a task repeatedly. You, of course, want the former.

Get an implementation from the Executors class. For your needs, we need only a single-thread. In other cases, you may want to use a thread pool.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

Specify how long to wait, a delay, until the task is executed. Calculate the elapsed time needed to wait.

Specify your target date. In real work I would verify that date is indeed in the future.

LocalDate localDate = LocalDate.of( 2020 , Month.FEBRUARY , 23 ) ;

We need a specific moment rather than just a date. I suppose you would want the first moment of that day. Do not assume this is 00:00. Some days in some zones on some dates may start at another time, such as 01:00.  Always let java.time determine first moment.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = localDate.atStartOfDay( z ) ;

Convert from that time zone to UTC.

Instant then = zdt.toInstant() ;

Capture the current moment as seen in UTC.

Instant now = Instant.now() ;

Calculate elapsed time as a Duration.

Duration d = Duration.between( now , then ) ;

Now schedule our task to be run after the delay expires. I suggest adding a bit of time to make sure all the clocks of any related systems are well into the new day. Plus midnight tends to be the Witching Hour for computing, with many cron jobs, log-rolling, utilities, and reports running then. Maybe add a few minutes or more.

ses.scheduleWithFixedDelay( runnable , d.plusMinutes( 7 ).toMinutes() , TimeUnit.MINUTES);

You may choose to capture the returned ScheduledFuture to monitor your task.

IMPORTANT Be sure to gracefully shutdown your executor service when no longer needed, or when your app is being shut down. Otherwise your threads may continue running in the background, surviving your app's exit.

ses.shutdown() ;


问:
Force sold individually product to be bought alone in WooCommerce
Let's Say I have Product A which is allow to bought alone.

If something else already in cart it shows the message. "Not Allow". I tried various methods but not able to find proper solution for that.

When somebody tries to click on the "ADD TO CART" button then it must check via code that if other items in cart it is not allow to put in cart and shows the message.

PRODUCT A is allow bought alone.

I tried with the category comparison and it works. but I want to do only with the Product ID.

add_filter('woocommerce_add_to_cart_validation', 'dont_add_paint_to_cart_containing_other', 10, 5);
function dont_add_paint_to_cart_containing_other($validation, $product_id) {

// Set flag false until we find a product in cat paint
    $cart_has_paint = false;

// Set $cat_check true if a cart item is in paint cat
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {

        $products_ids = 137817;
        $product = $cart_item['data'];

        if (has_term('miscellaneous', 'product_cat', $product->id)) {

            $cart_has_paint = true;
            // break because we only need one "true" to matter here
            break;
        }

    }

    $product_is_paint = false;
    if (has_term('miscellaneous', 'product_cat', $product_id)) {

        $product_is_paint = true;
    }

// Return true if cart empty

    if (!WC()->cart->get_cart_contents_count() == 0) {
        // If cart contains paint and product to be added is not paint, display error message and return false.
        if ($cart_has_paint && !$product_is_paint) {
             echo '';

            $validation = false;
        }
        // If cart contains a product that is not paint and product to be added is paint, display error message and return false.

       elseif (!$cart_has_paint && $product_is_paint) {
            echo '';

            $validation = false;
        }
    }
    // Otherwise, return true.
    return $validation;
}
```

This code only works with the miscellaneous category I want to allow only with the Product ID.. not category..

答:
Assuming that only 1 quantity can be purchased from product A

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Product id to bought alone
    $product_id_alone = 30;

    // Set variable
    $alone = true;

    // If passed
    if ( $passed ) {
        // If cart is NOT empty when a product is added
        if ( !WC()->cart->is_empty() ) {

            // If product id added = product id alone
            if ( $product_id_alone == $product_id ) {
                $alone = false;
            } else {
                // Generate a unique ID for the cart item
                $product_cart_id = WC()->cart->generate_cart_id( $product_id_alone );

                // Check if product is in the cart
                $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

                // If product is already in cart
                if ( $in_cart ) {
                    $alone = false;
                }
            }
        } else {
            // If product is added when cart is empty but $quantity > 1
            if ( $product_id_alone == $product_id && $quantity > 1 ) {
                $alone = false;
            }
        }
    }

    if ( $alone == false ) {
        // Set error message
        $message = 'PRODUCT A is allow bought alone.';
        wc_add_notice( __( $message, 'woocommerce' ), 'error' );
        $passed = false;

        // Empty the cart
        WC()->cart->empty_cart();

        // Add specific product with quantity 1
        WC()->cart->add_to_cart($product_id_alone, 1 );
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
```

Related: Force specific WooCommerce product to be sold in separate order

Body:
Let's Say I have Product A which is allow to bought alone.

If something else already in cart it shows the message. "Not Allow". I tried various methods but not able to find proper solution for that.

When somebody tries to click on the "ADD TO CART" button then it must check via code that if other items in cart it is not allow to put in cart and shows the message.

PRODUCT A is allow bought alone.

I tried with the category comparison and it works. but I want to do only with the Product ID.

add_filter('woocommerce_add_to_cart_validation', 'dont_add_paint_to_cart_containing_other', 10, 5);
function dont_add_paint_to_cart_containing_other($validation, $product_id) {

// Set flag false until we find a product in cat paint
    $cart_has_paint = false;

// Set $cat_check true if a cart item is in paint cat
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {

        $products_ids = 137817;
        $product = $cart_item['data'];

        if (has_term('miscellaneous', 'product_cat', $product->id)) {

            $cart_has_paint = true;
            // break because we only need one "true" to matter here
            break;
        }

    }

    $product_is_paint = false;
    if (has_term('miscellaneous', 'product_cat', $product_id)) {

        $product_is_paint = true;
    }

// Return true if cart empty

    if (!WC()->cart->get_cart_contents_count() == 0) {
        // If cart contains paint and product to be added is not paint, display error message and return false.
        if ($cart_has_paint && !$product_is_paint) {
             echo '';

            $validation = false;
        }
        // If cart contains a product that is not paint and product to be added is paint, display error message and return false.

       elseif (!$cart_has_paint && $product_is_paint) {
            echo '';

            $validation = false;
        }
    }
    // Otherwise, return true.
    return $validation;
}

This code only works with the miscellaneous category I want to allow only with the Product ID.. not category..

Body:
Assuming that only 1 quantity can be purchased from product A

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // Product id to bought alone
    $product_id_alone = 30;

    // Set variable
    $alone = true;

    // If passed
    if ( $passed ) {
        // If cart is NOT empty when a product is added
        if ( !WC()->cart->is_empty() ) {

            // If product id added = product id alone
            if ( $product_id_alone == $product_id ) {
                $alone = false;
            } else {
                // Generate a unique ID for the cart item
                $product_cart_id = WC()->cart->generate_cart_id( $product_id_alone );

                // Check if product is in the cart
                $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

                // If product is already in cart
                if ( $in_cart ) {
                    $alone = false;
                }
            }
        } else {
            // If product is added when cart is empty but $quantity > 1
            if ( $product_id_alone == $product_id && $quantity > 1 ) {
                $alone = false;
            }
        }
    }

    if ( $alone == false ) {
        // Set error message
        $message = 'PRODUCT A is allow bought alone.';
        wc_add_notice( __( $message, 'woocommerce' ), 'error' );
        $passed = false;

        // Empty the cart
        WC()->cart->empty_cart();

        // Add specific product with quantity 1
        WC()->cart->add_to_cart($product_id_alone, 1 );
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );

Related: Force specific WooCommerce product to be sold in separate order


问:
Can't detach network interfaces
I did the AWS misfits tutorial and I thought the cleanup would be as simple as deleting the Cloud Formation stack. However, items failed to delete so I am trying to clean them up manually to assist the Cloud Formation stack deletion.

I keep getting an error when trying to Detach the network interfaces (I am logged into the root account):

Error detaching network interfaces:

```<code>eni-0047gfhfgh8ab0e: You are not allowed to manage 'ela-attach' attachments.
eni-0f4a46hgfha757e: You are not allowed to manage 'ela-attach' attachments.
</code>```

I am unable to delete my VPC without these being deleted.

The stack as a whole is failing to delete because of the following:

The following resource(s) failed to delete: [InternetGateway,
PublicSubnetTwo, VPC, GatewayAttachement, PublicSubnetOne].

答:
Modify the VPC Endpoint Service to reject VPC Endpoint (deselect
Require acceptance for endpoint) https://docs.aws.amazon.com/vpc/latest/userguide/modify-endpoint-service.html

Delete the VPC Endpoint Service

Continue deleting other resources or try again the stack deletion task in
Cloudformation.

The VPC Endpoint Service deletion is restricted by the no longer existing VPC Endpoint.

Title: Can't detach network interfaces

Body:
I did the AWS misfits tutorial and I thought the cleanup would be as simple as deleting the Cloud Formation stack. However, items failed to delete so I am trying to clean them up manually to assist the Cloud Formation stack deletion.

I keep getting an error when trying to Detach the network interfaces (I am logged into the root account):

Error detaching network interfaces:

eni-0047gfhfgh8ab0e: You are not allowed to manage 'ela-attach' attachments.
eni-0f4a46hgfha757e: You are not allowed to manage 'ela-attach' attachments.

I am unable to delete my VPC without these being deleted.

The stack as a whole is failing to delete because of the following:

The following resource(s) failed to delete: [InternetGateway,
PublicSubnetTwo, VPC, GatewayAttachement, PublicSubnetOne].


问:
React: React-bootstrap, calling function only after user has finished typing
I am utilizing React-Bootstrap for a simple text box component. Right now, the callback is called every time the user edits the textbox, hence it is called back when every letter is called

```<code><Form.Group controlId="Id">
    <Form.Label>Id</Form.Label>
    <Form.Control style = {{marginLeft: 10}} name="Idstate" onChange={this.handleChange} defaultValue = {this.state.idstate}/>

</Form.Group>
</code>```

The code above is my form group

```<code>handleChange = (event) => {
    event.persist()
    const name = event.target.name
    if (name == "Idstate"){
        this.setState({idstate: event.target.value})
        this.state.idstate = event.target.value;
        Apiservice.updatetabletopmenudata(this.tableid, event.target.value, "idstate")
    }
    console.log(this.state)
}
</code>```

This results in a really laggy process, and sometimes the data isn't saved properly

Is there any way for the callback to be executed only after the user has finished editing the text box?

答:
This is because every time a state changes the component re-renders.So, you can avoid unnecessary renders by creating a variable in the state state = {fromOnChange: false} which should always be false and whenever there is a change in the input text field, handle like below

```<code>handleChange(event) {
    this.setState({
      fromOnChange: true,
    });
  }
</code>```

And when the state updates keep a life cycle method that checks wheather to render the component or not :

```<code>shouldComponentUpdate(nextProps, nextState) {
    if (!nextState.fromOnChange) {
      return true;
    } else {
      return false;
    }
  }
</code>```

After that whenever user had finished editing the text fields and submits the data then change the fromOnchange: false so that component renders only on onsubmit.

```<code>handleSubmit(event) {
    //Your API/function call goes here
    // and on success change the state so that it renders
    this.setState({
          fromOnChange: false
        });
  }

</code>```

Body:
I am utilizing React-Bootstrap for a simple text box component. Right now, the callback is called every time the user edits the textbox, hence it is called back when every letter is called

<Form.Group controlId="Id">
    <Form.Label>Id</Form.Label>
    <Form.Control style = {{marginLeft: 10}} name="Idstate" onChange={this.handleChange} defaultValue = {this.state.idstate}/>

</Form.Group>

The code above is my form group

handleChange = (event) => {
    event.persist()
    const name = event.target.name
    if (name == "Idstate"){
        this.setState({idstate: event.target.value})
        this.state.idstate = event.target.value;
        Apiservice.updatetabletopmenudata(this.tableid, event.target.value, "idstate")
    }
    console.log(this.state)
}

This results in a really laggy process, and sometimes the data isn't saved properly

Is there any way for the callback to be executed only after the user has finished editing the text box?

Body:
This is because every time a state changes the component re-renders.So, you can avoid unnecessary renders by creating a variable in the state state = {fromOnChange: false} which should always be false and whenever there is a change in the input text field, handle like below

handleChange(event) {
    this.setState({
      fromOnChange: true,
    });
  }

And when the state updates keep a life cycle method that checks wheather to render the component or not :

shouldComponentUpdate(nextProps, nextState) {
    if (!nextState.fromOnChange) {
      return true;
    } else {
      return false;
    }
  }

After that whenever user had finished editing the text fields and submits the data then change the fromOnchange: false so that component renders only on onsubmit.

handleSubmit(event) {
    //Your API/function call goes here
    // and on success change the state so that it renders
    this.setState({
          fromOnChange: false
        });
  }


问:
Chaining rxjs 6 observables with nested array
I have to do 3 dependent request to an API.

The first retreive an array of user id's.

The second have to iterate over the user id's array and for each retreive an array of project id's related to the user.

The third have to iterate over the project id's array and retreive data related to projects.

I want this kind of result:

```<code>[{'username': 'richard', projects: [{"id": 1, "name": "test"}]}, ...]
</code>```

But i'm totally stuck with mergeMap, forkJoin etc..

The thing i have tried:

```<code>getUserTeamMembers(): Observable<any> {
return this.http.get(`${environment.serverUrl}/user/profil`).pipe(
  mergeMap((teamUsers: any) =>
    this.http.get(
      `api/user/${teamUsers.data._id}/team`
    )
  ),
  mergeMap((teamUsers: any) =>
    forkJoin(
      ...teamUsers.data.map((user: any) =>
        this.http.get(`api/user/${user.id}`)
      )
    )
  ),
  map((res: any) =>
    res
      .map((user: any) => {
        if (user.data) {
          return {
            firstname: user.data.local.firstname,
            lastname: user.data.local.lastname,
            email: user.data.local.email,
            projects: user.data.local.projects,
            language: user.data.local.lang
          };
        }
      })
      .filter((user: any) => user !== undefined)
  ),
  tap(t => console.log(t)),
  catchError(err => throwError(err))
);}
</code>```

I try so many things, but i have no clue where to populate my array of projects which is currently only contains id's, not data related:

```<code>[{'username': 'richard', projects: ['id1', 'id2']}, ...]
</code>```

答:
have made a similar example hope it clear the idea.

of course did't use http instead made it local using of

and stored the final result in an array called results

we have a source to get the list of all users, another source that given the user id it will return the list of this user's projects' ids projectList, and finally a source that give one project id will returns it's details(projcectsDetails)

    let users = of([ 1, 2, 3 ])
    let projectsList = (userId) => of([ userId, userId*2 ])
    let projectsDetails = (projectId) => of({ id: projectId, details: `details about ${projectId}` })

    let results = [];

    users
    .pipe(
      tap(users => {
        users.forEach(userId => results.push({ userId, projects: [] }));

        return users
      }),
      switchMap(users => forkJoin(users.map(userId => projectsList(userId)))),
      switchMap(projectsArray => forkJoin(
          projectsArray.map(
            oneProjectArray =>
            forkJoin(oneProjectArray.map(projectId => projectsDetails(projectId)))
          )
        )
      ),
      tap(projectDetailsArray => {
        projectDetailsArray.forEach((projectsArray, index) =>{
          results[index]['projects'] = [ ...projectsArray ]
        })
      })
    )
    .subscribe(() => console.warn('final',results))

```

<p>explanation</p>

```  1- initalize the result array from the given users
  [
   { userId: X, projcts: [] },
   { userId: Y, projcts: [] },
    ....
  ]

  2- for each give users we want the projects ids he/she has
  so the first switchMap will return (in order)
  [
   [ 1, 2, 3, ...] project ids for the first user,
   [ 8, 12, 63, ...] project ids for the second user,
   ...
  ]

  3- in the second switchMap we iterate over the previous array
  (which is an array that each item in it is an array of projects ids)

  so we needed two forkJoin the outer will iterate over each array of projects ids(the big outer
  array previously mentioned)
  the inner one will iterate over each single project id and resolve it's observable value(which is the
  project details)

  4- finally in the tap process we have an array of array like the 2nd step but this time each
  array has the projects details and not the projects ids

  [
   { userId:1, projects: [ { id:1, details: 'details about 1' }, { id:2, details: 'details about 2' }]},
   { userId:2, projects: [ { id:2, details: 'details about 2' }, { id:4, details: 'details about 4' }]},
   { userId:3, projects: [ { id:3, details: 'details about 3' }, { id:6, details: 'details about 6' }]}
  ]
```

Body:
I have to do 3 dependent request to an API.

The first retreive an array of user id's.

The second have to iterate over the user id's array and for each retreive an array of project id's related to the user.

The third have to iterate over the project id's array and retreive data related to projects.

I want this kind of result:

[{'username': 'richard', projects: [{"id": 1, "name": "test"}]}, ...]

But i'm totally stuck with mergeMap, forkJoin etc..

The thing i have tried:

getUserTeamMembers(): Observable<any> {
return this.http.get(`${environment.serverUrl}/user/profil`).pipe(
  mergeMap((teamUsers: any) =>
    this.http.get(
      `api/user/${teamUsers.data._id}/team`
    )
  ),
  mergeMap((teamUsers: any) =>
    forkJoin(
      ...teamUsers.data.map((user: any) =>
        this.http.get(`api/user/${user.id}`)
      )
    )
  ),
  map((res: any) =>
    res
      .map((user: any) => {
        if (user.data) {
          return {
            firstname: user.data.local.firstname,
            lastname: user.data.local.lastname,
            email: user.data.local.email,
            projects: user.data.local.projects,
            language: user.data.local.lang
          };
        }
      })
      .filter((user: any) => user !== undefined)
  ),
  tap(t => console.log(t)),
  catchError(err => throwError(err))
);}

I try so many things, but i have no clue where to populate my array of projects which is currently only contains id's, not data related:

[{'username': 'richard', projects: ['id1', 'id2']}, ...]

Body:
have made a similar example hope it clear the idea.

of course did't use http instead made it local using of

and stored the final result in an array called results

we have a source to get the list of all users, another source that given the user id it will return the list of this user's projects' ids projectList, and finally a source that give one project id will returns it's details(projcectsDetails)

    let users = of([ 1, 2, 3 ])
    let projectsList = (userId) => of([ userId, userId*2 ])
    let projectsDetails = (projectId) => of({ id: projectId, details: `details about ${projectId}` })

    let results = [];

    users
    .pipe(
      tap(users => {
        users.forEach(userId => results.push({ userId, projects: [] }));

        return users
      }),
      switchMap(users => forkJoin(users.map(userId => projectsList(userId)))),
      switchMap(projectsArray => forkJoin(
          projectsArray.map(
            oneProjectArray =>
            forkJoin(oneProjectArray.map(projectId => projectsDetails(projectId)))
          )
        )
      ),
      tap(projectDetailsArray => {
        projectDetailsArray.forEach((projectsArray, index) =>{
          results[index]['projects'] = [ ...projectsArray ]
        })
      })
    )
    .subscribe(() => console.warn('final',results))

explanation

  1- initalize the result array from the given users
  [
   { userId: X, projcts: [] },
   { userId: Y, projcts: [] },
    ....
  ]

  2- for each give users we want the projects ids he/she has
  so the first switchMap will return (in order)
  [
   [ 1, 2, 3, ...] project ids for the first user,
   [ 8, 12, 63, ...] project ids for the second user,
   ...
  ]

  3- in the second switchMap we iterate over the previous array
  (which is an array that each item in it is an array of projects ids)

  so we needed two forkJoin the outer will iterate over each array of projects ids(the big outer
  array previously mentioned)
  the inner one will iterate over each single project id and resolve it's observable value(which is the
  project details)

  4- finally in the tap process we have an array of array like the 2nd step but this time each
  array has the projects details and not the projects ids

  [
   { userId:1, projects: [ { id:1, details: 'details about 1' }, { id:2, details: 'details about 2' }]},
   { userId:2, projects: [ { id:2, details: 'details about 2' }, { id:4, details: 'details about 4' }]},
   { userId:3, projects: [ { id:3, details: 'details about 3' }, { id:6, details: 'details about 6' }]}
  ]


问:
Notebooks not persistent for Jupyter in Docker container?
Running jupyter in a docker container is a good solution for me, but I'm having trouble getting the notebook files to persist as advertised in the documentation here.

The docs say that after the session is closed and the server shutsdown, the .ipynb (notebook) files should be persisted in the ./work directory however, for me they are not.  I have created notebooks both in the root directory and also in the /work directory which appears in the Jupyter Home page, but neither are to be found after shutdown, and if I restart the server, they are not in the directory list anymore either.  I've tried launching the container in two ways -- first as suggested by the docs (substituting latest for the image tag):

```<code>docker run -p 8888:8888 jupyter/scipy-notebook:latest
</code>```

and second by creating a docker-compose.yml file which allows me to capture the command text options and avoid the token security (which I don't need) as follows:

```<code>version: '3'

  services: # jupyter notebook
    jupyter_notebook:
    image: jupyter/scipy-notebook
    volumes:
      - ./work:/work
    ports:
      - "8888:8888"
    command: "start.sh jupyter notebook --NotebookApp.token=''"
</code>```

I am running under Ubuntu 18.04.1 LTS with docker 18.06.1-ce
I am expecting to find the notebook (at least the one I created in the /work folder) in the host system's ./work folder which is in the directory where I launched docker (or docker-compose), but nothing is there.

Here is a session transcript:

```<code>   s@VC66:ls -la
   -rw-r--r-- 1 steve steve  232 Nov  7 22:45 docker-compose.yml
   drwxr-xr-x 2 steve steve 4096 Nov  7 21:34 work

   s@VC66:~/sambashare/jupyter$ cat docker-compose.yml

   version: '3'

     services:
       jupyter_notebook:
         image: jupyter/scipy-notebook
         volumes:
           - ./work:/work
         ports:
           - "8888:8888"
         command: "start.sh jupyter notebook --NotebookApp.token=''"

   s@VC66:~/sambashare/jupyter$ docker-compose up

   Creating network "jupyter_default" with the default driver
   Creating jupyter_jupyter_notebook_1 ... done
   Attaching to jupyter_jupyter_notebook_1
   jupyter_notebook_1  | Container must be run with group "root" to update passwd file
   jupyter_notebook_1  | Executing the command: jupyter notebook --NotebookApp.token=
   jupyter_notebook_1  | [I 16:08:40.454 NotebookApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
   jupyter_notebook_1  | [W 16:08:40.597 NotebookApp] All authentication is disabled.  Anyone who can connect to this server will be able to run code.
   jupyter_notebook_1  | [I 16:08:40.625 NotebookApp] JupyterLab extension loaded from /opt/conda/lib/python3.6/site-packages/jupyterlab
   jupyter_notebook_1  | [I 16:08:40.625 NotebookApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] Serving notebooks from local directory: /home/jovyan
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] The Jupyter Notebook is running at:
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] http://(62b087792f87 or 127.0.0.1):8888/
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
   jupyter_notebook_1  | [I 16:08:58.820 NotebookApp] 302 GET / (172.21.0.1) 0.48ms
   jupyter_notebook_1  | [I 16:09:07.941 NotebookApp] Creating new file in /work
   jupyter_notebook_1  | [I 16:09:17.360 NotebookApp] Saving file at /work/untitled.txt
   jupyter_notebook_1  | [I 16:09:24.725 NotebookApp] Shutting down on /api/shutdown request.
   jupyter_notebook_1  | [I 16:09:24.727 NotebookApp] Shutting down 0 kernels
   jupyter_jupyter_notebook_1 exited with code 0
   s@VC666:~/sambashare/jupyter$ ls work
   s@VC66:~/sambashare/jupyter$ ls
   docker-compose.yml  work
</code>```

As you can see, it says it saved "untitled.txt" in the /work dir, but upon exiting there's nothing in there.

So to further refine the problem here, I altered the docker-compose.yml file to run a simple python script to create a file in the /work dir and see if it persists.  It does!

```<code>command: "python3 /work/test.py"  # rather than start.sh...
</code>```

here's the python test.py script:

```<code>   import os
   import pytz
   from datetime import datetime

   dir = "/work"
   if not os.path.isdir(dir):
      dir = "" # to test outside docker container...

   nyc_time = datetime.now( pytz.timezone("America/New_York"))
   fname = os.path.join(dir,"test.txt")
   f = open(fname, 'w')
   f.write(f"Test time is {nyc_time}\n")
   f.close()
   exit()
</code>```

This time, after docker-compose up, the work folder contains "test.txt" which contains

Test time is 2018-11-09 11:55:28.472581-05:00

So the docker container mounting the /work dir seems fine -- problem might be something the jupyter image is doing on shutdown perhaps?

答:
I think your misconception is about the docker container using /work. AFAIKs it is /home/jovyan/work instead.

So you can solve your trouble by e.g. this volume mapping

```<code>mkdir -P /your-jupyter/work
docker run -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes -v /your-jupyter/work:home/jovyan/work jupyter/scipy-notebook
</code>```

HTH.

Body:
Running jupyter in a docker container is a good solution for me, but I'm having trouble getting the notebook files to persist as advertised in the documentation here.

The docs say that after the session is closed and the server shutsdown, the .ipynb (notebook) files should be persisted in the ./work directory however, for me they are not.  I have created notebooks both in the root directory and also in the /work directory which appears in the Jupyter Home page, but neither are to be found after shutdown, and if I restart the server, they are not in the directory list anymore either.  I've tried launching the container in two ways -- first as suggested by the docs (substituting latest for the image tag):

docker run -p 8888:8888 jupyter/scipy-notebook:latest

and second by creating a docker-compose.yml file which allows me to capture the command text options and avoid the token security (which I don't need) as follows:

version: '3'

  services: # jupyter notebook
    jupyter_notebook:
    image: jupyter/scipy-notebook
    volumes:
      - ./work:/work
    ports:
      - "8888:8888"
    command: "start.sh jupyter notebook --NotebookApp.token=''"

I am running under Ubuntu 18.04.1 LTS with docker 18.06.1-ce
I am expecting to find the notebook (at least the one I created in the /work folder) in the host system's ./work folder which is in the directory where I launched docker (or docker-compose), but nothing is there.

Here is a session transcript:

   s@VC66:ls -la
   -rw-r--r-- 1 steve steve  232 Nov  7 22:45 docker-compose.yml
   drwxr-xr-x 2 steve steve 4096 Nov  7 21:34 work

   s@VC66:~/sambashare/jupyter$ cat docker-compose.yml

   version: '3'

     services:
       jupyter_notebook:
         image: jupyter/scipy-notebook
         volumes:
           - ./work:/work
         ports:
           - "8888:8888"
         command: "start.sh jupyter notebook --NotebookApp.token=''"

   s@VC66:~/sambashare/jupyter$ docker-compose up

   Creating network "jupyter_default" with the default driver
   Creating jupyter_jupyter_notebook_1 ... done
   Attaching to jupyter_jupyter_notebook_1
   jupyter_notebook_1  | Container must be run with group "root" to update passwd file
   jupyter_notebook_1  | Executing the command: jupyter notebook --NotebookApp.token=
   jupyter_notebook_1  | [I 16:08:40.454 NotebookApp] Writing notebook server cookie secret to /home/jovyan/.local/share/jupyter/runtime/notebook_cookie_secret
   jupyter_notebook_1  | [W 16:08:40.597 NotebookApp] All authentication is disabled.  Anyone who can connect to this server will be able to run code.
   jupyter_notebook_1  | [I 16:08:40.625 NotebookApp] JupyterLab extension loaded from /opt/conda/lib/python3.6/site-packages/jupyterlab
   jupyter_notebook_1  | [I 16:08:40.625 NotebookApp] JupyterLab application directory is /opt/conda/share/jupyter/lab
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] Serving notebooks from local directory: /home/jovyan
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] The Jupyter Notebook is running at:
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] http://(62b087792f87 or 127.0.0.1):8888/
   jupyter_notebook_1  | [I 16:08:40.631 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
   jupyter_notebook_1  | [I 16:08:58.820 NotebookApp] 302 GET / (172.21.0.1) 0.48ms
   jupyter_notebook_1  | [I 16:09:07.941 NotebookApp] Creating new file in /work
   jupyter_notebook_1  | [I 16:09:17.360 NotebookApp] Saving file at /work/untitled.txt
   jupyter_notebook_1  | [I 16:09:24.725 NotebookApp] Shutting down on /api/shutdown request.
   jupyter_notebook_1  | [I 16:09:24.727 NotebookApp] Shutting down 0 kernels
   jupyter_jupyter_notebook_1 exited with code 0
   s@VC666:~/sambashare/jupyter$ ls work
   s@VC66:~/sambashare/jupyter$ ls
   docker-compose.yml  work

As you can see, it says it saved "untitled.txt" in the /work dir, but upon exiting there's nothing in there.

So to further refine the problem here, I altered the docker-compose.yml file to run a simple python script to create a file in the /work dir and see if it persists.  It does!

command: "python3 /work/test.py"  # rather than start.sh...

here's the python test.py script:

   import os
   import pytz
   from datetime import datetime

   dir = "/work"
   if not os.path.isdir(dir):
      dir = "" # to test outside docker container...

   nyc_time = datetime.now( pytz.timezone("America/New_York"))
   fname = os.path.join(dir,"test.txt")
   f = open(fname, 'w')
   f.write(f"Test time is {nyc_time}\n")
   f.close()
   exit()

This time, after docker-compose up, the work folder contains "test.txt" which contains

Test time is 2018-11-09 11:55:28.472581-05:00

So the docker container mounting the /work dir seems fine -- problem might be something the jupyter image is doing on shutdown perhaps?

Body:
I think your misconception is about the docker container using /work. AFAIKs it is /home/jovyan/work instead.

So you can solve your trouble by e.g. this volume mapping

mkdir -P /your-jupyter/work
docker run -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes -v /your-jupyter/work:home/jovyan/work jupyter/scipy-notebook

HTH.


问:
What are the relations between a kernel control path a kernel thread?
Understanding The Linux Kernel says:

A kernel control path denotes the sequence of instructions executed by the kernel to
  handle a system call, an exception, or an interrupt.

and

Besides user processes, Unix systems include a few privileged processes called kernel
  threads with the following characteristics:

• They run in Kernel Mode in the kernel address space.

• They do not interact with users, and thus do not require terminal
  devices.

• They are usually created during system startup and remain alive
  until the system is shut down.

What are the relations between the two concepts: a kernel control
path a kernel thread?

Is a kernel control path a kernel thread?

Is a kernel thread a kernel control path?

If I am correct, a kernel thread is represented as a task_struct
object.

So is a kernel control path?

If not, what kinds of kernel control paths can be and what kinds
can't be?

If I am correct, a kernel thread can be scheduled together with processes.

Can a kernel control path? If not, what kinds of kernel control paths can be and what kinds can't be?

答:
A kernel control path is the sequence of instructions executed by a kernel to handle a system call, an interrupt or an exception.

The kernel is the core of an operating system, and it controls virtually everything that occurs on a computer. An interrupt is a signal to the kernel that an event has occurred. Hardware interrupts are initiated by hardware devices, including the keyboard, the mouse, a printer or a disk drive. Interrupt signals initiated by programs are called software interrupts or exceptions.

In the most simple situation, the CPU executes a kernel control path sequentially, that is, beginning with the first instruction and ending with the last instruction.

source: http://www.linfo.org/kernel_control_path.html