问:
How to place divs under one another while using flex to avoid the extra gap?
I have created a webpage where I want the layout to be like the screenshot. Basically, I want the elements to begin under the first element if there is space. I have added the current css and html for the page.

Is it possible? Could someone help, please.
Thanks!

.main {
    width: 1024px;
}
.container {
    display: flex;
}
.container div {
    border: 1px solid #444;
    margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<div class="main">
  <div class="container">
    <div class="one"> First element </div>
    <div class="two"> Second element<br />
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div>
    <div class="three"> Third element </div>
    <div class="forth"> Forth element </div>
    <div class="five"> Five element </div>
  </div>
</div>
</body>
</html></code>```

答:
A solution based on your screenshot. Essentially you should nest both sides in their own respective divs. Then you can flex the left side and use flex-direction: column; with gap to space them out. Then you can take your parent main which has everything nested inside of it, and use a standard display: flex; with that element.

.main {
  width: 1024px;
  display: flex;
  align-items: center;
}

.left {
  display: flex;
  flex-direction: column;
  white-space: nowrap;
  gap: 25px;
}

.one,
.two,
.three,
.forth {
  border: 1px solid #444;
  margin: 5px;
}

.right {
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
</head>

<body>
  <div class="main">
    <div class="left">
      <div class="one"> First element </div>
      <div class="three"> Third element </div>
      <div class="forth"> Forth element </div>

    </div>
    <div class="right">
      <div class="two"> Second element<br>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
        <p>
      </div>
    </div>
  </div>
</body>

</html></code>```

Body:
I have created a webpage where I want the layout to be like the screenshot. Basically, I want the elements to begin under the first element if there is space. I have added the current css and html for the page.

Is it possible? Could someone help, please.
Thanks!

.main {
    width: 1024px;
}
.container {
    display: flex;
}
.container div {
    border: 1px solid #444;
    margin: 10px;
}

<!doctype html>

<meta charset="utf-8">
<title>Untitled Document</title>

 First element

 Second element

      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

 Third element

 Forth element

 Five element

Body:
A solution based on your screenshot. Essentially you should nest both sides in their own respective divs. Then you can flex the left side and use flex-direction: column; with gap to space them out. Then you can take your parent main which has everything nested inside of it, and use a standard display: flex; with that element.

.main {
  width: 1024px;
  display: flex;
  align-items: center;
}

.left {
  display: flex;
  flex-direction: column;
  white-space: nowrap;
  gap: 25px;
}

.one,
.two,
.three,
.forth {
  border: 1px solid #444;
  margin: 5px;
}

.right {
  height: 100%;
}

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Untitled Document</title>
</head>

<body>
  <div class="main">
    <div class="left">
      <div class="one"> First element </div>
      <div class="three"> Third element </div>
      <div class="forth"> Forth element </div>

    </div>
    <div class="right">
      <div class="two"> Second element<br>
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
          It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
          desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</p>
        <p>
      </div>
    </div>
  </div>
</body>

</html>


来源: stackexchange

问:
multiple conditional renderings inside a map function
Hi there I'm looking if there's a better way to render my todos

I have this

```<code>         {
            todos.map((todo) => (

                todo.status === 1 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (
                    <p>{todo.title}</p>
                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (
                    <p>{todo.title}</p>
                )
            ))
        }
</code>```

Is there a way to do this?

Thanks a lot

答:
I'm assuming they really are all right next to each other like that. If so:, either:

Sort todos before rendering

Use an outer loop of status values

Sort

Sort the todos array, ideally just the once prior to rendering/re-rendering.

```<code>todos.sort((a, b) => a.status - b.status);
</code>```

Note that this assumes there are only those three status values. If there are others, you may want to have a separate filtered and sorted array that you rebuild when todos changes.

Outer loop

```<code>{[1, 2, 3].map(
    status => todos.map(
        todo => todo.status === status && <p>{todo.title}</p>
    )
)}
</code>```

Side note: Those p elements need keys.

ContentLicense: CC BY-SA 4.0

Body:
Hi there I'm looking if there's a better way to render my todos

I have this

         {
            todos.map((todo) => (

                todo.status === 1 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 2 && (

{todo.title}

                )
            ))
        }
        {
            todos.map((todo) => (
                todo.status === 3 && (

{todo.title}

                )
            ))
        }

Is there a way to do this?

Thanks a lot

Body:
I'm assuming they really are all right next to each other like that. If so:, either:

Sort todos before rendering

Use an outer loop of status values

Sort

Sort the todos array, ideally just the once prior to rendering/re-rendering.

todos.sort((a, b) => a.status - b.status);

Note that this assumes there are only those three status values. If there are others, you may want to have a separate filtered and sorted array that you rebuild when todos changes.

Outer loop

{[1, 2, 3].map(
    status => todos.map(
        todo => todo.status === status && <p>{todo.title}</p>
    )
)}

Side note: Those p elements need keys.


问:
How to call DynamicObject.TryGetMember directly?
I'm implementing a general purpose function to extract a value from an arbitrary provided dynamic object, but don't know how to call TryGetMember because it requires a GetMemberBinder which is abstract, hence I cannot create it.
Sample...

```<code>public object GetValue(DynamicObject Source, string FieldName)
{
    object Result = null;
    GetMemberBinder Binder = x;  // What object must be provided?
    Binder.Name = FieldName;
    if (Source.TryGetMember(Binder, out Result))
       return Result;

    throw new Exception("The field '" + FieldName + "' not exists");
}
</code>```

Is there an already existent concrete descendant of GetMemberBinder ready for use? or a guideline to create my own implementation?

答:
I'm not sure if there's any method in the framework that actually returns a GetMemberBinder, but it doesn't matter - that isn't the correct way to invoke a dynamic member by name.

What you actually need to do is create a call site.  The method looks like this:

```<code>static object GetDynamicMember(object obj, string memberName)
{
    var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(),
        new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
    var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
    return callsite.Target(callsite, obj);
}
</code>```

Note that Binder.GetMember creates a CallSiteBinder, not a GetMemberBinder. Just to be 100% clear.  This method will throw a RuntimeBinderException if the internal call to TryGetMember fails, so you do not need to check the result. If you don't want callers to see the RuntimeBinderException then wrap it in your own try/catch.

Dynamic dispatch is complex, at least relative to reflection on static types. Since the CLR is not actually dynamically typed, C# has to actually instantiate a compiler to figure out how to execute the member/method. That's creating a call site. As far as I know, you have to do this, which is why every Binder method returns a CallSiteBinder and you can't instantiate any of the binders directly.

Note that the DLR does some sort of call site caching, but I'm not sure if the automatic caching covers this scenario. There's a good chance you'll want to save your call site for future calls to avoid the overhead of constant recompilation.

P.S. If you are using (or can use) ExpandoObject instead of DynamicObject then keep in mind that it implements IDictionary<string, object>, so you don't need to do any of this. Just cast it to the dictionary type and check if the property exists.  I would only ever use DynamicObject over ExpandoObject if I were doing something a lot more complicated than simply adding members at runtime, i.e. changing the actual behaviour based on the runtime binder.

ContentLicense: CC BY-SA 2.5

Body:
I'm implementing a general purpose function to extract a value from an arbitrary provided dynamic object, but don't know how to call TryGetMember because it requires a GetMemberBinder which is abstract, hence I cannot create it.
Sample...

public object GetValue(DynamicObject Source, string FieldName)
{
    object Result = null;
    GetMemberBinder Binder = x;  // What object must be provided?
    Binder.Name = FieldName;
    if (Source.TryGetMember(Binder, out Result))
       return Result;

    throw new Exception("The field '" + FieldName + "' not exists");
}

Is there an already existent concrete descendant of GetMemberBinder ready for use? or a guideline to create my own implementation?

Body:
I'm not sure if there's any method in the framework that actually returns a GetMemberBinder, but it doesn't matter - that isn't the correct way to invoke a dynamic member by name.

What you actually need to do is create a call site.  The method looks like this:

static object GetDynamicMember(object obj, string memberName)
{
    var binder = Binder.GetMember(CSharpBinderFlags.None, memberName, obj.GetType(),
        new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });
    var callsite = CallSite<Func<CallSite, object, object>>.Create(binder);
    return callsite.Target(callsite, obj);
}

Note that Binder.GetMember creates a CallSiteBinder, not a GetMemberBinder. Just to be 100% clear.  This method will throw a RuntimeBinderException if the internal call to TryGetMember fails, so you do not need to check the result. If you don't want callers to see the RuntimeBinderException then wrap it in your own try/catch.

Dynamic dispatch is complex, at least relative to reflection on static types. Since the CLR is not actually dynamically typed, C# has to actually instantiate a compiler to figure out how to execute the member/method. That's creating a call site. As far as I know, you have to do this, which is why every Binder method returns a CallSiteBinder and you can't instantiate any of the binders directly.

Note that the DLR does some sort of call site caching, but I'm not sure if the automatic caching covers this scenario. There's a good chance you'll want to save your call site for future calls to avoid the overhead of constant recompilation.

P.S. If you are using (or can use) ExpandoObject instead of DynamicObject then keep in mind that it implements IDictionary<string, object>, so you don't need to do any of this. Just cast it to the dictionary type and check if the property exists.  I would only ever use DynamicObject over ExpandoObject if I were doing something a lot more complicated than simply adding members at runtime, i.e. changing the actual behaviour based on the runtime binder.

ContentLicense: CC BY-SA 3.0


问:
Input from the use in a try/except block

List item

i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks

Sloved!!

import sys
while True:

difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:

```<code>         if difficulty == '1':
            print('Easy game mode is set!')
         elif difficulty =='2':
            print('Hard game mode is set!')
         elif difficulty =='quit':
            print('Sheeeeeeeeeeeeeeesh')

      except:
         continue
      if difficulty == '1' or difficulty =='2':
         break
      elif difficulty == 'quit':
         sys.exit('byeeeee')
         break
    #elif difficulty
      else:
         print('invalid ')
</code>```

答:
You are storing the user input in uppercase for difficulty variable.
And in if condition verifying in lowercase.
So remove the upper() from
input("Choose difficulty 1 for easy 2 for hard: ").upper()

Body:
List item

i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks

Sloved!!

import sys
while True:

difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:

         if difficulty == '1':
            print('Easy game mode is set!')
         elif difficulty =='2':
            print('Hard game mode is set!')
         elif difficulty =='quit':
            print('Sheeeeeeeeeeeeeeesh')

      except:
         continue
      if difficulty == '1' or difficulty =='2':
         break
      elif difficulty == 'quit':
         sys.exit('byeeeee')
         break
    #elif difficulty
      else:
         print('invalid ')


问:
Gradle dependency for springdoc-openapi-ui
I am trying to use springdoc-openapi-ui using gradle dependency.

Maven

```<code> <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.4.3</version>
   </dependency>
</code>```

Gradle

```<code>    plugins {
    id 'org.springframework.boot' version '2.3.1.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'fete.bird'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'
compileJava {
    options.compilerArgs += ["--enable-preview"]
}
repositories {
    jcenter()
    mavenCentral()
}
ext {
    set('springCloudVersion', "Hoxton.SR6")
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'org.springdoc:springdoc-openapi-ui'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.kafka:spring-kafka'
    implementation 'org.projectlombok:lombok'
}
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

test {
    useJUnitPlatform()
}
</code>```

Error

```<code>Could not find org.springdoc:springdoc-openapi-ui:.
Required by:
    project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
</code>```

What is the repository for the gradle?

答:
implementation 'org.springdoc:springdoc-openapi-ui' fail with following error Could not find org.springdoc:springdoc-openapi-ui

While following worked

implementation 'org.springdoc:springdoc-openapi-ui:1.6.6'

Body:
I am trying to use springdoc-openapi-ui using gradle dependency.

Maven

 <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-ui</artifactId>
      <version>1.4.3</version>
   </dependency>

Gradle

    plugins {
    id 'org.springframework.boot' version '2.3.1.RELEASE'
    id 'io.spring.dependency-management' version '1.0.9.RELEASE'
    id 'java'
}

group = 'fete.bird'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '14'
compileJava {
    options.compilerArgs += ["--enable-preview"]
}
repositories {
    jcenter()
    mavenCentral()
}
ext {
    set('springCloudVersion', "Hoxton.SR6")
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'org.springdoc:springdoc-openapi-ui'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    implementation 'org.springframework.cloud:spring-cloud-starter-config'
    implementation 'org.springframework.kafka:spring-kafka'
    implementation 'org.projectlombok:lombok'
}
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

test {
    useJUnitPlatform()
}

Error

Could not find org.springdoc:springdoc-openapi-ui:.
Required by:
    project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

What is the repository for the gradle?


问:
How do I access properties of non-fired LinkButtons in an ASP RepeaterControl?
I have a navigation bar which is dynamically populated with LinkButtons by an ASP repeaterControl.

I have no problem accessing, and setting properties for the clicked LinkButton. This I can do using the sender object from the fired LinkButton. Once a LinkButton is clicked, it is highlighted in bold.

My problem is to clear the bold property of the previously clicked linkButton when a new LinkButton ( another RepeaterItem within the same repeater) is clicked.

Any ideas on this, please? Many thanks!

ps.
I cannot access the buttons through their ID, since they all have the same ID within the repeater.

I have unique arguments on each RepeaterItem (CommandArgument), but when I try to iterate through all linkbuttons, only static linkbuttons are found, none inside the repeater. See below:

```<code>Dim c As Control
For Each c In Form1.Controls
    If TypeOf c Is LinkButton Then
        MsgBox(DirectCast(c, LinkButton).CommandArgument)
    End If
Next c
</code>```

答:
Try this:</p>

```<code>For each item as RepeaterItem in YourRepeaterControl.Items

    Dim button as LinkButton = item.FindControl("YourLinkButtonId")
    If button IsNot Nothing Then
        'Do whatever you want here
    End If

Next
</code>```

Body:
I have a navigation bar which is dynamically populated with LinkButtons by an ASP repeaterControl.

I have no problem accessing, and setting properties for the clicked LinkButton. This I can do using the sender object from the fired LinkButton. Once a LinkButton is clicked, it is highlighted in bold.

My problem is to clear the bold property of the previously clicked linkButton when a new LinkButton ( another RepeaterItem within the same repeater) is clicked.

Any ideas on this, please? Many thanks!

ps.
I cannot access the buttons through their ID, since they all have the same ID within the repeater.

I have unique arguments on each RepeaterItem (CommandArgument), but when I try to iterate through all linkbuttons, only static linkbuttons are found, none inside the repeater. See below:

Dim c As Control
For Each c In Form1.Controls
    If TypeOf c Is LinkButton Then
        MsgBox(DirectCast(c, LinkButton).CommandArgument)
    End If
Next c

Body:
Try this:

For each item as RepeaterItem in YourRepeaterControl.Items

    Dim button as LinkButton = item.FindControl("YourLinkButtonId")
    If button IsNot Nothing Then
        'Do whatever you want here
    End If

Next


问:
Deserialize only one object from JSON array in Java
I get JSON response from API:

```<code>{
  "value": [{
    "some-field": "blah-blah",
    ...
  }]
}
</code>```

There is always one object in the array so I don't want to store a pojo like this:

```<code>public class Foo {
    private List<InnerClass> value;
}
</code>```

but like this:

```<code>public class Foo {
    private String field1;
    private String field2;
...
}
</code>```

How do I create custom deserializer for it?

I have tried the following:

```<code>public class CustomDeserializer extends StdDeserializer<Foo> {

    public CustomDeserializer(Class<Foo> clazz) {
        super(clazz);
    }

    public CustomDeserializer() {
        this(null);
    }

    @Override
    public Foo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {

        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        String s = jsonNode.get("value").get(0).toString();
        Foo obj = new ObjectMapper().readValue(s, Foo.class);
        return obj;
    }
}
</code>```

but there is some kind of circle issues and it doesn't work.

答:
The problem comes from this line in you custom deserializer:

```<code>Foo obj = new ObjectMapper().readValue(s, Foo.class);
</code>```

When you do it like this your CustomDeserializer is called a second time, but now with a json in different format and it can't handle it. To be more precise, it can't find the property named value. So you have two options for fixing it:

Create Foo and set fields manually

```<code>public class CustomDeserializer extends StdDeserializer<Foo> {

    public CustomDeserializer(Class<Foo> clazz) {
        super(clazz);
    }

    public CustomDeserializer() {
        this(null);
    }

    @Override
    public Foo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        JsonNode valueNode = jsonNode.get("value").get(0);
        Foo obj = new Foo();
        obj.setField1(valueNode.get("field1").asText());
        obj.setField2(valueNode.get("field2").asText());
        return obj;
    }
}
</code>```

To keep CustomDeserializer as is, you need to register your deserializer only with the ObjectMapper instance, which does the actual deserializing of the initial json and don't use annotations on Foo to specify deserializer.

```<code>ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Foo.class, new CustomDeserializer());
mapper.registerModule(module);
</code>```

As a side note, if you choose second option, Foo obj = new ObjectMapper().readValue(s, Foo.class); - this line creates new instance of ObjectMapper every time you deserialize. It would be better to keep an instance of ObjectMapper as a static field, for example.

Body:
I get JSON response from API:

{
  "value": [{
    "some-field": "blah-blah",
    ...
  }]
}

There is always one object in the array so I don't want to store a pojo like this:

public class Foo {
    private List<InnerClass> value;
}

but like this:

public class Foo {
    private String field1;
    private String field2;
...
}

How do I create custom deserializer for it?

I have tried the following:

public class CustomDeserializer extends StdDeserializer<Foo> {

    public CustomDeserializer(Class<Foo> clazz) {
        super(clazz);
    }

    public CustomDeserializer() {
        this(null);
    }

    @Override
    public Foo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {

        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        String s = jsonNode.get("value").get(0).toString();
        Foo obj = new ObjectMapper().readValue(s, Foo.class);
        return obj;
    }
}

but there is some kind of circle issues and it doesn't work.

Body:
The problem comes from this line in you custom deserializer:

Foo obj = new ObjectMapper().readValue(s, Foo.class);

When you do it like this your CustomDeserializer is called a second time, but now with a json in different format and it can't handle it. To be more precise, it can't find the property named value. So you have two options for fixing it:

Create Foo and set fields manually

public class CustomDeserializer extends StdDeserializer<Foo> {

    public CustomDeserializer(Class<Foo> clazz) {
        super(clazz);
    }

    public CustomDeserializer() {
        this(null);
    }

    @Override
    public Foo deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        JsonNode valueNode = jsonNode.get("value").get(0);
        Foo obj = new Foo();
        obj.setField1(valueNode.get("field1").asText());
        obj.setField2(valueNode.get("field2").asText());
        return obj;
    }
}

To keep CustomDeserializer as is, you need to register your deserializer only with the ObjectMapper instance, which does the actual deserializing of the initial json and don't use annotations on Foo to specify deserializer.

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Foo.class, new CustomDeserializer());
mapper.registerModule(module);

As a side note, if you choose second option, Foo obj = new ObjectMapper().readValue(s, Foo.class); - this line creates new instance of ObjectMapper every time you deserialize. It would be better to keep an instance of ObjectMapper as a static field, for example.


问:
ValueError: Length mismatch: Expected axis has X elements, new values have Y elements
I try to fill missing value with the most appeared one in its group .
Code :

```<code>f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan
s = df.groupby('VehicleType')['FuelType'].transform(f)
df['FuelType']=df['FuelType'].fillna(s)
</code>```

Error: ValueError: Length mismatch: Expected axis has 316879 elements, new values have 354369 elements

Data sample :

Possible solutions: I think that maybe the VehicleType data has missing values, therefore it gives an error .Because when I use another column that has no missing values, it works. But I have to use VehicleType for this task .

答:
This problem appears to have been fixed in newer versions of pandas. (Works without issue on 1.4.0). But for older versions of pandas...

The issue is caused by NaN values in your grouping column together with .transform. To get around this problem instead of grouping by the column name, group by the Series where you first .fillna() with some value that doesn't occur in  that column. This will succeed in assiging the NaN 'VehicleType' rows with the modal value for 'FuelType' among those NaN rows.

I'll assign the result as a separate column below for illustration.

Sample data to reproduce problem

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'VehicleType': ['a', 'b', 'c', 'a', np.NaN, np.NaN, np.NaN, 'a'],
                   'FuelType': ['Y', np.NaN, 'Y', 'X', 'Z', 'Z', 'Y', 'X']})
f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan

df.groupby('VehicleType')['FuelType'].transform(f)
#ValueError: Length mismatch: Expected axis has 5 elements, new values have 8 elements
</code>```

Solution

```<code>df['FuelType_mode'] = (df.groupby(df['VehicleType'].fillna('SPECIAL_MISSING'))
                         ['FuelType'].transform(f))
</code>```

```<code>print(df)
  VehicleType FuelType FuelType_mode
0           a        Y             X
1           b      NaN           NaN
2           c        Y             Y
3           a        X             X
4         NaN        Z             Z
5         NaN        Z             Z
6         NaN        Y             Z
7           a        X             X
</code>```

With newer versions of pandas the dropna arg can be used to specify whether you want to ignore NaN rows entirely when you group, or if you want to consider them their own unique group. Depending upon your desired behavior you would do:

```<code># Still assigns NAN Vehicle Typethe modal Fuel Type.
# Same logic as above
df['FT3'] = df.groupby('VehicleType', dropna=False)['FuelType'].transform(f)

# NAN Vehicle Types get NAN Fuel
df['FT4'] = df.groupby('VehicleType')['FuelType'].transform(f)

  VehicleType FuelType FuelType_mode  FT3  FT4
0           a        Y             X    X    X
1           b      NaN           NaN  NaN  NaN
2           c        Y             Y    Y    Y
3           a        X             X    X    X
4         NaN        Z             Z    Z  NaN
5         NaN        Z             Z    Z  NaN
6         NaN        Y             Z    Z  NaN
7           a        X             X    X    X
</code>```

Body:
I try to fill missing value with the most appeared one in its group .
Code :

f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan
s = df.groupby('VehicleType')['FuelType'].transform(f)
df['FuelType']=df['FuelType'].fillna(s)

Error: ValueError: Length mismatch: Expected axis has 316879 elements, new values have 354369 elements

Data sample :

Possible solutions: I think that maybe the VehicleType data has missing values, therefore it gives an error .Because when I use another column that has no missing values, it works. But I have to use VehicleType for this task .

Body:
This problem appears to have been fixed in newer versions of pandas. (Works without issue on 1.4.0). But for older versions of pandas...

The issue is caused by NaN values in your grouping column together with .transform. To get around this problem instead of grouping by the column name, group by the Series where you first .fillna() with some value that doesn't occur in  that column. This will succeed in assiging the NaN 'VehicleType' rows with the modal value for 'FuelType' among those NaN rows.

I'll assign the result as a separate column below for illustration.

Sample data to reproduce problem

import pandas as pd
import numpy as np

df = pd.DataFrame({'VehicleType': ['a', 'b', 'c', 'a', np.NaN, np.NaN, np.NaN, 'a'],
                   'FuelType': ['Y', np.NaN, 'Y', 'X', 'Z', 'Z', 'Y', 'X']})
f = lambda x: x.mode().iat[0] if x.notna().any() else np.nan

df.groupby('VehicleType')['FuelType'].transform(f)
#ValueError: Length mismatch: Expected axis has 5 elements, new values have 8 elements

Solution

df['FuelType_mode'] = (df.groupby(df['VehicleType'].fillna('SPECIAL_MISSING'))
                         ['FuelType'].transform(f))

print(df)
  VehicleType FuelType FuelType_mode
0           a        Y             X
1           b      NaN           NaN
2           c        Y             Y
3           a        X             X
4         NaN        Z             Z
5         NaN        Z             Z
6         NaN        Y             Z
7           a        X             X

With newer versions of pandas the dropna arg can be used to specify whether you want to ignore NaN rows entirely when you group, or if you want to consider them their own unique group. Depending upon your desired behavior you would do:

# Still assigns NAN Vehicle Typethe modal Fuel Type.
# Same logic as above
df['FT3'] = df.groupby('VehicleType', dropna=False)['FuelType'].transform(f)

# NAN Vehicle Types get NAN Fuel
df['FT4'] = df.groupby('VehicleType')['FuelType'].transform(f)

  VehicleType FuelType FuelType_mode  FT3  FT4
0           a        Y             X    X    X
1           b      NaN           NaN  NaN  NaN
2           c        Y             Y    Y    Y
3           a        X             X    X    X
4         NaN        Z             Z    Z  NaN
5         NaN        Z             Z    Z  NaN
6         NaN        Y             Z    Z  NaN
7           a        X             X    X    X


问:
How to elegantly check if a number is within a range?
How can I do this elegantly with C#?

For example, a number can be between 1 and 100.

I know a simple if (x >= 1 && x <= 100) would suffice; but with a lot of syntax sugar and new features constantly added to C#/.Net this question is about more idiomatic (one can all it elegance) ways to write that.

Performance is not a concern, but please add performance note to solutions that are not O(1) as people may copy-paste the suggestions.

答:
Ok I'll play along. So many answers already but maybe still room for some other novelties:

(obviously don't actually use these)

```<code>    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = Math.Clamp(num, min, max) == num;
</code>```

Or

```<code>    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = num switch { < min => false, > max => false, _ => true };
</code>```

Or

```<code>    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = num is >= min and <= max;
</code>```

OK maybe you could use that last one.

OK one more

```<code>    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = Enumerable.Range(min, max-min).Contains(num);
</code>```

Body:
Ok I'll play along. So many answers already but maybe still room for some other novelties:

(obviously don't actually use these)

    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = Math.Clamp(num, min, max) == num;

Or

    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = num switch { < min => false, > max => false, _ => true };

Or

    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = num is >= min and <= max;

OK maybe you could use that last one.

OK one more

    var num = 7;
    const int min = 5;
    const int max = 10;
    var inRange = Enumerable.Range(min, max-min).Contains(num);


问:
How to generate combinations of elements of different lists?
I have a list of lists that goes like

```<code>[[1,2,3],[3,4,5],[5,6,7,8]]
</code>```

I want to create a program/function that creates a combinations like

```<code>1,3,5
1,3,6
1,3,7
1,3,8
1,4,5
1,4,6
.
.
.
</code>```

If there's a way you can do it without using the itertools module, that would be even more appreciated.

答:
Convert it into linear list and use combinations

from itertools import combinations
linearArr = [ele for ele in row for row in [[1,2,3],[3,4,5],[5,6,7,8]]]
for comb in combinations(linearArr,3):
    print(comb)

```

Body:
I have a list of lists that goes like

[[1,2,3],[3,4,5],[5,6,7,8]]

I want to create a program/function that creates a combinations like

1,3,5
1,3,6
1,3,7
1,3,8
1,4,5
1,4,6
.
.
.

If there's a way you can do it without using the itertools module, that would be even more appreciated.


问:
How to run a pulled images - docker
I'm trying to run a pulled image without any success.
I pulled an image from AWS using the Image URI.

when I run docker images I can see my pulled image:

```<code>REPOSITORY                                           TAG             IMAGE ID            CREATED             SIZE
alpine                                               3.9             055936d39205        3 weeks ago         5.53MB
24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools    dab-1.1.0slim   f994713b61cb        3 weeks ago         110MB
ubuntu                                               16.04           a3551444fc85        5 weeks ago         119MB
anapsix/alpine-java                                  8               745575fbfe52        3 months ago        126MB
</code>```

I'm new at dockers, but from what I understand after pulling no need to build it, just run it but when I tried to run it like so: docker run 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools I get the below message:

```<code>Unable to find image '24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools:latest' locally
docker: Error response from daemon: pull access denied for 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools, repository does not exist or may require 'docker login'.
</code>```

So I tried to build it like so: docker build -t 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools
and got the message:

```<code>"docker build" requires exactly 1 argument.
See 'docker build --help'.
</code>```

What is the problem?
How can I run a pulled image from AWS?

答:
Adding some information that hasn't been covered above for anyone else.

Checking what docker images are available with docker ls -al will add the image name to the terminal output allowing docker run name which is similar to using the image ID Sree has given in his answer. However, docker default names are human-readable and are created automatically when the container is built.

Title: How to run a pulled images - docker

Body:
I'm trying to run a pulled image without any success.
I pulled an image from AWS using the Image URI.

when I run docker images I can see my pulled image:

REPOSITORY                                           TAG             IMAGE ID            CREATED             SIZE
alpine                                               3.9             055936d39205        3 weeks ago         5.53MB
24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools    dab-1.1.0slim   f994713b61cb        3 weeks ago         110MB
ubuntu                                               16.04           a3551444fc85        5 weeks ago         119MB
anapsix/alpine-java                                  8               745575fbfe52        3 months ago        126MB

I'm new at dockers, but from what I understand after pulling no need to build it, just run it but when I tried to run it like so: docker run 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools I get the below message:

Unable to find image '24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools:latest' locally
docker: Error response from daemon: pull access denied for 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools, repository does not exist or may require 'docker login'.

So I tried to build it like so: docker build -t 24325.dkr.ecr.us-east-1.amazonaws.com/lm/rd/tools
and got the message:

"docker build" requires exactly 1 argument.
See 'docker build --help'.

What is the problem?
How can I run a pulled image from AWS?


问:
Salesforce Camel Kafka Connector converting message to weird format
We are producing events from Salesforce to Kafka via something in SF called platform events.  To get these events into Kafka, we are using the Salesforce Kafka Source Connector from Camel.  Documentation for this Kafka connector can be found here:

https://camel.apache.org/camel-kafka-connector/latest/reference/connectors/camel-salesforce-kafka-source-connector.html

The events generated from Salesforce are in JSON format.  The format looks something like this:

```<code>{
 "data": {
    "schema": "NhgeDyLTvEyVPQ9uOzDqeQ",
    "payload": {
        "AccountId__c": "00119000013q2g3AAA",
        "AccountUUID__c": "4654fefb-e3d1-4b08-a4e2-5dabaa504abb",
        "GUID__c": null,
        "CreatedById": "0056g000005YeBAAA0",
        "CreatedDate": "2021-10-10T15:24:43.819Z"
    },
    "event": {
        "replayId": "1256093"
    }
},
 "channel": "/event/Order_Completed__e"
}
</code>```

This leads us to our issue.  We are using the following configuration for our source connector:

```<code>{
"name": "sf_order_p_event_connector",
"config": {
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "key.converter.schemas.enable": "true",
    "value.converter": "org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "true",
    "connector.class": "org.apache.camel.kafkaconnector.salesforce.CamelSalesforceSourceConnector",
    "camel.component.salesforce.loginUrl": "<redacted>",
    "camel.component.salesforce.instanceUrl": "<redacted>",
    "topics": "<redacted>",
    "camel.source.endpoint.rawPayload": "true",
    "camel.source.path.topicName": "/event/Order_Completed__e",
    "camel.source.endpoint.replayId": "-1",
    "camel.component.salesforce.authenticationType": "USERNAME_PASSWORD",
    "camel.component.salesforce.clientId": "<redacted",
    "camel.component.salesforce.clientSecret": "<redacted>",
    "camel.component.salesforce.password": "<redacted5",
    "camel.component.salesforce.userName": "<redacted>",
    "camel.source.endpoint.apiVersion": "52.0"
}
}
</code>```

When using this value.converter from the configuration above, we get the following exception:

ERROR [sf_account_change_connector|task-0] WorkerSourceTask{id=sf_account_change_connector-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted (org.apache.kafka.connect.runtime.WorkerTask:184)
org.apache.kafka.connect.errors.ConnectException: Tolerance exceeded in error handler
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:206)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
at org.apache.kafka.connect.runtime.WorkerSourceTask.convertTransformedRecord(WorkerSourceTask.java:298)
at org.apache.kafka.connect.runtime.WorkerSourceTask.sendRecords(WorkerSourceTask.java:324)
at org.apache.kafka.connect.runtime.WorkerSourceTask.execute(WorkerSourceTask.java:248)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:182)
at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:231)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at org.apache.kafka.connect.json.JsonConverter.convertToJson(JsonConverter.java:677)
at org.apache.kafka.connect.json.JsonConverter.convertToJsonWithEnvelope(JsonConverter.java:592)
at org.apache.kafka.connect.json.JsonConverter.fromConnectData(JsonConverter.java:346)
at org.apache.kafka.connect.storage.Converter.fromConnectData(Converter.java:63)
at org.apache.kafka.connect.runtime.WorkerSourceTask.lambda$convertTransformedRecord$2(WorkerSourceTask.java:298)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
... 11 more

It seems it cannot convert whatever value is coming through to Kafka into JSON.  I changed value.converter to "org.apache.kafka.connect.storage.StringConverter" to see what I am actually getting in the topic.  Once I did that, this is the message I saw coming through to Kafka from Salesforce:

```<code>{data={schema=NhgeDyLTvEyVPQ9uOzDqeQ, payload={AccountId__c=00119000013q2g3AAA,
AccountUUID__c=4654fefb-e3d1-4b08-a4e2-5dabaa504abb, GUID__c=null,
CreatedById=0056g000005YeBAAA0, CreatedDate=2021-10-10T15:24:43.819Z}, event=
{replayId=1256093}}, channel=/event/Order_Completed__e}
</code>```

It seems Kafka is not processing this as JSON but as a key=value (whatever this is) type of value.  My question is, why am I seeing this type of payload and not JSON?  Also, what configuration (if any) for the source connector can I use to get past this and perhaps convert the value into JSON?  I need this value in JSON for my faust agent to properly process it.  I have tried multiple different configurations for the source connector but nothing seems to be working.

Any help would be appreciated.  Thank you in advance!

答: please use camel.source.endpoint.rawPayload=true in your connector config

Body:
We are producing events from Salesforce to Kafka via something in SF called platform events.  To get these events into Kafka, we are using the Salesforce Kafka Source Connector from Camel.  Documentation for this Kafka connector can be found here:

https://camel.apache.org/camel-kafka-connector/latest/reference/connectors/camel-salesforce-kafka-source-connector.html

The events generated from Salesforce are in JSON format.  The format looks something like this:

{
 "data": {
    "schema": "NhgeDyLTvEyVPQ9uOzDqeQ",
    "payload": {
        "AccountId__c": "00119000013q2g3AAA",
        "AccountUUID__c": "4654fefb-e3d1-4b08-a4e2-5dabaa504abb",
        "GUID__c": null,
        "CreatedById": "0056g000005YeBAAA0",
        "CreatedDate": "2021-10-10T15:24:43.819Z"
    },
    "event": {
        "replayId": "1256093"
    }
},
 "channel": "/event/Order_Completed__e"
}

This leads us to our issue.  We are using the following configuration for our source connector:

{
"name": "sf_order_p_event_connector",
"config": {
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "key.converter.schemas.enable": "true",
    "value.converter": "org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "true",
    "connector.class": "org.apache.camel.kafkaconnector.salesforce.CamelSalesforceSourceConnector",
    "camel.component.salesforce.loginUrl": "<redacted>",
    "camel.component.salesforce.instanceUrl": "<redacted>",
    "topics": "<redacted>",
    "camel.source.endpoint.rawPayload": "true",
    "camel.source.path.topicName": "/event/Order_Completed__e",
    "camel.source.endpoint.replayId": "-1",
    "camel.component.salesforce.authenticationType": "USERNAME_PASSWORD",
    "camel.component.salesforce.clientId": "<redacted",
    "camel.component.salesforce.clientSecret": "<redacted>",
    "camel.component.salesforce.password": "<redacted5",
    "camel.component.salesforce.userName": "<redacted>",
    "camel.source.endpoint.apiVersion": "52.0"
}
}

When using this value.converter from the configuration above, we get the following exception:

ERROR [sf_account_change_connector|task-0] WorkerSourceTask{id=sf_account_change_connector-0} Task threw an uncaught and unrecoverable exception. Task is being killed and will not recover until manually restarted (org.apache.kafka.connect.runtime.WorkerTask:184)
org.apache.kafka.connect.errors.ConnectException: Tolerance exceeded in error handler
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:206)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
at org.apache.kafka.connect.runtime.WorkerSourceTask.convertTransformedRecord(WorkerSourceTask.java:298)
at org.apache.kafka.connect.runtime.WorkerSourceTask.sendRecords(WorkerSourceTask.java:324)
at org.apache.kafka.connect.runtime.WorkerSourceTask.execute(WorkerSourceTask.java:248)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:182)
at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:231)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at org.apache.kafka.connect.json.JsonConverter.convertToJson(JsonConverter.java:677)
at org.apache.kafka.connect.json.JsonConverter.convertToJsonWithEnvelope(JsonConverter.java:592)
at org.apache.kafka.connect.json.JsonConverter.fromConnectData(JsonConverter.java:346)
at org.apache.kafka.connect.storage.Converter.fromConnectData(Converter.java:63)
at org.apache.kafka.connect.runtime.WorkerSourceTask.lambda$convertTransformedRecord$2(WorkerSourceTask.java:298)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
... 11 more

It seems it cannot convert whatever value is coming through to Kafka into JSON.  I changed value.converter to "org.apache.kafka.connect.storage.StringConverter" to see what I am actually getting in the topic.  Once I did that, this is the message I saw coming through to Kafka from Salesforce:

{data={schema=NhgeDyLTvEyVPQ9uOzDqeQ, payload={AccountId__c=00119000013q2g3AAA,
AccountUUID__c=4654fefb-e3d1-4b08-a4e2-5dabaa504abb, GUID__c=null,
CreatedById=0056g000005YeBAAA0, CreatedDate=2021-10-10T15:24:43.819Z}, event=
{replayId=1256093}}, channel=/event/Order_Completed__e}

It seems Kafka is not processing this as JSON but as a key=value (whatever this is) type of value.  My question is, why am I seeing this type of payload and not JSON?  Also, what configuration (if any) for the source connector can I use to get past this and perhaps convert the value into JSON?  I need this value in JSON for my faust agent to properly process it.  I have tried multiple different configurations for the source connector but nothing seems to be working.

Any help would be appreciated.  Thank you in advance!


问:
Output of this javascript and the reason
```<code>function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();
</code>```

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.

答:
run this:
var m=0;
var d=0;

alert(m++ +":"+ ++d);

and you get "0:1"

IF it were me asking in an interview, the difference in where the ++ is is what I would be after :)
http://jsfiddle.net/MarkSchultheiss/S5nJk/

Body:
function getCtr(){
  var i = 0;
  return function(){
    console.log(++i);
  }
}
var ctr = getCtr();
ctr();
ctr();

I've been using Javascript from last five years, but this question made me dumb in last interview. I tried everything to my knowledge but can't figure it out.

Can you please help me with the output and reason for it so that I can be better equipped for future interviews if I have one.


问:
Comparing two files with respective fields and output required in a specific format
I am comparing two files

food1.txt file  and compares food2.txt file, like this

```<code># cat food1.txt
pizza=1ea
chicken=5ea
tooboo=4ea
orange=2ea
</code>```
```<code># cat food2.txt
pizza=2ea
chicken=5ea
grape=3ea
tooboo=4ea
melon=1ea
</code>```

my work...

```<code>FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done
</code>```

output.. but i don't like it

```<code>-----[ WARN ] : pizza=1ea
-----[  OK  ] : chicken=5ea
-----[  OK  ] : tooboo=4ea
-----[ WARN ] : orange=2ea
</code>```

I want to print the comparison target together

I want output, like this

```<code>food2.txt                   food1.txt
pizza=2ea   : [ NotMatch ] : pizza=1ea
            : [    OK    ] : chicken=5ea
            : [    OK    ] : tooboo=4ea
            : [ NotExist ] : orange=2ea
grape=3ea   : [ NotExist ] :
melon=1ea   : [ NotExist ] :
</code>```

Is it possible? please help me.

答:
As bash is tagged, here's a solution using associative arrays. The first while loop populates the array reading the first file. The second while loop iterates over the second file, checks whether keys and/or values match with entries in the array, and deletes them. Finally the for loop iterates over the remaining "unchecked" items in the array.

out() {
  if   [[      -z "$3" ]]; then l="$1"    m="                " r="$2"
  elif [[      -z "$2" ]]; then l="$3=$1" m=": [ NotExist ] :" r=""
  elif [[      -z "$1" ]]; then l=""      m=": [ NotExist ] :" r="$3=$2"
  elif [[ "$2" == "$1" ]]; then l=""      m=": [    OK    ] :" r="$3=$2"
  else                          l="$3=$1" m=": [ NotMatch ] :" r="$3=$2"; fi
  printf '%-10s %s %-10s\n' "$l" "$m" "$r"
}

f1=food1.txt
f2=food2.txt

out "$f2" "$f1"

declare -A f
while IFS== read -r k v; do f[$k]=$v; done < "$f2"

while IFS== read -r k v; do out "${f[$k]}" "$v" "$k"; unset f[$k]; done < "$f1"

for k in "${!f[@]}"; do out "${f[$k]}" "" "$k"; done
```
```food2.txt                   food1.txt
pizza=2ea  : [ NotMatch ] : pizza=1ea
           : [    OK    ] : chicken=5ea
           : [    OK    ] : tooboo=4ea
           : [ NotExist ] : orange=2ea
grape=3ea  : [ NotExist ] :
melon=1ea  : [ NotExist ] :
```

Body:
I am comparing two files

food1.txt file  and compares food2.txt file, like this

# cat food1.txt
pizza=1ea
chicken=5ea
tooboo=4ea
orange=2ea

# cat food2.txt
pizza=2ea
chicken=5ea
grape=3ea
tooboo=4ea
melon=1ea

my work...

FOOD1=`cat ./food1.txt`
FOOD2=`cat ./food2.txt`

echo "$FOOD1" | while read ACCOUNT
do
grep -w $ACCOUNT ./food2.txt  >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "-----[  OK  ] : $ACCOUNT"
else
echo "-----[ WARN ] : $ACCOUNT"
fi
done

output.. but i don't like it

-----[ WARN ] : pizza=1ea
-----[  OK  ] : chicken=5ea
-----[  OK  ] : tooboo=4ea
-----[ WARN ] : orange=2ea

I want to print the comparison target together

I want output, like this

food2.txt                   food1.txt
pizza=2ea   : [ NotMatch ] : pizza=1ea
            : [    OK    ] : chicken=5ea
            : [    OK    ] : tooboo=4ea
            : [ NotExist ] : orange=2ea
grape=3ea   : [ NotExist ] :
melon=1ea   : [ NotExist ] :

Is it possible? please help me.

Body:
As bash is tagged, here's a solution using associative arrays. The first while loop populates the array reading the first file. The second while loop iterates over the second file, checks whether keys and/or values match with entries in the array, and deletes them. Finally the for loop iterates over the remaining "unchecked" items in the array.

out() {
  if   [[      -z "$3" ]]; then l="$1"    m="                " r="$2"
  elif [[      -z "$2" ]]; then l="$3=$1" m=": [ NotExist ] :" r=""
  elif [[      -z "$1" ]]; then l=""      m=": [ NotExist ] :" r="$3=$2"
  elif [[ "$2" == "$1" ]]; then l=""      m=": [    OK    ] :" r="$3=$2"
  else                          l="$3=$1" m=": [ NotMatch ] :" r="$3=$2"; fi
  printf '%-10s %s %-10s\n' "$l" "$m" "$r"
}

f1=food1.txt
f2=food2.txt

out "$f2" "$f1"

declare -A f
while IFS== read -r k v; do f[$k]=$v; done < "$f2"

while IFS== read -r k v; do out "${f[$k]}" "$v" "$k"; unset f[$k]; done < "$f1"

for k in "${!f[@]}"; do out "${f[$k]}" "" "$k"; done

food2.txt                   food1.txt
pizza=2ea  : [ NotMatch ] : pizza=1ea
           : [    OK    ] : chicken=5ea
           : [    OK    ] : tooboo=4ea
           : [ NotExist ] : orange=2ea
grape=3ea  : [ NotExist ] :
melon=1ea  : [ NotExist ] :


问:
Displayed image from a time frame of a video has the wrong color
i tried to extract a time frame of a video, and show it as image(JPEG). But unfortunately the displayed image using PIL.Image.fromarray() is bluer than it supposed to be. the tricky part is, when i save it first (using cv2.imwrite) and open that new file using PIL.Image.open(), the image has the right color.

I thought it has something to do with the RGB array composition, but then i checked it, and both array (direct from the frame and from the Image.open()) are exactly the same.

Is there anything i can do to show the right image without saving it as an external file beforehand?

Thank you.

```<code>def TimeFrame(file, tf):
    capture = cv2.VideoCapture(file)
    frameCount = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    capture.set(cv2.CAP_PROP_POS_FRAMES, tf)
    _, frame = capture.read()

    directTF = Image.fromarray(frame)

    cv2.imwrite("12345678999.jpg", frame)
    image = Image.open("12345678999.jpg")
</code>```

note: file is the name of the video and tf is the certain timeframe that you want to extract the image from.

答:
OpenCV uses BGR as its default colour order for images

Use cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before displaying

Body:
i tried to extract a time frame of a video, and show it as image(JPEG). But unfortunately the displayed image using PIL.Image.fromarray() is bluer than it supposed to be. the tricky part is, when i save it first (using cv2.imwrite) and open that new file using PIL.Image.open(), the image has the right color.

I thought it has something to do with the RGB array composition, but then i checked it, and both array (direct from the frame and from the Image.open()) are exactly the same.

Is there anything i can do to show the right image without saving it as an external file beforehand?

Thank you.

def TimeFrame(file, tf):
    capture = cv2.VideoCapture(file)
    frameCount = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    capture.set(cv2.CAP_PROP_POS_FRAMES, tf)
    _, frame = capture.read()

    directTF = Image.fromarray(frame)

    cv2.imwrite("12345678999.jpg", frame)
    image = Image.open("12345678999.jpg")

note: file is the name of the video and tf is the certain timeframe that you want to extract the image from.


答:
OpenCV uses BGR, PIL uses RGB.

You might want to try

```<code>directTF = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
</code>```

to have OpenCV flip those channels before you ask PIL to read the array.

Title: Displayed image from a time frame of a video has the wrong color

Body:
OpenCV uses BGR, PIL uses RGB.

You might want to try

directTF = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))

to have OpenCV flip those channels before you ask PIL to read the array.


问:
SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 96 Current browser version is 98.0
Error tracelogs:

```<code>DevTools listening on ws://127.0.0.1:54791/devtools/browser/6f264bcc-d44a-40d9-b6cf-
8b1655c97ccd
Traceback (most recent call last):
File "c:\Users\alsgn\OneDrive\desktop\mypython\getselenium\dc\findbulletins.py", line 11, in
<module>
browser = webdriver.Chrome()
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__
RemoteWebDriver.__init__(
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This
version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path C:\Program
Files\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
    Ordinal0 [0x00FF6903+2517251]
    Ordinal0 [0x00F8F8E1+2095329]
    Ordinal0 [0x00E92848+1058888]
    Ordinal0 [0x00EB0B9D+1182621]
    Ordinal0 [0x00EACA60+1165920]
    Ordinal0 [0x00EAA2CF+1155791]
    Ordinal0 [0x00EDAAAF+1354415]
    Ordinal0 [0x00EDA71A+1353498]
    Ordinal0 [0x00ED639B+1336219]
    Ordinal0 [0x00EB27A7+1189799]
    Ordinal0 [0x00EB3609+1193481]
    GetHandleVerifier [0x01185904+1577972]
    GetHandleVerifier [0x01230B97+2279047]
    GetHandleVerifier [0x01086D09+534521]
    GetHandleVerifier [0x01085DB9+530601]
    Ordinal0 [0x00F94FF9+2117625]
    Ordinal0 [0x00F998A8+2136232]
    Ordinal0 [0x00F999E2+2136546]
    Ordinal0 [0x00FA3541+2176321]
    BaseThreadInitThunk [0x755AFA29+25]
    RtlGetAppContainerNamedObjectPath [0x775C7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x775C7A6E+238]
</code>```

The code that I ran was okay in 2 days ago, but now, the code have been showed this error.
Please say how to solve this problem. I wonder why it ran well before.

答:
Your output log states:

```<code>This version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path
</code>```

You have two options:

Use chromedriver for Chrome 98

Install Chrome 96

Body:
Error tracelogs:

DevTools listening on ws://127.0.0.1:54791/devtools/browser/6f264bcc-d44a-40d9-b6cf-
8b1655c97ccd
Traceback (most recent call last):
File "c:\Users\alsgn\OneDrive\desktop\mypython\getselenium\dc\findbulletins.py", line 11, in
<module>
browser = webdriver.Chrome()
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__
RemoteWebDriver.__init__(
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "C:\Users\alsgn\AppData\Local\Programs\Python\Python39\lib\site-
packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This
version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path C:\Program
Files\Google\Chrome\Application\chrome.exe
Stacktrace:
Backtrace:
    Ordinal0 [0x00FF6903+2517251]
    Ordinal0 [0x00F8F8E1+2095329]
    Ordinal0 [0x00E92848+1058888]
    Ordinal0 [0x00EB0B9D+1182621]
    Ordinal0 [0x00EACA60+1165920]
    Ordinal0 [0x00EAA2CF+1155791]
    Ordinal0 [0x00EDAAAF+1354415]
    Ordinal0 [0x00EDA71A+1353498]
    Ordinal0 [0x00ED639B+1336219]
    Ordinal0 [0x00EB27A7+1189799]
    Ordinal0 [0x00EB3609+1193481]
    GetHandleVerifier [0x01185904+1577972]
    GetHandleVerifier [0x01230B97+2279047]
    GetHandleVerifier [0x01086D09+534521]
    GetHandleVerifier [0x01085DB9+530601]
    Ordinal0 [0x00F94FF9+2117625]
    Ordinal0 [0x00F998A8+2136232]
    Ordinal0 [0x00F999E2+2136546]
    Ordinal0 [0x00FA3541+2176321]
    BaseThreadInitThunk [0x755AFA29+25]
    RtlGetAppContainerNamedObjectPath [0x775C7A9E+286]
    RtlGetAppContainerNamedObjectPath [0x775C7A6E+238]

The code that I ran was okay in 2 days ago, but now, the code have been showed this error.
Please say how to solve this problem. I wonder why it ran well before.

Body:
Your output log states:

This version of ChromeDriver only supports Chrome version 96
Current browser version is 98.0.4758.82 with binary path

You have two options:

Use chromedriver for Chrome 98

Install Chrome 96


问:
issue with counting lines of python file
I am traversing a directory, and if python file is found, trying to find the number of lines of code in it.
I am not really sure why I face the below issue.

```<code>for dirpath, dirnames, filenames in os.walk(APP_FOLDER):

    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            num_lines = len(open(file).readlines()) #causes issue
            print(
                f"Root:{dirpath}\n"
                f"file:{file}\n\n"
                f"lines: {num_lines}" //
            )
</code>```

Érror:

```<code>Traceback (most recent call last):
  File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
    num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory:
</code>```

If i remove that line, the code works as expected. There is a single line code within. Any guidance here?

答:
You can also try this way. You have to get the os.path.abspath(file) path of the file then only it'll open.

and always with contect_managers for IO operation.

```<code>for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            try:
                with open(os.path.abspath(file)) as f:
                    print(len(f.readlines()))
                    print(os.path.abspath(file))
            except:
                pass
</code>```

Body:
I am traversing a directory, and if python file is found, trying to find the number of lines of code in it.
I am not really sure why I face the below issue.

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):

    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            num_lines = len(open(file).readlines()) #causes issue
            print(
                f"Root:{dirpath}\n"
                f"file:{file}\n\n"
                f"lines: {num_lines}" //
            )

Érror:

Traceback (most recent call last):
  File "C:\Users\XXXX\PycharmProjects\pythonProject1\main.py", line 11, in <module>
    num_lines = len(open(file).readlines())
FileNotFoundError: [Errno 2] No such file or directory:

If i remove that line, the code works as expected. There is a single line code within. Any guidance here?

Body:
You can also try this way. You have to get the os.path.abspath(file) path of the file then only it'll open.

and always with contect_managers for IO operation.

for dirpath, dirnames, filenames in os.walk(APP_FOLDER):
    for file in filenames:
        if pathlib.Path(file).suffix == ".py":
            try:
                with open(os.path.abspath(file)) as f:
                    print(len(f.readlines()))
                    print(os.path.abspath(file))
            except:
                pass


问:
How to select rows with at least one categorical value in pandas DataFrame
How I can retrieve indexes of the rows, in a pandas DataFrame (df), with "object" type (dtype=='O') in at least one column of the DataFrame?

What I would like to do in practice is to create a new dataframe (numeric_df) with only the numeric values of a source dataframe (df).

答:
Use:

```<code>df = pd.DataFrame({'object col':[1,'a',25]})
df[df['object col'].apply(lambda x: type(x))==int]
</code>```

result:

Based on the comment:

```<code>df = pd.DataFrame({'object col':[1,'a',25], 'object col2':['a','a',25]})
def check(row):
  for col in row:
    if type(col)==str:
      return False
  return True
df[df.apply(check, axis = 1)]
</code>```

result:

Body:
Use:

df = pd.DataFrame({'object col':[1,'a',25]})
df[df['object col'].apply(lambda x: type(x))==int]

result:

Based on the comment:

df = pd.DataFrame({'object col':[1,'a',25], 'object col2':['a','a',25]})
def check(row):
  for col in row:
    if type(col)==str:
      return False
  return True
df[df.apply(check, axis = 1)]

result:


问:
How to prevent duplicate Modal Popup & not scrolling to last element in ReactJS
I'm creating a Project where I fetch data from server & render 10 data in 10 different Bootstrap card using map(). Each card have a button to popup a Modal. Beside I set a Link to button that will show me route of that data.

Information

Using react-bootstrap for modal with hooks

Using react-router-dom for show route

Using useState hooks to set data from fetched data to modal.

All of code are in one component.

info_prop & info are different but it works with same data.

I have import all needed things & don't have any warning or error

About Data Handling

First I get data with useGetDataQuery() using chapterId.

Map data & destructure  info data & set to state with setInfo

Send to Modal props with info

Handle of sending to setInfo with handleModal. I also try without this function. That time I do it on onClick.

Problem

Route Problem with map()

I use a Button to show Modal & Wrapped the button with Link. Every Link has a uniqe ID like 1:1, 1:2, 1:3...1:10. If I click on 1:1 button it show me the content of 1:1. But when I close the modal the route auto change 1:1 to 1:3...1:10.

I can realize that there it's render a duplicate Modal behind main Modal. I can see only 3-4 lines of back modal.

Modal Problem

When I show 1-5 data with map & click button of popup modal, modal show normally with blur background.

When I dhow 1-10 data with map & click button of popup modal, background become pure black.(I think it's not normal)

Dependencies

react-bootstrap v5

bootstrap v5

react-router-dom v6

Code

Code of component. Modal in same component but in another function.

function TafsirModal(props) {
    return (
        <Modal
            {...props}
            size="md"
            aria-labelledby="contained-modal-title-vcenter"
            centered
        >
            <Modal.Header closeButton>
                <Modal.Title id="contained-modal-title-vcenter">
                    Heading
                </Modal.Title>
            </Modal.Header>
            <Modal.Body>

                    {props.info}

            </Modal.Body>
            <Modal.Footer>
                <Button onClick={props.onHide}>Close</Button>
            </Modal.Footer>
        </Modal>
    )
}

const InfoCom = () => {
    const { chapterId } = useParams()

    let [modalShow, setModalShow] = useState(false);
    let [info, setInfo] = useState('')
    const { data } = useGetDataQuery(chapterId)

    const handleModal = (info_prop) => {
        setInfo(info_prop)
        setModalShow(true)
    }

    return (
        <>

                        {data.map(res => (
                            <Link to={`/li/${chapterId}/${res.res_key}`} key={res.res_key} >

                                            <Button onClick={() => handleModal(res.info[0].text)}>
                                                Get Info
                                            </Button>

                                            <TafsirModal
                                                show={modalShow}
                                                onHide={() => setModalShow(false)}
                                                info={info}
                                            />

                            </Link>
                        ))}

        </>
    )
}
export default InfoCom

```

答:
The issue looks like it's the way you're handling showing your modal with
show={modalShow}
Whenever you click on a button to show your modal all of them are showing because they all have show modal true from modalShow. instead of using showModal state try this:

```<code>let [activeModal, setActiveModal] = useState('');

function handleModal(info_prop) {
  setInfo(info_prop)
  // if you have an id or something use that instead of text in set activeModal
  setActiveModal(info_prop)
}
// in map
<Button onClick=(() => handleModal(res.info[0].text)></Button>

<TafsirModal
  show={activeModal === res.info[0].text ? true : false}
  onHide=(setActiveModal(''))
/>
</code>```

Another solution that I more commonly use is to render the modal outside of the map towards the top level of the the component and this way you could use the same logic you currently have and this way we are rendering only one modal which would be better in my opinion and easier to read.
We can do this my simply moving <TafsirModal /> up a few levels in the tree

```<code><>
            <div className="container">
                <div className="row">
                    <div className="col-md-12">
                        {data.map(res => (
                            <Link to={`/li/${chapterId}/${res.res_key}`} key={res.res_key} >
                                <div key={res.id} className='card my-2'>
                                    <div className="card-body">
                                        <div className="d-flex flex-row">
                                            <Button onClick={() => handleModal(res.info[0].text)}>
                                                Get Info
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            </Link>
                        ))}
                    </div>
                </div>
               {activeModal && <TafsirModal
                  show={modalShow}
                  onHide={() => setModalShow(false)}
                  info={info}
                 />
                }
            </div>
        </>
</code>```

Body:
The issue looks like it's the way you're handling showing your modal with
show={modalShow}
Whenever you click on a button to show your modal all of them are showing because they all have show modal true from modalShow. instead of using showModal state try this:

let [activeModal, setActiveModal] = useState('');

function handleModal(info_prop) {
  setInfo(info_prop)
  // if you have an id or something use that instead of text in set activeModal
  setActiveModal(info_prop)
}
// in map
<Button onClick=(() => handleModal(res.info[0].text)></Button>

<TafsirModal
  show={activeModal === res.info[0].text ? true : false}
  onHide=(setActiveModal(''))
/>

Another solution that I more commonly use is to render the modal outside of the map towards the top level of the the component and this way you could use the same logic you currently have and this way we are rendering only one modal which would be better in my opinion and easier to read.
We can do this my simply moving <TafsirModal /> up a few levels in the tree

<>
            <div className="container">
                <div className="row">
                    <div className="col-md-12">
                        {data.map(res => (
                            <Link to={`/li/${chapterId}/${res.res_key}`} key={res.res_key} >
                                <div key={res.id} className='card my-2'>
                                    <div className="card-body">
                                        <div className="d-flex flex-row">
                                            <Button onClick={() => handleModal(res.info[0].text)}>
                                                Get Info
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                            </Link>
                        ))}
                    </div>
                </div>
               {activeModal && <TafsirModal
                  show={modalShow}
                  onHide={() => setModalShow(false)}
                  info={info}
                 />
                }
            </div>
        </>


问:
Regression with lagged time time series data in R
I have two-time series data A and B. I want to execute the following linear regression in R

A ~ Lags(A, 1:2) + Lags(B, 1:2)

Can you please help me with the R code ?

答:
Using dyn and the built in BOD data frame (which contains two columns, Time and demand) we can specify the indicated lags.

Note that the dplyr package clobbers lag so just in case it is loaded we restore base lag.  Note the sign needed with lag.

Using dyn$lm and zoo(BOD) will result in automatic alignment.

If BOD did not include only numeric data it would be necessary to eliminate any columns not used first; however, here BOD is entirely numeric.

```<code>library(dyn)  # also loads zoo

lag <- stats::lag
fm <- dyn$lm(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2)), zoo(BOD))
fm
</code>```

giving:

```<code>Call:
lm(formula = dyn(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2))),
    data = zoo(BOD))

Coefficients:
         (Intercept)  lag(demand, -(1:2))1  lag(demand, -(1:2))2
             23.5410               -0.5126               -0.5071
  lag(Time, -(1:2))1    lag(Time, -(1:2))2
              2.4737                    NA
</code>```

This shows BOD and the model.frame and model.matrix used.

```<code>> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

> model.frame(fm)
  demand lag(demand, -(1:2)).1 lag(demand, -(1:2)).2 lag(Time, -(1:2)).1 lag(Time, -(1:2)).2
3   19.0                  10.3                   8.3                   2                   1
4   16.0                  19.0                  10.3                   3                   2
5   15.6                  16.0                  19.0                   4                   3
6   19.8                  15.6                  16.0                   5                   4

> model.matrix(fm)
  (Intercept) lag(demand, -(1:2))1 lag(demand, -(1:2))2 lag(Time, -(1:2))1 lag(Time, -(1:2))2
3           1                 10.3                  8.3                  2                  1
4           1                 19.0                 10.3                  3                  2
5           1                 16.0                 19.0                  4                  3
6           1                 15.6                 16.0                  5                  4
attr(,"assign")
[1] 0 1 1 2 2
</code>```

Body:
Using dyn and the built in BOD data frame (which contains two columns, Time and demand) we can specify the indicated lags.

Note that the dplyr package clobbers lag so just in case it is loaded we restore base lag.  Note the sign needed with lag.

Using dyn$lm and zoo(BOD) will result in automatic alignment.

If BOD did not include only numeric data it would be necessary to eliminate any columns not used first; however, here BOD is entirely numeric.

library(dyn)  # also loads zoo

lag <- stats::lag
fm <- dyn$lm(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2)), zoo(BOD))
fm

giving:

Call:
lm(formula = dyn(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2))),
    data = zoo(BOD))

Coefficients:
         (Intercept)  lag(demand, -(1:2))1  lag(demand, -(1:2))2
             23.5410               -0.5126               -0.5071
  lag(Time, -(1:2))1    lag(Time, -(1:2))2
              2.4737                    NA

This shows BOD and the model.frame and model.matrix used.

> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

> model.frame(fm)
  demand lag(demand, -(1:2)).1 lag(demand, -(1:2)).2 lag(Time, -(1:2)).1 lag(Time, -(1:2)).2
3   19.0                  10.3                   8.3                   2                   1
4   16.0                  19.0                  10.3                   3                   2
5   15.6                  16.0                  19.0                   4                   3
6   19.8                  15.6                  16.0                   5                   4

> model.matrix(fm)
  (Intercept) lag(demand, -(1:2))1 lag(demand, -(1:2))2 lag(Time, -(1:2))1 lag(Time, -(1:2))2
3           1                 10.3                  8.3                  2                  1
4           1                 19.0                 10.3                  3                  2
5           1                 16.0                 19.0                  4                  3
6           1                 15.6                 16.0                  5                  4
attr(,"assign")
[1] 0 1 1 2 2


问:
Javascript matching objects of an array
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

```<code>const allaOrter = orter.map((allOrt) =>
<li>{allOrt.url}</li>
)
</code>```

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

```<code>orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]
</code>```

答:
You should first try to narrow down by matching the object which contains the url /blekinge using the filter method. Once you have filtered, the resulting array can be used to present a list.

To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.

let listElement = document.getElementById('name-list');

let data = [
  {
      "id": "2",
      "name": "Blekinge",
      "url": "/blekinge"
  },
  {
      "id": "23",
      "name": "Karlshamn",
      "url": "/blekinge/karlshamn"
  },
  {
      "id": "24",
      "name": "Karlskrona",
      "url": "/blekinge/karlskrona"
  },
  {
      "id": "25",
      "name": "Olofström",
      "url": "/blekinge/olofstrom"
  },
  {
      "id": "26",
      "name": "Ronneby",
      "url": "/test/ronneby"
  }
];

let updateList = (list, content) => {
  let li = document.createElement("li");

  li.innerHTML = content;

  list.appendChild(li);
};

let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);

filteredData.map(elem => updateList(listElement, elem.name)); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="name-list">Matching names</label>
<ul id="name-list">
<ul></code>```

Title: Javascript matching objects of an array

Body:
I have this array, I wish to pick out all the names which have a URL which contains '/blekinge'.

Any way to do this with map? And present in a list?
I've come this far:

const allaOrter = orter.map((allOrt) =>

{allOrt.url}

)

What I would like to do is to have sort of an ifstatement or a forEach loop that picks out all the URLs which contains /blekinge and present those. But I dont know how...
The real array I'm working with is much bigger and contains loads of urls.
Maybe even make new arrays which contains those elements that have a common url.
I hope my provided example is enough for someone of you guys to help me out. :)

orter.json
[{
        "id": "2",
        "namn": "Blekinge",
        "url": "/blekinge"
    },
    {
        "id": "23",
        "namn": "Karlshamn",
        "url": "/blekinge/karlshamn"
    },
    {
        "id": "24",
        "namn": "Karlskrona",
        "url": "/blekinge/karlskrona"
    },
    {
        "id": "25",
        "namn": "Olofström",
        "url": "/blekinge/olofstrom"
    },
    {
        "id": "26",
        "namn": "Ronneby",
        "url": "/blekinge/ronneby"
    }]

Body:
You should first try to narrow down by matching the object which contains the url /blekinge using the filter method. Once you have filtered, the resulting array can be used to present a list.

To keep things simple, I implemented an unordered list to present the result, but the core of what you need is in the resulting filtered array.

let listElement = document.getElementById('name-list');

let data = [
  {
      "id": "2",
      "name": "Blekinge",
      "url": "/blekinge"
  },
  {
      "id": "23",
      "name": "Karlshamn",
      "url": "/blekinge/karlshamn"
  },
  {
      "id": "24",
      "name": "Karlskrona",
      "url": "/blekinge/karlskrona"
  },
  {
      "id": "25",
      "name": "Olofström",
      "url": "/blekinge/olofstrom"
  },
  {
      "id": "26",
      "name": "Ronneby",
      "url": "/test/ronneby"
  }
];

let updateList = (list, content) => {
  let li = document.createElement("li");

  li.innerHTML = content;

  list.appendChild(li);
};

let filteredData = data.filter(elem => elem.url.indexOf('/blekinge') !== -1);

filteredData.map(elem => updateList(listElement, elem.name));

<label for="name-list">Matching names</label>
<ul id="name-list">
<ul>


问:
calling a ruby script by double-clicking does not work
I've got a ruby script myscript.sh like this

#!/usr/bin/env ruby

puts 'do some ruby stuff'

opening a terminal and calling it with ./myscript.sh just works fine.

But when I try doubleclicking the file it does not.

A simple shell script like this works just fine either by doubleclicking or terminal.

```<code>#!/bin/bash
echo 'TEST' > Test.txt
</code>```

I am using Ubuntu 11.04

I also use rvm aka Ruby Version Manager. The Problem was that I also require nokogiri.
So I needed to set up rvm in my Scriptings to resolve the necessary resources, which I did with a startscript containing

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

if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then

  \# First try to load from a user install
  source "$HOME/.rvm/scripts/rvm"

elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then

  \# Then try to load from a root install
  source "/usr/local/rvm/scripts/rvm"

else

  printf "ERROR: An RVM installation was not found.\n"

fi

./myscript.sh
</code>```

答:
My guess is it runs in background, with no window.

Try:

```<code>#!/usr/bin/env ruby
File.open('rubytest.txt', 'w') do |f|
  f.puts 'do some ruby stuff'
end
</code>```

and check if rubytest.txt exists.

Body:
I've got a ruby script myscript.sh like this

#!/usr/bin/env ruby

puts 'do some ruby stuff'

opening a terminal and calling it with ./myscript.sh just works fine.

But when I try doubleclicking the file it does not.

A simple shell script like this works just fine either by doubleclicking or terminal.

#!/bin/bash
echo 'TEST' > Test.txt

I am using Ubuntu 11.04

I also use rvm aka Ruby Version Manager. The Problem was that I also require nokogiri.
So I needed to set up rvm in my Scriptings to resolve the necessary resources, which I did with a startscript containing

#!/bin/bash

if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then

  \# First try to load from a user install
  source "$HOME/.rvm/scripts/rvm"

elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then

  \# Then try to load from a root install
  source "/usr/local/rvm/scripts/rvm"

else

  printf "ERROR: An RVM installation was not found.\n"

fi

./myscript.sh

Body:
My guess is it runs in background, with no window.

Try:

#!/usr/bin/env ruby
File.open('rubytest.txt', 'w') do |f|
  f.puts 'do some ruby stuff'
end

and check if rubytest.txt exists.


问:
How to enable Swagger to listen to IP instead of localhost?
I have Swagger integrated with my desktop application listening on port 8081 (http://localhost:8081).
Swagger-ui is available on http://localhost:8081/docs
You see here that its listening only on localhost.

How do I get the server to listen on the actual IP address of my Server e.g. 10.12.13.23 and not localhost?

As I want to access it from another PC and send and receive API responses, how do I configure to listen to IP address?

答:
Give this a try:

Go to the swagger folder

Open file named package.json

Replace localhost:8081 with {your_ip}:8081

Restart swagger


问:
Is it possible for a child process to get the PID of its siblings?
The child process is another C program run with execlp. The machine is Unix. I know the child process can access the process table with execlp("ps", "ps", NULL) but I can't figure out how it can determine its sibling.

Even though the processes are asynchronous, I know that the sibling process will be running.

答:
yes, it is possible. I am attaching c code for this. Here I have taken 4 children and all are sharing their pid's.</p>
```<code>#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define NUM_CHILDREN 4

/* Entry point for the child processes */
int child_main(int pipe_read_end) {
  pid_t my_pid = getpid();

  /* Read child pids from pipe */
  int child_pids[NUM_CHILDREN];
  unsigned int bytes_read = 0;
  while (bytes_read < sizeof(child_pids)) {
    ssize_t result = read(pipe_read_end, ((unsigned char *) child_pids) + bytes_read, sizeof(child_pids) - bytes_read);
    if (result < 0) {
      perror("error reading from pipe");
      return 1;
    } else if (result == 0) {
      fprintf(stderr, "unexpected end of file\n");
      return 1;
    } else {
      bytes_read += result;
    }
  }
  close(pipe_read_end);

  /* Do something useful with these child pids */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    printf("Child %d received sibling pid %d\n", my_pid, child_pids[i]);
  }

  return 0;
}

/* Entry point for the parent process. */
int main() {
  int child_pids[NUM_CHILDREN];
  int pipe_write_ends[NUM_CHILDREN];
  for (int i = 0; i < NUM_CHILDREN; i++) {
    /* Create the pipe for child i */
    int pipefd[2];
    if (pipe(pipefd)) {
      perror("error creating pipe");
      return 1;
    }
    int pipe_read_end = pipefd[0];
    int pipe_write_end = pipefd[1];

    /* Fork child i */
    pid_t child_pid = fork();
    if (child_pid < 0) {
      perror("error forking");
      return 1;
    } else if (child_pid == 0) {
      printf("Child %d was forked\n", getpid());
      close(pipe_write_end);
      return child_main(pipe_read_end);
    } else {
      printf("Parent forked child %d\n", child_pid);
      close(pipe_read_end);
      pipe_write_ends[i] = pipe_write_end;
      child_pids[i] = child_pid;
    }
  }

  /* Send pids down the pipes for each child */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    unsigned int bytes_written = 0;
    while (bytes_written < sizeof(child_pids)) {
      ssize_t result = write(pipe_write_ends[i], ((unsigned char *) child_pids) + bytes_written, sizeof(child_pids) - bytes_written);
      if (result < 0) {
        perror("error writing to pipe");
        return 1;
      } else {
        bytes_written += result;
      }
    }
    close(pipe_write_ends[i]);
  }

  /* Wait for children to exit */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    if (waitpid(child_pids[i], 0, 0) < 0) {
      perror("error waiting for child");
      return 1;
    }
  }
  }
</code>```

Body:
yes, it is possible. I am attaching c code for this. Here I have taken 4 children and all are sharing their pid's.

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define NUM_CHILDREN 4

/* Entry point for the child processes */
int child_main(int pipe_read_end) {
  pid_t my_pid = getpid();

  /* Read child pids from pipe */
  int child_pids[NUM_CHILDREN];
  unsigned int bytes_read = 0;
  while (bytes_read < sizeof(child_pids)) {
    ssize_t result = read(pipe_read_end, ((unsigned char *) child_pids) + bytes_read, sizeof(child_pids) - bytes_read);
    if (result < 0) {
      perror("error reading from pipe");
      return 1;
    } else if (result == 0) {
      fprintf(stderr, "unexpected end of file\n");
      return 1;
    } else {
      bytes_read += result;
    }
  }
  close(pipe_read_end);

  /* Do something useful with these child pids */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    printf("Child %d received sibling pid %d\n", my_pid, child_pids[i]);
  }

  return 0;
}

/* Entry point for the parent process. */
int main() {
  int child_pids[NUM_CHILDREN];
  int pipe_write_ends[NUM_CHILDREN];
  for (int i = 0; i < NUM_CHILDREN; i++) {
    /* Create the pipe for child i */
    int pipefd[2];
    if (pipe(pipefd)) {
      perror("error creating pipe");
      return 1;
    }
    int pipe_read_end = pipefd[0];
    int pipe_write_end = pipefd[1];

    /* Fork child i */
    pid_t child_pid = fork();
    if (child_pid < 0) {
      perror("error forking");
      return 1;
    } else if (child_pid == 0) {
      printf("Child %d was forked\n", getpid());
      close(pipe_write_end);
      return child_main(pipe_read_end);
    } else {
      printf("Parent forked child %d\n", child_pid);
      close(pipe_read_end);
      pipe_write_ends[i] = pipe_write_end;
      child_pids[i] = child_pid;
    }
  }

  /* Send pids down the pipes for each child */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    unsigned int bytes_written = 0;
    while (bytes_written < sizeof(child_pids)) {
      ssize_t result = write(pipe_write_ends[i], ((unsigned char *) child_pids) + bytes_written, sizeof(child_pids) - bytes_written);
      if (result < 0) {
        perror("error writing to pipe");
        return 1;
      } else {
        bytes_written += result;
      }
    }
    close(pipe_write_ends[i]);
  }

  /* Wait for children to exit */
  for (int i = 0; i < NUM_CHILDREN; i++) {
    if (waitpid(child_pids[i], 0, 0) < 0) {
      perror("error waiting for child");
      return 1;
    }
  }
  }


问:
CVDisplayLink debug messages
Since Xcode 13.2.1 I get flooded with CVDisplayLink debug / warning messages.

Like

```<code>CVDisplayLink::start
CVDisplayLink::stop
</code>```

20 times a second or so.

I think they may come from an WebView which runs an embedded version of the Ace editor.

Does anybody know how to prevent the CVDisplayLink messages specifically ?

答:
Unfortunately disabling OS_ACTIVITY_MODE disables all system logs output including os_log(..)

I found a better solution:

```<code>CFPreferencesSetValue("cv_note" as CFString, 0 as CFPropertyList, "com.apple.corevideo" as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
CFPreferencesSynchronize("com.apple.corevideo" as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
</code>```

Title: CVDisplayLink debug messages

Body:
Since Xcode 13.2.1 I get flooded with CVDisplayLink debug / warning messages.

Like

CVDisplayLink::start
CVDisplayLink::stop

20 times a second or so.

I think they may come from an WebView which runs an embedded version of the Ace editor.

Does anybody know how to prevent the CVDisplayLink messages specifically ?

Body:
Unfortunately disabling OS_ACTIVITY_MODE disables all system logs output including os_log(..)

I found a better solution:

CFPreferencesSetValue("cv_note" as CFString, 0 as CFPropertyList, "com.apple.corevideo" as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
CFPreferencesSynchronize("com.apple.corevideo" as CFString, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)


问:
Parsing Date JSON Crash in UK region
I am downloading json with a date string. An example is "2020-06-08T09:48:47.570"

I am easily able to convert this string into a date with a DateFormatter and a dateFormat of "yyyy-MM-dd'T'HH:mm:ss.SSS". However, when I set the iPhone region to UK and the time display to 12 hours, the dateFormatter fails to parse the string.

答:
Either set the calendar of the formatter to an ISO8601 calendar

```<code>let dateString = "2020-06-08T09:48:47.570"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = formatter.date(from: dateString)
</code>```

or use ISO8601DateFormatter, however you have to append a Z time zone specifier

```<code>let dateString = "2020-06-08T09:48:47.570"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: dateString + "Z")
</code>```

Title: Parsing Date JSON Crash in UK region

Body:
Either set the calendar of the formatter to an ISO8601 calendar

let dateString = "2020-06-08T09:48:47.570"
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
let date = formatter.date(from: dateString)

or use ISO8601DateFormatter, however you have to append a Z time zone specifier

let dateString = "2020-06-08T09:48:47.570"
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: dateString + "Z")