问:
HTML draw vertical line intersecting two rows bootstrap
I am attempting to draw a vertical line between the two brief case icons, ideally that isn't fixed in position so it adjusts with screen size. I have attached a copy of the container as well as a screen shot of what it currently looks like when run. Thanks!

Work Expierence and Education

Intern

Summer 2018

Academy

 Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test

Intern 2

Summer 2019

Academy

 Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test

```

答:
You can draw vertical lines going from the bottom and top of each of the circles using after and before pseudo elements.

If these are made long but the containing element given overflow of hidden they join up but don't spill over.

In addition, the first instance has the before pseudo element displayed none and the last pseudo element has the after pseudo element displayed none.

  <title>Bootstrap 5 Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css">

Work Expierence and Education

Intern

Summer 2018

Academy

 Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test

Intern 2

Summer 2019

Academy

 Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test

```

There are what seemed like spurious p and br elements in the given HTML.

You may like to look further at these and see if they are necessary - they don't seem to add to the meaning given in the structure of the HTML. The main problem being to select what 'logically' seemed like the first child being the first row - but it wasn't because of p and br elements.

Body:
You can draw vertical lines going from the bottom and top of each of the circles using after and before pseudo elements.

If these are made long but the containing element given overflow of hidden they join up but don't spill over.

In addition, the first instance has the before pseudo element displayed none and the last pseudo element has the after pseudo element displayed none.

<head>
  <title>Bootstrap 5 Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.7/css/all.css">
  <style>
    .col-md-auto:nth-child(2) {
      overflow: hidden;
    }

    .col-md-auto:nth-child(2) span.fa-stack {
      position: relative;
    }

    .col-md-auto:nth-child(2) span.fa-stack::before,
    .col-md-auto:nth-child(2) span.fa-stack::after {
      content: '';
      background: black;
      position: absolute;
      left: 50%;
      height: 100vh;
      width: 1px;
      display: inline-block;
      z-index: 1;
    }

    .col-md-auto:nth-child(2) span.fa-stack::before {
      bottom: 100%;
    }

    .col-md-auto:nth-child(2) span.fa-stack::after {
      top: 100%;
    }

    div.row.justify-content-center:nth-child(3) .col-md-auto:nth-child(2) span.fa-stack::before,
    div.row.justify-content-center:last-child .col-md-auto:nth-child(2) span.fa-stack::after {
      display: none;
    }
  </style>
</head>

<body>
  <div class="container2">
    <p style="font-size:64px; color: #555555;text-align:center; font-family: Courier New">Work Expierence and Education
      <p>
        <div class="row justify-content-center">
          <div class="col-md-auto">
            <div class="p-2">
              <p style="font-size:32px; color: #000000;text-align:left; font-family: Courier New">Intern
                <p>
                  <p style="font-size:24px; color: #555555;text-align:left; font-family: Courier New">Summer 2018
                    <p>
            </div>
          </div>
          <div class="col-md-auto">
            <br>
            <span class="fa-stack" style="vertical-align: middle;">
      <i class="far fa-circle fa-stack-2x"></i>
      <i class="fas fa-briefcase fa-stack-1x"></i>
    </span>
          </div>
          <div class="col-6">
            <p style="font-size:32px; color: #000000;text-align:left; font-family: Courier New">Academy
              <p>
                <p style="font-size:18px; color: #000000;text-align:left; font-family: Courier New"> Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test
                  <p>
          </div>
        </div>

        <div class="row justify-content-center">
          <div class="col-md-auto">
            <div class="p-2">
              <p style="font-size:32px; color: #000000;text-align:left; font-family: Courier New">Intern 2
                <p>
                  <p style="font-size:24px; color: #555555;text-align:left; font-family: Courier New">Summer 2019
                    <p>
            </div>
          </div>
          <div class="col-md-auto">
            <br>
            <span class="fa-stack" style="vertical-align: middle;">
      <i class="far fa-circle fa-stack-2x"></i>
      <i class="fas fa-briefcase fa-stack-1x"></i>
    </span>
          </div>
          <div class="col-6">
            <p style="font-size:32px; color: #000000;text-align:left; font-family: Courier New">Academy
              <p>
                <p style="font-size:18px; color: #000000;text-align:left; font-family: Courier New"> Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test TestTest Test Test Test Test Test Test Test Test Test
                  <p>
          </div>
        </div>
  </div>

There are what seemed like spurious p and br elements in the given HTML.

You may like to look further at these and see if they are necessary - they don't seem to add to the meaning given in the structure of the HTML. The main problem being to select what 'logically' seemed like the first child being the first row - but it wasn't because of p and br elements.


来源: stackexchange

问:
How to remove UserAccountsDrawerHeader outline on flutter
I'm learning flutter.
I used the UserAccountsDrawerHeader widget using the Drawer widget, but when setting Radius, unnecessary line appears below.
How can you remove it?

Here's my code

```<code>drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            UserAccountsDrawerHeader(
              currentAccountPicture: CircleAvatar(
                child: Image.asset('assets/nyancat_bg.png'),
                backgroundColor: Colors.white,
              ),
              accountName: Text('NYAN CAT'),
              accountEmail: Text('nyancat@abc.com'),
              onDetailsPressed: () {
                debugPrint("arrow is clicked");
              },
              decoration: BoxDecoration(
                  color: Colors.indigo[400],
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20.0),
                      bottomRight: Radius.circular(20.0))),
            )
          ],
        ),
      ),
</code>```

screenshot

答:
Use ClipRRect

ex)

```<code>drawer: Drawer(
        child: ListView(
//           padding: EdgeInsets.zero,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20.0),
                  bottomRight: Radius.circular(20.0)),
              child: UserAccountsDrawerHeader(
                margin: EdgeInsets.zero,
                currentAccountPicture: CircleAvatar(
                  child: Image.asset('assets/nyancat_bg.png'),
                  backgroundColor: Colors.white,
                ),
                accountName: Text('NYAN CAT'),
                accountEmail: Text('nyancat@abc.com'),
                onDetailsPressed: () {
                  debugPrint("arrow is clicked");
                },
                decoration: BoxDecoration(
                  color: Colors.indigo[400],
//                   borderRadius: BorderRadius.only(
//                       bottomLeft: Radius.circular(20.0),
//                       bottomRight: Radius.circular(20.0)),
                ),
              ),
            ),
          ],
        ),
      ),
</code>```

안녕하세요!
https://open.kakao.com/o/gsshoXJ 로 오시면 더 자세하고 많은 이야기를 나누실 수 있습니다.

ContentLicense: CC BY-SA 4.0

Body:
I'm learning flutter.
I used the UserAccountsDrawerHeader widget using the Drawer widget, but when setting Radius, unnecessary line appears below.
How can you remove it?

Here's my code

drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            UserAccountsDrawerHeader(
              currentAccountPicture: CircleAvatar(
                child: Image.asset('assets/nyancat_bg.png'),
                backgroundColor: Colors.white,
              ),
              accountName: Text('NYAN CAT'),
              accountEmail: Text('nyancat@abc.com'),
              onDetailsPressed: () {
                debugPrint("arrow is clicked");
              },
              decoration: BoxDecoration(
                  color: Colors.indigo[400],
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(20.0),
                      bottomRight: Radius.circular(20.0))),
            )
          ],
        ),
      ),

screenshot

Body:
Use ClipRRect

ex)

drawer: Drawer(
        child: ListView(
//           padding: EdgeInsets.zero,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(20.0),
                  bottomRight: Radius.circular(20.0)),
              child: UserAccountsDrawerHeader(
                margin: EdgeInsets.zero,
                currentAccountPicture: CircleAvatar(
                  child: Image.asset('assets/nyancat_bg.png'),
                  backgroundColor: Colors.white,
                ),
                accountName: Text('NYAN CAT'),
                accountEmail: Text('nyancat@abc.com'),
                onDetailsPressed: () {
                  debugPrint("arrow is clicked");
                },
                decoration: BoxDecoration(
                  color: Colors.indigo[400],
//                   borderRadius: BorderRadius.only(
//                       bottomLeft: Radius.circular(20.0),
//                       bottomRight: Radius.circular(20.0)),
                ),
              ),
            ),
          ],
        ),
      ),

안녕하세요!
https://open.kakao.com/o/gsshoXJ 로 오시면 더 자세하고 많은 이야기를 나누실 수 있습니다.


问:
Adding a JSON elements to an Array of JSON in Javascript
I have JSON and JSON array and I want to push every elements of JSON to JSON array with some condition.

Here is my code:

```<code>let json = { Jack: 10, Merry: 29, Charles: 37, Lahm: 0 }
let jsonArray = [
    {
        match: {
            Ashley: 46,
        },
    },
]

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: `{${key}: ${json[key]}}`,
        })
    }
}

</code>```

I get the following response:

```<code>[
  { match: { Ashley: 46 } },
  { match: '{Jack: 10}' },
  { match: '{Merry: 29}' },
  { match: '{Charles: 37}' }
]

</code>```

The problem is that pushed elements has single quotes which I don't want.
Is there a way to push those elements without quotes?

答:
Note that you're not really working with JSON. JSON is a string representation of JavaScript objects. What you have is simply a plain JS object, and also an array of objects.

Your issue is that you're simply passing a string into match, and not an actual object, when you are using template literals.

Instead, use bracket notation to use the value of the key variable in your new match object, i.e.:

```<code>match: { [key]: json[key] }
</code>```

See proof-of-concept example:

let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

for (const key in myObject) {
  if (myObject[key] !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: myObject[key]
      }
    })
  }
}

console.log(myArrayOfObjects);```
</div>
</div>
</p>
<hr />
<p>This is also a good chance to explore the use of <code>Object.entries</code>, since it actually returns the a <code>[key, value]</code> tuple:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

Object.entries(myObject).forEach(([key, value]) => {
  if (value !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: value
      }
    })
  }
});

console.log(myArrayOfObjects);</code>```

Body:
I have JSON and JSON array and I want to push every elements of JSON to JSON array with some condition.

Here is my code:

let json = { Jack: 10, Merry: 29, Charles: 37, Lahm: 0 }
let jsonArray = [
    {
        match: {
            Ashley: 46,
        },
    },
]

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: `{${key}: ${json[key]}}`,
        })
    }
}

I get the following response:

[
  { match: { Ashley: 46 } },
  { match: '{Jack: 10}' },
  { match: '{Merry: 29}' },
  { match: '{Charles: 37}' }
]

The problem is that pushed elements has single quotes which I don't want.
Is there a way to push those elements without quotes?

Body:
Note that you're not really working with JSON. JSON is a string representation of JavaScript objects. What you have is simply a plain JS object, and also an array of objects.

Your issue is that you're simply passing a string into match, and not an actual object, when you are using template literals.

Instead, use bracket notation to use the value of the key variable in your new match object, i.e.:

match: { [key]: json[key] }

See proof-of-concept example:

let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

for (const key in myObject) {
  if (myObject[key] !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: myObject[key]
      }
    })
  }
}

console.log(myArrayOfObjects);

This is also a good chance to explore the use of Object.entries, since it actually returns the a [key, value] tuple:

let myObject = {
  Jack: 10,
  Merry: 29,
  Charles: 37,
  Lahm: 0
}
let myArrayOfObjects = [{
  match: {
    Ashley: 46,
  },
}, ]

Object.entries(myObject).forEach(([key, value]) => {
  if (value !== 0) {
    myArrayOfObjects.push({
      match: {
        [key]: value
      }
    })
  }
});

console.log(myArrayOfObjects);


问:
Why this import is not working
I'm using a the normalize function to get the absolute path from a String,

```<code>org.apache.commons.io.FilenameUtils.normalize(String)
</code>```

But when I use just normalize(String) I get :

The method normalize(String) is undefined for the type MyClass

I tried : import org.apache.commons.io.FilenameUtils;

I downloaded the library from Apache website, and linked it to my project but I get the same error.

I don't want to write everytime the whole line to call the function.

Is there any solution for this ?

Thanks

答:
keep the import as import org.apache.commons.io.FilenameUtils;
and invoke the method as FilenameUtils.normalize(string).

or change the import to import static org.apache.commons.io.FilenameUtils.normalize;
and leave the method invocation as it is (normalize(string)).

ContentLicense: CC BY-SA 3.0

Title: Why this import is not working

Body:
I'm using a the normalize function to get the absolute path from a String,

org.apache.commons.io.FilenameUtils.normalize(String)

But when I use just normalize(String) I get :

The method normalize(String) is undefined for the type MyClass

I tried : import org.apache.commons.io.FilenameUtils;

I downloaded the library from Apache website, and linked it to my project but I get the same error.

I don't want to write everytime the whole line to call the function.

Is there any solution for this ?

Thanks


问:
How to get value of variable call.data when use two IF statement
i have a problem hope someone can help me.

Ex:

```<code>@bot.callback_query_handler(func = lambda call: True)
    def xu_ly(call):
       if call.data == 'a':
         markup = sub_main_1_2()
         if call.data == 'a_1':
           markup = sub_main_1_2_1()
</code>```

i can't get value of call.data from button have callback_data = 'a_1'

Ple help me.

答:
Your structure is wrong. For sub_main_1_2_1() to run, the call.data has to be 'a' and 'a_1', which is impossible.

Unindent the second if statement:

```<code>@bot.callback_query_handler(func = lambda call: True)
    def xu_ly(call):
       if call.data == 'a':
         markup = sub_main_1_2()
       if call.data == 'a_1':
         markup = sub_main_1_2_1()
</code>```

Body:
i have a problem hope someone can help me.

Ex:

@bot.callback_query_handler(func = lambda call: True)
    def xu_ly(call):
       if call.data == 'a':
         markup = sub_main_1_2()
         if call.data == 'a_1':
           markup = sub_main_1_2_1()

i can't get value of call.data from button have callback_data = 'a_1'

Ple help me.

Body:
Your structure is wrong. For sub_main_1_2_1() to run, the call.data has to be 'a' and 'a_1', which is impossible.

Unindent the second if statement:

@bot.callback_query_handler(func = lambda call: True)
    def xu_ly(call):
       if call.data == 'a':
         markup = sub_main_1_2()
       if call.data == 'a_1':
         markup = sub_main_1_2_1()


问:
using X-PATH over other options
Why should I use functions to find elements, like find_elements_by_id or find_elements_by_class, when I can easily do that with find_elements_by_xpath?

(I know that in Selenium 4.0 we don't use these functions anymore, instead we use find_element(By.CLASS_NAME, "class")) but still, can someone explain it to me, I would very appreciate any advice)

答:
The "Class name" and "ID" of the elements don't often change to a different name. If you search for elements with xpath, it can change for example with every new section added to the page.

Example before a new section gets added:

```<code>find_element(By.CLASS_NAME, "class"))
find_element(By.ID, "id"))
find_element(By.XPATH, "div/div"))
</code>```

Example after a new section gets added:

```<code>find_element(By.CLASS_NAME, "class"))
find_element(By.ID, "id"))
find_element(By.XPATH, "div/div/div/a"))
</code>```

Result:
If you were finding elements with xpath, you'll have to change all the xpaths now. The class name and Id stayed the same.

A way more effective way is if you write your own xpath.

Example:

```<code>//a[contains(@class,'something')]
</code>```

How? -> https://www.guru99.com/xpath-selenium.html

Title: using X-PATH over other options

Body:
The "Class name" and "ID" of the elements don't often change to a different name. If you search for elements with xpath, it can change for example with every new section added to the page.

Example before a new section gets added:

find_element(By.CLASS_NAME, "class"))
find_element(By.ID, "id"))
find_element(By.XPATH, "div/div"))

Example after a new section gets added:

find_element(By.CLASS_NAME, "class"))
find_element(By.ID, "id"))
find_element(By.XPATH, "div/div/div/a"))

Result:
If you were finding elements with xpath, you'll have to change all the xpaths now. The class name and Id stayed the same.

A way more effective way is if you write your own xpath.

Example:

//a[contains(@class,'something')]

How? -> https://www.guru99.com/xpath-selenium.html


问:
Python PIL.Image.tobytes() gives invalid bytes for image
When I run this pillow code:

from PIL import Image

image = Image.open(BytesIO(some_bytes))
resized = image.resize((44, 44))
with open('filename.png', 'wb') as file:
    file.write(resized.tobytes())
```

No errors occur, but when I go to the file 'filename.png', my computer or any other software can't show the file, presumably because the bytes are invalid. Why is this so?

resized.tobytes() seems to return bytes, so I'm not sure why the picture's bytes are invalid. When I just write my normal bytes to filename.png it works, so that isn't invalid. Only the resized ones are.

Why is this so and how can I fix it?

答:
Answered by Jason Yang in comments -

Method Image.tobytes returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data.

Body:
When I run this pillow code:

from PIL import Image

image = Image.open(BytesIO(some_bytes))
resized = image.resize((44, 44))
with open('filename.png', 'wb') as file:
    file.write(resized.tobytes())

No errors occur, but when I go to the file 'filename.png', my computer or any other software can't show the file, presumably because the bytes are invalid. Why is this so?

resized.tobytes() seems to return bytes, so I'm not sure why the picture's bytes are invalid. When I just write my normal bytes to filename.png it works, so that isn't invalid. Only the resized ones are.

Why is this so and how can I fix it?


问:
WCF invoking service fail
I was able to call it in my own server and it works but the problem occurs when I host wcf service in IIS. The details of this error are as follows...

Failed to invoke the service. Possible causes: The service is offline
  or inaccessible; the client-side configuration does not match the
  proxy; the existing proxy is invalid. Refer to the stack trace for
  more detail. You can try to recover by starting a new proxy, restoring
  to default configuration, or refreshing the service.

Stack Trace Error Details

The server was unable to process the request due to an internal error.
  For more information about the error, either turn on
  IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
  or from the <serviceDebug> configuration behavior) on the server in
  order to send the exception information back to the client, or turn on
  tracing as per the Microsoft .NET Framework 3.0 SDK documentation and
  inspect the server trace logs.

Server stack trace:

  at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
  reply, MessageFault fault, String action, MessageVersion version,
  FaultConverter faultConverter)

  at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
  operation, ProxyRpc& rpc)

  at System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)

  at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)

  at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:

  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)

  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)

  at IUserService.GetUser(String UserID)

  at UserServiceClient.GetUser(String UserID)

Here are the source codes:

app.config file from wcfservicelirbrary

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

<system.web>
<compilation debug="true" />
</system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
        <endpoint address="" binding="wsHttpBinding"      contract="UserServiceLibrary.IUserService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/UserServiceLibrary/UserService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

Web config file from WCF Website Host

```<code><?xml version="1.0"?>
 <configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
       <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
  contract="IMetadataExchange" />
       <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
  contract="UserServiceLibrary.IUserService" />
       <endpoint address="" binding="wsHttpBinding" contract="UserServiceLibrary.IUserService" />
      </service>
    </services>
    <behaviors>
     <serviceBehaviors>
       <behavior>

         <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
</code>```

答:
As usual with WCF errors, the key is most likely right at the bottom of the stack trace:

   UserServiceClient.GetUser(String UserID)

This was what caused the error in the first place.

To check, if you have access to the server, try attaching a Visual Studio debugger to the IIS service (usually w3wp.exe) that hosts your WCF code. (Do this though Debug | Attach to Process...; you'll need be running with Administrator privileges, and check "on" the "View processes from all users" option).

If you don't have direct access to attach a debugger to the service but can tweak the configuration file for the service, then try the WCF diagnostic traces (documented on MSDN here). This lets you create logs that can be viewed with the Service Trace Viewer - you should be able to find much more information on the exception very easily using this.

A hunch: is UserID null, by any chance? If so, and you're not expecting it to be, has the service contract changed recently? Adding System.Runtime.Serialization to the diagnostic trace for the Service Viewer can bring up some more information on that: details here.

Title: WCF invoking service fail

Body:
I was able to call it in my own server and it works but the problem occurs when I host wcf service in IIS. The details of this error are as follows...

Failed to invoke the service. Possible causes: The service is offline
  or inaccessible; the client-side configuration does not match the
  proxy; the existing proxy is invalid. Refer to the stack trace for
  more detail. You can try to recover by starting a new proxy, restoring
  to default configuration, or refreshing the service.

Stack Trace Error Details

The server was unable to process the request due to an internal error.
  For more information about the error, either turn on
  IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute
  or from the <serviceDebug> configuration behavior) on the server in
  order to send the exception information back to the client, or turn on
  tracing as per the Microsoft .NET Framework 3.0 SDK documentation and
  inspect the server trace logs.

Server stack trace:

  at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message
  reply, MessageFault fault, String action, MessageVersion version,
  FaultConverter faultConverter)

  at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
  operation, ProxyRpc& rpc)

  at System.ServiceModel.Channels.ServiceChannel.Call(String action,
  Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
  Object[] outs, TimeSpan timeout)

  at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
  methodCall, ProxyOperationRuntime operation)

  at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
  message)

Exception rethrown at [0]:

  at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
  reqMsg, IMessage retMsg)

  at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
  msgData, Int32 type)

  at IUserService.GetUser(String UserID)

  at UserServiceClient.GetUser(String UserID)

Here are the source codes:

app.config file from wcfservicelirbrary

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

<system.web>
<compilation debug="true" />
</system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
        <endpoint address="" binding="wsHttpBinding"      contract="UserServiceLibrary.IUserService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8732/Design_Time_Addresses/UserServiceLibrary/UserService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Web config file from WCF Website Host

<?xml version="1.0"?>
 <configuration>

  <system.web>
    <compilation debug="false" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="UserServiceLibrary.UserService">
       <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
  contract="IMetadataExchange" />
       <endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
  contract="UserServiceLibrary.IUserService" />
       <endpoint address="" binding="wsHttpBinding" contract="UserServiceLibrary.IUserService" />
      </service>
    </services>
    <behaviors>
     <serviceBehaviors>
       <behavior>

         <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
       </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
   <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


问:
Jest unexpected token - Typescript import
I am getting the following error when I run jest. It looks like the cause is Typescript-related but I have some typescript handling in the package.json, so I'm not sure why it wouldn't be handled.

```<code>Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

...

Details:

    /Users/ryancocuzzo/ex/test/example/mobile-app/node_modules/react-native-fs/FS.common.js:30
    var normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path);
                                 ^

    SyntaxError: Unexpected token ':'

    > 1 | import RNFS from "react-native-fs";
</code>```

The library in question is react-native-fs.

package.json:

```<code>"jest": {
    "preset": "react-native",
    "setupFiles": [
      "./setupTests.js",
      "./node_modules/react-native-gesture-handler/jestSetup.js"
    ],
    "transform": {
      "^.+\\.ts?$": "ts-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.js$": "./node_modules/react-native/jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    }
  }
</code>```

Info:

```<code>react: 17.0.1
react-native: 0.64.1
react-native-fs: 2.18.0
ts-jest: 27.1.3
jest: 26.6.3
babel-jest: 26.6.3
</code>```

答:
Use the <rootDir> string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories.

You also need to set the test environment for your react-native tests. so that it mimics the environment of a React Native app as it  doesn't load any DOM or browser APIs, which would greatly improves Jest's startup time.

{
  //...

  "testEnvironment": "node",

  "transform": {
    "^.+\\.ts?$": "ts-jest",
    "^.+\\.tsx?$": "ts-jest",
   // use <rootDir> absolute path here
    "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
  },

}

```

Body:
I am getting the following error when I run jest. It looks like the cause is Typescript-related but I have some typescript handling in the package.json, so I'm not sure why it wouldn't be handled.

Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

...

Details:

    /Users/ryancocuzzo/ex/test/example/mobile-app/node_modules/react-native-fs/FS.common.js:30
    var normalizeFilePath = (path: string) => (path.startsWith('file://') ? path.slice(7) : path);
                                 ^

    SyntaxError: Unexpected token ':'

    > 1 | import RNFS from "react-native-fs";

The library in question is react-native-fs.

package.json:

"jest": {
    "preset": "react-native",
    "setupFiles": [
      "./setupTests.js",
      "./node_modules/react-native-gesture-handler/jestSetup.js"
    ],
    "transform": {
      "^.+\\.ts?$": "ts-jest",
      "^.+\\.tsx?$": "ts-jest",
      "^.+\\.js$": "./node_modules/react-native/jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)?$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    }
  }

Info:

react: 17.0.1
react-native: 0.64.1
react-native-fs: 2.18.0
ts-jest: 27.1.3
jest: 26.6.3
babel-jest: 26.6.3


问:
Postfix ignoring first line of hash table
My access table look:

```<code>ban@test.local REJECT
test@test.local OK
</code>```

The first line does not working, but, if i try this:

```<code># Some comment or another access rule
ban@test.local REJECT
test@test.local OK
</code>```

Line "ban@test.local REJECT" successfully rejecting address
I.e. postfix first line skips, always

PS: main.cf:

```<code>check_sender_access hash:/path/to/access_table
</code>```

答:
So, the problem is character encoding when saving utf8 files with "BOM" in bdb

Curve file encoding: Unicode text, UTF-8 (with BOM) text

Normal file encoding: Unicode text, UTF-8 text

At the beginning of the line, characters were inserted: \ef\bb\ then, the address was perceived incorrectly.

If you open the bearkley db file, you can immediately see the characters of the BOM encoding (\ef\bb):

```<code>$ db_dump -p bad_access_table.db
VERSION=3
format=print
type=hash
h_nelem=4097
db_pagesize=4096
HEADER=END
 \ef\bb\bfban@test.local\00
 REJECT\00
 test@test.local\00
 OK\00
DATA=END
</code>```

Saving the file in UTF-8 as a solution!

Body:
My access table look:

ban@test.local REJECT
test@test.local OK

The first line does not working, but, if i try this:

# Some comment or another access rule
ban@test.local REJECT
test@test.local OK

Line "ban@test.local REJECT" successfully rejecting address
I.e. postfix first line skips, always

PS: main.cf:

check_sender_access hash:/path/to/access_table

Body:
So, the problem is character encoding when saving utf8 files with "BOM" in bdb

Curve file encoding: Unicode text, UTF-8 (with BOM) text

Normal file encoding: Unicode text, UTF-8 text

At the beginning of the line, characters were inserted: \ef\bb\ then, the address was perceived incorrectly.

If you open the bearkley db file, you can immediately see the characters of the BOM encoding (\ef\bb):

$ db_dump -p bad_access_table.db
VERSION=3
format=print
type=hash
h_nelem=4097
db_pagesize=4096
HEADER=END
 \ef\bb\bfban@test.local\00
 REJECT\00
 test@test.local\00
 OK\00
DATA=END

Saving the file in UTF-8 as a solution!


问:
Making `volume` in docker-compose.yml work earlier than dockerfile
my docker-compose.yml

```<code>version: "3.9"
services:
  admin_site:
    build:
      context: ./
      dockerfile: Dockerfile.local
    volumes:
      - .:/usr/src/app
    ports:
      - "8010:8010"
    restart: always
</code>```

I want to mount current folder to /usr/src/app

Dockerfile.local

```<code>FROM python:3.9.5
ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get install -y netcat
WORKDIR /usr/src/app

RUN pip install pipenv
RUN pipenv install --dev --system
</code>```

When I try to docker compose -f docker-compose.yml build

This error occurs.

ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting.

I guess it means there is no Pipfile

However There is Pipfile in my current directly.

So I guess volumes: doesn't work before Dockerfile?

How can I solve this problem?

答:
Mounts always apply to Container and not to the Image Build.
So would use

```<code># DO
# $ pipenv lock --dev --requirements > requirements.txt
# before build!
COPY requirements*.txt ./
RUN python -m pip --no-cache-dir install -r requirements.txt
</code>```

This is not using your Pipenv-File, you have to manually generate the requirements-file. There are some benefits doing it like that:

Packages in Docker-Image can't be changed by accident

You can define versions for dependencies separately, very helpful if you have bugs in dependency-packages, but need to update the main package

Pipenv does not run lock on image build (takes ages every time)

Furthermore copying whole folder forces docker build to not reuse this layer on any file change.

Body:
my docker-compose.yml

version: "3.9"
services:
  admin_site:
    build:
      context: ./
      dockerfile: Dockerfile.local
    volumes:
      - .:/usr/src/app
    ports:
      - "8010:8010"
    restart: always

I want to mount current folder to /usr/src/app

Dockerfile.local

FROM python:3.9.5
ENV PYTHONUNBUFFERED 1
RUN apt-get update && apt-get install -y netcat
WORKDIR /usr/src/app

RUN pip install pipenv
RUN pipenv install --dev --system

When I try to docker compose -f docker-compose.yml build

This error occurs.

ERROR:: --system is intended to be used for pre-existing Pipfile installation, not installation of specific packages. Aborting.

I guess it means there is no Pipfile

However There is Pipfile in my current directly.

So I guess volumes: doesn't work before Dockerfile?

How can I solve this problem?

Body:
Mounts always apply to Container and not to the Image Build.
So would use

# DO
# $ pipenv lock --dev --requirements > requirements.txt
# before build!
COPY requirements*.txt ./
RUN python -m pip --no-cache-dir install -r requirements.txt

This is not using your Pipenv-File, you have to manually generate the requirements-file. There are some benefits doing it like that:

Packages in Docker-Image can't be changed by accident

You can define versions for dependencies separately, very helpful if you have bugs in dependency-packages, but need to update the main package

Pipenv does not run lock on image build (takes ages every time)

Furthermore copying whole folder forces docker build to not reuse this layer on any file change.


问:
dynamic collection name using python mongoengine
I want to use MongoDB for storing API logs.
For this matter, I want to use the approach mentioned here, using weekly or monthly collections for storing logs and dropping them on expiration, therefore I need to be able to set collection names dynamically based on date.
Is there any way to do this using mongoengine?

I've tried the meta option on the collection but it does not work since it's only used once when the collection definition is being interpreted and it's not meant to use for my intended behavior.

Also, I'm open to any alternative approach.

答:
I've found that MongoDB has no job scheduling built-in and that mongoengine has no mechanism for changing the name of the collection corresponding to a document class.

Eventually, I found that it's better to use the os job scheduler like cron to handle this kind of task.

links for help:

running commands in mongo using shell scrips

also running commands in mongo using shell scrips


问:
Visual Studio Code cant locate my python interpreter
I can run python in the terminal but it shows that the python interpreter is not found and when I run the file it shows the python path in your debug configuration is invalid.

click to see image

when i click on select python interpreter, it shows this, and yes the file path is completely valid

python works perfectly fine in terminal

答: Try the Python Extension in VS-Code. Go on the left to "Extensions", type "Python", go for the first one or which ever you like (I chose the first). You´ll probably need to select your python interpreter again after this</p>


问:
how to goto a page by code?
I tried using window.location="#pageLogin".
It works in my desktop but appears a blank in my android device.

After doing some search,I uses $.mobile.changePage like this

```<code>var user;
$(document).ready(function(){
    user=GetCurrUser();
    if(user==null){
            $.mobile.changePage("#pageLogin", {
            transition: "pop",
            reverse: false,
            changeHash: false
        });
    }
});
</code>```

Still nothing appears,even on desktop (Chrome).

Is there any better way to do that?

UPDATE
The error message in firebug of $.mobile.changePage is
settings.pageContainer is undefined

答:
The jQuery Mobile way works for me, here's the example of code:

```<code>$.mobile.changePage($("#dashboard"), "none");
</code>```

Not sure what could be your error. Can you try to reproduce it in jsFiddle?

Title: how to goto a page by code?

Body:
I tried using window.location="#pageLogin".
It works in my desktop but appears a blank in my android device.

After doing some search,I uses $.mobile.changePage like this

var user;
$(document).ready(function(){
    user=GetCurrUser();
    if(user==null){
            $.mobile.changePage("#pageLogin", {
            transition: "pop",
            reverse: false,
            changeHash: false
        });
    }
});

Still nothing appears,even on desktop (Chrome).

Is there any better way to do that?

UPDATE
The error message in firebug of $.mobile.changePage is
settings.pageContainer is undefined

Body:
The jQuery Mobile way works for me, here's the example of code:

$.mobile.changePage($("#dashboard"), "none");

Not sure what could be your error. Can you try to reproduce it in jsFiddle?


问:
ReactJS:Input on controlled component doesn't change state
I have an object literal with some empty values that I want to change according to a list of inputs. The problem is that, though the value of the input is updated with a predefined value in useEffect(), I can't change the input with the onChange handler. This is what I have:

```<code>const userValues = {
  username:'',
  city:'',
  country:'',
  description:''
}

function Comp(){
 const  [details, setDetails] = useState(userValues)

 useEffect(() => {
    setUserDetails()
  }, [details])

async function setUserDetails() {
      setDetails({...details,
      username: "username",
      country: "country",
      city: "city"
      })
}
const handleInputChange = (e) =>{
    const {name,value} = e.target
    setDetails({
      ...details,
      [name]:value
    })

   <Input fontSize="20px" w="sm" mr={5} fontWeight="bold" textAlign="center"
               value={details.username} onChange={(e)=>handleInputChange(e)}/>
}
</code>```

I have also tried to set the value directly in the onChange event

```<code>onChange={(e)=>setDetails({...details,[e.target.name]:e.target.value})}}
</code>```

but the input won't change from the default value. Maybe someone can point me into the right direction. I followed this tutorial https://dev.to/deboragaleano/how-to-handle-multiple-inputs-in-react-55el Any help would be appreciated!

答:
You have to set the correct name attribute to you input element e.g.:

```<code>  return (
    <Input

      name="userName"
      value={details.username}

      fontSize="20px"
      w="sm"
      mr={5}
      fontWeight="bold"
      textAlign="center"
      onChange={(e) => handleInputChange(e)}
    />
  )
</code>```

The second issue is the following effect:

```<code>useEffect(() => {
    setUserDetails()
  }, [details])
</code>```

This code will reset details whenever details changes.

You will have to delete this effect or at least remove details from the dependency array e.g.:

```<code>const  [details, setDetails] = useState(() => {
  return {
      username: "username",
      country: "country",
      city: "city"
  };
});
</code>```

or

```<code>useEffect(() => {
    setUserDetails()
  }, [])
</code>```

Body:
I have an object literal with some empty values that I want to change according to a list of inputs. The problem is that, though the value of the input is updated with a predefined value in useEffect(), I can't change the input with the onChange handler. This is what I have:

const userValues = {
  username:'',
  city:'',
  country:'',
  description:''
}

function Comp(){
 const  [details, setDetails] = useState(userValues)

 useEffect(() => {
    setUserDetails()
  }, [details])

async function setUserDetails() {
      setDetails({...details,
      username: "username",
      country: "country",
      city: "city"
      })
}
const handleInputChange = (e) =>{
    const {name,value} = e.target
    setDetails({
      ...details,
      [name]:value
    })

   <Input fontSize="20px" w="sm" mr={5} fontWeight="bold" textAlign="center"
               value={details.username} onChange={(e)=>handleInputChange(e)}/>
}

I have also tried to set the value directly in the onChange event

onChange={(e)=>setDetails({...details,[e.target.name]:e.target.value})}}

but the input won't change from the default value. Maybe someone can point me into the right direction. I followed this tutorial https://dev.to/deboragaleano/how-to-handle-multiple-inputs-in-react-55el Any help would be appreciated!

Body:
You have to set the correct name attribute to you input element e.g.:

  return (
    <Input

      name="userName"
      value={details.username}

      fontSize="20px"
      w="sm"
      mr={5}
      fontWeight="bold"
      textAlign="center"
      onChange={(e) => handleInputChange(e)}
    />
  )

The second issue is the following effect:

useEffect(() => {
    setUserDetails()
  }, [details])

This code will reset details whenever details changes.

You will have to delete this effect or at least remove details from the dependency array e.g.:

const  [details, setDetails] = useState(() => {
  return {
      username: "username",
      country: "country",
      city: "city"
  };
});

or

useEffect(() => {
    setUserDetails()
  }, [])


问:
How to cast object correctly
I have this code:

https://dotnetfiddle.net/21G0of

Basically I am curious, about how to cast the object2 - ResponseErrorForSlack to the same format as is the object1 - it should be the same - as can be seen when I serialize both objects to JSON, but when I use JsonResult - the content of the object is different.

Code overview:

```<code>public class Program
{
    public static void Main()
    {
        Dictionary<string, string> dict = new();
        dict.Add("endOfShiftBlock" ,"End time must be later than start time!");
        object object1 = new { response_action = "errors", errors = dict };

        ResponseErrorForSlack object2 = new("errors", "endOfShiftBlock", "End time must be later than start time!");

        string json1 = JsonConvert.SerializeObject(object1);
        string json2 = JsonConvert.SerializeObject(object2);

        Console.WriteLine("This is Json from Object1 :" + json1);
        Console.WriteLine("This is Json from Object2 :" + json2);
        Console.WriteLine();

        JsonResult jr1 = new JsonResult(object1);
        JsonResult jr2 = new JsonResult(object2);

        Console.WriteLine("This is correct:      " + jr1.Value);
        Console.WriteLine("This is not correct:  " + jr2.Value);
    }

}
class ResponseErrorForSlack
{
    public ResponseErrorForSlack(string responseAction,string blockId = null, string error = null)
    {
        ResponseAction = responseAction;
        if(blockId is not null && error is not null)
        {
            Errors = new()
            {
                { blockId, error }
            };
        }
    }

    public ResponseErrorForSlack(string responseAction, Dictionary<string, string> errors)
    {
        ResponseAction = responseAction;
        if (errors is not null)
        {
            Errors = errors;
        }
    }

    [JsonProperty("response_action")]
    public string ResponseAction { get; set; }
    [JsonProperty("errors")]
    public Dictionary<string, string> Errors { get; set; }
}
</code>```

答:
What you see in your Console is the output of ToString().

Add the following override to your class ResponseErrorForSlack:

```<code>    public override string ToString() {
        return "Test";
    }
</code>```

and you will see following output:

```<code>This is Json from Object1 :{"response_action":"errors","errors":{"endOfShiftBlock":"End time must be later than start time!"}}
This is Json from Object2 :{"response_action":"errors","errors":{"endOfShiftBlock":"End time must be later than start time!"}}

This is correct:      { response_action = errors, errors = System.Collections.Generic.Dictionary`2[System.String,System.String] }
This is not correct:  Test
</code>```

A check after your Console.WriteLines, shows up in output as well.

```<code>        if (jr2.Value.GetType() == typeof(ResponseErrorForSlack))
        {
            Console.WriteLine("Yeah its correct");
        }
</code>```

Title: How to cast object correctly

Body:
I have this code:

https://dotnetfiddle.net/21G0of

Basically I am curious, about how to cast the object2 - ResponseErrorForSlack to the same format as is the object1 - it should be the same - as can be seen when I serialize both objects to JSON, but when I use JsonResult - the content of the object is different.

Code overview:

public class Program
{
    public static void Main()
    {
        Dictionary<string, string> dict = new();
        dict.Add("endOfShiftBlock" ,"End time must be later than start time!");
        object object1 = new { response_action = "errors", errors = dict };

        ResponseErrorForSlack object2 = new("errors", "endOfShiftBlock", "End time must be later than start time!");

        string json1 = JsonConvert.SerializeObject(object1);
        string json2 = JsonConvert.SerializeObject(object2);

        Console.WriteLine("This is Json from Object1 :" + json1);
        Console.WriteLine("This is Json from Object2 :" + json2);
        Console.WriteLine();

        JsonResult jr1 = new JsonResult(object1);
        JsonResult jr2 = new JsonResult(object2);

        Console.WriteLine("This is correct:      " + jr1.Value);
        Console.WriteLine("This is not correct:  " + jr2.Value);
    }

}
class ResponseErrorForSlack
{
    public ResponseErrorForSlack(string responseAction,string blockId = null, string error = null)
    {
        ResponseAction = responseAction;
        if(blockId is not null && error is not null)
        {
            Errors = new()
            {
                { blockId, error }
            };
        }
    }

    public ResponseErrorForSlack(string responseAction, Dictionary<string, string> errors)
    {
        ResponseAction = responseAction;
        if (errors is not null)
        {
            Errors = errors;
        }
    }

    [JsonProperty("response_action")]
    public string ResponseAction { get; set; }
    [JsonProperty("errors")]
    public Dictionary<string, string> Errors { get; set; }
}

Body:
What you see in your Console is the output of ToString().

Add the following override to your class ResponseErrorForSlack:

    public override string ToString() {
        return "Test";
    }

and you will see following output:

This is Json from Object1 :{"response_action":"errors","errors":{"endOfShiftBlock":"End time must be later than start time!"}}
This is Json from Object2 :{"response_action":"errors","errors":{"endOfShiftBlock":"End time must be later than start time!"}}

This is correct:      { response_action = errors, errors = System.Collections.Generic.Dictionary`2[System.String,System.String] }
This is not correct:  Test

A check after your Console.WriteLines, shows up in output as well.

        if (jr2.Value.GetType() == typeof(ResponseErrorForSlack))
        {
            Console.WriteLine("Yeah its correct");
        }


问:
Import HTML as string and test with Jest
I'm using sveltekit and I can't use the files api to import html templates. So I decided to import by writing a module that imports the content of the document as a string (described here).

```<code>// src/global.d.ts

/// <reference types="@sveltejs/kit" />
declare module '*.html' {
  const content: string
  export default content
}
</code>```

So far so good, but now I need to test the code and jest can't interpret the code.

```<code>● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
                                                                                ^

SyntaxError: Unexpected token '<'
</code>```

I don't understand how jest understands the .d.ts files... How do I get to test the code?

答:
Do you install @babel/plugin-transform-runtime"?

I share my config for jest/svelte-jester..

I have:

jsconfig.json

```<code>{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "$lib": ["src/lib"],
            "$lib/*": ["src/lib/*"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"],

}
</code>```

svelte.config.js

```<code> import vercel from '@sveltejs/adapter-vercel'

/** @type {import('@sveltejs/kit').Config} */
const config = {

    kit: {
        adapter: vercel(),
        vite: {
            define: {
              'process.env': process.env,
            },
          },

    },
    transform: {
        "^.+\\.svelte$": ["svelte-jester", { "preprocess": true }]
      }
};

export default config;
</code>```

babel.config.json

```<code>{
  "presets": [
    ["@babel/preset-env", { "modules": "auto" }]
  ],
    "plugins": ["babel-plugin-transform-vite-meta-env","@babel/plugin-transform-runtime"]
}
</code>```

jest.config.js

```<code>export default {
  "transform": {
    "^.+\\.js$": "babel-jest",
   "^.+\\.svelte$": "svelte-jester",

 },
 "moduleFileExtensions": ["svelte", "js"],
  "testEnvironment": "jsdom",
  "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"]

  }
</code>```

and whole package.json

```<code>{
  "name": "sveltekit",
  "version": "0.0.1",
  "scripts": {
    "dev": "svelte-kit dev",
    "build": "svelte-kit build",
    "package": "svelte-kit package",
    "preview": "svelte-kit preview",
    "test": "jest src",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/plugin-transform-modules-commonjs": "^7.16.8",
    "@babel/plugin-transform-runtime": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "@supabase/supabase-js": "^1.29.1",
    "@sveltejs/adapter-auto": "^1.0.0-next.7",
    "@sveltejs/kit": "^1.0.0-next.215",
    "@sveltejs/svelte-virtual-list": "^3.0.1",
    "@testing-library/svelte": "^3.0.3",
    "autoprefixer": "^10.4.1",
    "babel-jest": "^27.4.6",
    "babel-plugin-transform-vite-meta-env": "^1.0.3",
    "jest": "^27.4.7",
    "postcss-load-config": "^3.1.1",
    "prettier": "^2.5.1",
    "prettier-plugin-svelte": "^2.5.1",
    "svelte": "^3.44.0",
    "svelte-jester": "^2.1.5",
    "svelte-lazy": "^1.0.12",
    "tailwindcss": "^3.0.8",
    "ts-jest": "^27.1.3"
  },
  "type": "module",
  "dependencies": {
    "@fontsource/fira-mono": "^4.5.0",
    "@lukeed/uuid": "^2.0.0",
    "@testing-library/jest-dom": "^5.16.1",
    "cookie": "^0.4.1",
    "svelte-lazy-image": "^0.2.0",
    "swiper": "^8.0.3"
  },
  "testEnvironment": "jsdom"
}
</code>```

I hope it will help you.I had a lot of troubles too with setting up jest..

Body:
I'm using sveltekit and I can't use the files api to import html templates. So I decided to import by writing a module that imports the content of the document as a string (described here).

// src/global.d.ts

/// <reference types="@sveltejs/kit" />
declare module '*.html' {
  const content: string
  export default content
}

So far so good, but now I need to test the code and jest can't interpret the code.

● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/home/developer/workspace/src/assets/html/confirm_email.html:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<!DOCTYPE html>
                                                                                ^

SyntaxError: Unexpected token '<'

I don't understand how jest understands the .d.ts files... How do I get to test the code?

Body:
Do you install @babel/plugin-transform-runtime"?

I share my config for jest/svelte-jester..

I have:

jsconfig.json

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "$lib": ["src/lib"],
            "$lib/*": ["src/lib/*"]
        }
    },
    "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"],

}

svelte.config.js

 import vercel from '@sveltejs/adapter-vercel'

/** @type {import('@sveltejs/kit').Config} */
const config = {

    kit: {
        adapter: vercel(),
        vite: {
            define: {
              'process.env': process.env,
            },
          },

    },
    transform: {
        "^.+\\.svelte$": ["svelte-jester", { "preprocess": true }]
      }
};

export default config;

babel.config.json

{
  "presets": [
    ["@babel/preset-env", { "modules": "auto" }]
  ],
    "plugins": ["babel-plugin-transform-vite-meta-env","@babel/plugin-transform-runtime"]
}

jest.config.js

export default {
  "transform": {
    "^.+\\.js$": "babel-jest",
   "^.+\\.svelte$": "svelte-jester",

 },
 "moduleFileExtensions": ["svelte", "js"],
  "testEnvironment": "jsdom",
  "setupFilesAfterEnv": ["@testing-library/jest-dom/extend-expect"]

  }

and whole package.json

{
  "name": "sveltekit",
  "version": "0.0.1",
  "scripts": {
    "dev": "svelte-kit dev",
    "build": "svelte-kit build",
    "package": "svelte-kit package",
    "preview": "svelte-kit preview",
    "test": "jest src",
    "test:watch": "npm run test -- --watch"
  },
  "devDependencies": {
    "@babel/core": "^7.16.12",
    "@babel/plugin-transform-modules-commonjs": "^7.16.8",
    "@babel/plugin-transform-runtime": "^7.17.0",
    "@babel/preset-env": "^7.16.11",
    "@supabase/supabase-js": "^1.29.1",
    "@sveltejs/adapter-auto": "^1.0.0-next.7",
    "@sveltejs/kit": "^1.0.0-next.215",
    "@sveltejs/svelte-virtual-list": "^3.0.1",
    "@testing-library/svelte": "^3.0.3",
    "autoprefixer": "^10.4.1",
    "babel-jest": "^27.4.6",
    "babel-plugin-transform-vite-meta-env": "^1.0.3",
    "jest": "^27.4.7",
    "postcss-load-config": "^3.1.1",
    "prettier": "^2.5.1",
    "prettier-plugin-svelte": "^2.5.1",
    "svelte": "^3.44.0",
    "svelte-jester": "^2.1.5",
    "svelte-lazy": "^1.0.12",
    "tailwindcss": "^3.0.8",
    "ts-jest": "^27.1.3"
  },
  "type": "module",
  "dependencies": {
    "@fontsource/fira-mono": "^4.5.0",
    "@lukeed/uuid": "^2.0.0",
    "@testing-library/jest-dom": "^5.16.1",
    "cookie": "^0.4.1",
    "svelte-lazy-image": "^0.2.0",
    "swiper": "^8.0.3"
  },
  "testEnvironment": "jsdom"
}

I hope it will help you.I had a lot of troubles too with setting up jest..


问:
How to make a font thinner on web
I'm trying to design a website and have a problem with font style and size. I looked at many websites to get some ideas for example if you look at this website: http://www.albionwestcoast.com/ and check the font style and size for the name of the team members on the right side you can see they apparently used Georgia for that (in red) but when I try to get the same shape my font appears a bit bolder and fatter and I don't know why.

This is the style I've got:

```<code>font-size: 2em;
font-family: Georgia,'Times New Roman',serif;
font-style: italic;
font-weight: normal;
</code>```

am I missing anything to get the same effect?

答:
Yesterday I looked for a way how to make a font thinner if I can't change font-weight.

There is a problem, that on windows and mac fonts look different, they use different algorithms of smoothings.
(see https://github.com/vector-im/element-web/issues/11425)

So, if we force the browser to smooth a font identically then the font gets thicker.

And I have found a solution!

```<code>font-variant-ligatures: common-ligatures;
</code>```

Title: How to make a font thinner on web

Body:
I'm trying to design a website and have a problem with font style and size. I looked at many websites to get some ideas for example if you look at this website: http://www.albionwestcoast.com/ and check the font style and size for the name of the team members on the right side you can see they apparently used Georgia for that (in red) but when I try to get the same shape my font appears a bit bolder and fatter and I don't know why.

This is the style I've got:

font-size: 2em;
font-family: Georgia,'Times New Roman',serif;
font-style: italic;
font-weight: normal;

am I missing anything to get the same effect?

Body:
Yesterday I looked for a way how to make a font thinner if I can't change font-weight.

There is a problem, that on windows and mac fonts look different, they use different algorithms of smoothings.
(see https://github.com/vector-im/element-web/issues/11425)

So, if we force the browser to smooth a font identically then the font gets thicker.

And I have found a solution!

font-variant-ligatures: common-ligatures;


答:
The problem is that you are pushing an object with a template string in it to the array. You need to change the syntax a little bit.</p>
```<code>for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: {[key]: json[key]}
        })
    }
}
</code>```

Title: Adding a JSON elements to an Array of JSON in Javascript

Body:
I have JSON and JSON array and I want to push every elements of JSON to JSON array with some condition.

Here is my code:

let json = { Jack: 10, Merry: 29, Charles: 37, Lahm: 0 }
let jsonArray = [
    {
        match: {
            Ashley: 46,
        },
    },
]

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: `{${key}: ${json[key]}}`,
        })
    }
}

I get the following response:

[
  { match: { Ashley: 46 } },
  { match: '{Jack: 10}' },
  { match: '{Merry: 29}' },
  { match: '{Charles: 37}' }
]

The problem is that pushed elements has single quotes which I don't want.
Is there a way to push those elements without quotes?

Body:
The problem is that you are pushing an object with a template string in it to the array. You need to change the syntax a little bit.

for (const key in json) {
    if (json[key] !== 0) {
        jsonArray.push({
            match: {[key]: json[key]}
        })
    }
}


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答:
What do you need to set up? The values are created when the class loads, and as it's an enum, no other values can be created (unless you add them to the source and recompile).

That's the point of an enum, to be able to give limit a type to an explicit range of constant, immutable values. Now, anywhere in your code, you can refer to a type Car, or its values, Car.NANO, Car.MERCEDES, etc.

If, on the other hand, you have a set of values that isn't an explicit range, and you want to be able to create arbitrary objects of this type, you'd use the same ctor as in your post, but as a regular, not enum class. Then Spring provides various helper clases to read values from some source (XML file, config file, whatever) and create Lists of that type.

OwnerDisplayName: Olivier

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

OwnerDisplayName: tpdi

ContentLicense: CC BY-SA 2.5


问:
How save a entire text file to a array and display in textbox
```<code>string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}
</code>```

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

答:
You would need to append the subsequent text to the current value you have, but not reassign.

Also remember to set your Textbox Multiline Property to True to display all text.

```<code>public Form1()
        {
            InitializeComponent();
            string[] readText = File.ReadAllLines(@"C:\testfile.txt");
            int counter = 0;
            foreach (string s in readText)
            {
                if (counter == 0)
                {
                    textBox1.Text = string.Join(",", s);
                }
                else
                {
                    textBox1.Text = textBox1.Text + string.Join(",", s);
                }
                textBox1.AppendText(Environment.NewLine);
                counter++;
            }
        }
</code>```

Body:
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

Body:
You would need to append the subsequent text to the current value you have, but not reassign.

Also remember to set your Textbox Multiline Property to True to display all text.

public Form1()
        {
            InitializeComponent();
            string[] readText = File.ReadAllLines(@"C:\testfile.txt");
            int counter = 0;
            foreach (string s in readText)
            {
                if (counter == 0)
                {
                    textBox1.Text = string.Join(",", s);
                }
                else
                {
                    textBox1.Text = textBox1.Text + string.Join(",", s);
                }
                textBox1.AppendText(Environment.NewLine);
                counter++;
            }
        }


问:
Quick question about ports on a web address
I got a little confused about sockets.

In an address like:

https://localhost:5000/

...where I am running a web server during development, I know that the HTTPS translates to the local port 443, so the question is, what is the 5000 port number in that address?

答: HTTPS defaults to port 443, unless otherwise specified. In localhost:5000 you are explicitly specifying a port, so it's port 5000. Only https://localhost would be using port 443 implicitly.


问:
How to pass multiple array values of checkbox in PHP to another page?
I wanted to create a selection pages (by using checkboxes) where at the end it will show the result from the selection of all the checkboxes. There are about 5 different categories of checkboxes in my first page (only contains HTML) which is for emotions, time, movements, tools & personalization.

First page: index.php

```<code>    <div>
    <form action="process.php" method="post">
    <label>Select your emotions :</label>
    <input type="checkbox" name="emotions[]" value="Sadness"> Sadness
    <input type="checkbox" name="emotions[]" value="Anxiety"> Anxiety
    <input type="checkbox" name="emotions[]" value="Anger"> Anger
    <input type="checkbox" name="emotions[]" value="Disgust"> Disgust
    <input type="checkbox" name="emotions[]" value="Fear"> Fear
    <input type="checkbox" name="emotions[]" value="Surprised"> Surprised
    <br>
    <label>Select your time to commit :</label>
    <input type="checkbox" name="time[]" value="1"> Less than 1 minute
    <input type="checkbox" name="time[]" value="1-3"> 1-3 minutes
    <input type="checkbox" name="time[]" value="3-5"> 3-5 minutes
    <input type="checkbox" name="time[]" value="5-10"> 5-10 minutes
    <input type="checkbox" name="time[]" value="10-15"> 10-15 minutes
    <input type="checkbox" name="time[]" value="15-30"> 15-30 minutes
    <br>
    <label>Select how you want to move :</label>
    <input type="checkbox" name="movement[]" value="Lying Down"> Lying Down
    <input type="checkbox" name="movement[]" value="Sitting"> Sitting
    <input type="checkbox" name="movement[]" value="Standing"> Standing
    <input type="checkbox" name="movement[]" value="Stretching"> Stretching
    <input type="checkbox" name="movement[]" value="Walking"> Walking
    <input type="checkbox" name="movement[]" value="Work-out"> Work-out
    <br>
    <label>Tools around me :</label>
    <input type="checkbox" name="tools[]" value="Me"> Me
    <input type="checkbox" name="tools[]" value="Pen & Paper"> Pen & Paper
    <input type="checkbox" name="tools[]" value="Bottle"> Bottle
    <input type="checkbox" name="tools[]" value="Color Pencils"> Color Pencils
    <input type="checkbox" name="tools[]" value="Drinks"> Drinks
    <input type="checkbox" name="tools[]" value="Snacks"> Snacks
    <label>Personalization :</label>
    <input type="checkbox" name="personalization[]" value="Favorites"> Favorites
    <input type="checkbox" name="personalization[]" value="New"> New
    <input type="checkbox" name="personalization[]" value="Completed"> Completed
    <input type="checkbox" name="personalization[]" value="Islamic"> Islamic
</div>
<div>
    <button type="submit">Submit</button>
</div>
</code>```

2nd page: process.php

```<code><?php
$emotions = (isset($_POST['emotions'])) ? $_POST['emotions'] : array(); ?>
<p><strong>Emotions :</strong>
    <?php
    if (count($emotions) > 0) {
        foreach ($emotions as $emotions) {
            echo $emotions . ' ';
        }
    } else {
        echo "No emotions has been selected";
    }
    ?>
</p>

<?
$time = (isset($_POST['time'])) ? $_POST['time'] : array(); ?>
<p><strong>Time :</strong>
    <?php
    if (count($time) > 0) {
        foreach ($time as $time) {
            echo $time . ' ';
        }
    } else {
        echo "No time has been selected";
    }
    ?>
</p>
<?
$movement = (isset($_POST['movement'])) ? $_POST['movement'] : array(); ?>
<p><strong>Movement :</strong>
    <?php
    if (count($movement) > 0) {
        foreach ($movement as $movement) {
            echo $movement . ' ';
        }
    } else {
        echo "No movements has been selected";
    }
    ?>
</p>

<?
$tools = (isset($_POST['tools'])) ? $_POST['tools'] : array(); ?>
<p><strong>Tools :</strong>
    <?php
    if (count($tools) > 0) {
        foreach ($tools as $tools) {
            echo $tools . ' ';
        }
    } else {
        echo "No tools has been selected";
    }
    ?>
</p>

<?
$personalization = (isset($_POST['personalization'])) ? $_POST['personalization'] : array(); ?>
<p><strong>Personalization :</strong>
    <?php
    if (count($personalization) > 0) {
        foreach ($personalization as $personalization) {
            echo $personalization . ' ';
        }
    } else {
        echo "No personalization has been selected";
    }
    ?>
</p>
</code>```

答:
Review your foreach.
What you do is :

```<code>$array = [1, 2, 3];
foreach($array as $array){
  // $array is no more an array, but have the first value of the init array : 1
}
</code>```

it's like if you do : $array = $array[0]

you have to do something like :

```<code>$array = [1, 2, 3];
foreach($array as $ar){
  ...
  // code for $ar
  ...
}
</code>```

Body:
I wanted to create a selection pages (by using checkboxes) where at the end it will show the result from the selection of all the checkboxes. There are about 5 different categories of checkboxes in my first page (only contains HTML) which is for emotions, time, movements, tools & personalization.

First page: index.php

    <form action="process.php" method="post">
    Select your emotions :
    <input type="checkbox" name="emotions[]" value="Sadness"> Sadness
    <input type="checkbox" name="emotions[]" value="Anxiety"> Anxiety
    <input type="checkbox" name="emotions[]" value="Anger"> Anger
    <input type="checkbox" name="emotions[]" value="Disgust"> Disgust
    <input type="checkbox" name="emotions[]" value="Fear"> Fear
    <input type="checkbox" name="emotions[]" value="Surprised"> Surprised

    Select your time to commit :
    <input type="checkbox" name="time[]" value="1"> Less than 1 minute
    <input type="checkbox" name="time[]" value="1-3"> 1-3 minutes
    <input type="checkbox" name="time[]" value="3-5"> 3-5 minutes
    <input type="checkbox" name="time[]" value="5-10"> 5-10 minutes
    <input type="checkbox" name="time[]" value="10-15"> 10-15 minutes
    <input type="checkbox" name="time[]" value="15-30"> 15-30 minutes

    Select how you want to move :
    <input type="checkbox" name="movement[]" value="Lying Down"> Lying Down
    <input type="checkbox" name="movement[]" value="Sitting"> Sitting
    <input type="checkbox" name="movement[]" value="Standing"> Standing
    <input type="checkbox" name="movement[]" value="Stretching"> Stretching
    <input type="checkbox" name="movement[]" value="Walking"> Walking
    <input type="checkbox" name="movement[]" value="Work-out"> Work-out

    Tools around me :
    <input type="checkbox" name="tools[]" value="Me"> Me
    <input type="checkbox" name="tools[]" value="Pen & Paper"> Pen & Paper
    <input type="checkbox" name="tools[]" value="Bottle"> Bottle
    <input type="checkbox" name="tools[]" value="Color Pencils"> Color Pencils
    <input type="checkbox" name="tools[]" value="Drinks"> Drinks
    <input type="checkbox" name="tools[]" value="Snacks"> Snacks
    Personalization :
    <input type="checkbox" name="personalization[]" value="Favorites"> Favorites
    <input type="checkbox" name="personalization[]" value="New"> New
    <input type="checkbox" name="personalization[]" value="Completed"> Completed
    <input type="checkbox" name="personalization[]" value="Islamic"> Islamic

    <button type="submit">Submit</button>

2nd page: process.php

<?php
$emotions = (isset($_POST['emotions'])) ? $_POST['emotions'] : array(); ?>

Emotions :
    <?php
    if (count($emotions) > 0) {
        foreach ($emotions as $emotions) {
            echo $emotions . ' ';
        }
    } else {
        echo "No emotions has been selected";
    }
    ?>

<?
$time = (isset($_POST['time'])) ? $_POST['time'] : array(); ?>

Time :
    <?php
    if (count($time) > 0) {
        foreach ($time as $time) {
            echo $time . ' ';
        }
    } else {
        echo "No time has been selected";
    }
    ?>

<?
$movement = (isset($_POST['movement'])) ? $_POST['movement'] : array(); ?>

Movement :
    <?php
    if (count($movement) > 0) {
        foreach ($movement as $movement) {
            echo $movement . ' ';
        }
    } else {
        echo "No movements has been selected";
    }
    ?>

<?
$tools = (isset($_POST['tools'])) ? $_POST['tools'] : array(); ?>

Tools :
    <?php
    if (count($tools) > 0) {
        foreach ($tools as $tools) {
            echo $tools . ' ';
        }
    } else {
        echo "No tools has been selected";
    }
    ?>

<?
$personalization = (isset($_POST['personalization'])) ? $_POST['personalization'] : array(); ?>

Personalization :
    <?php
    if (count($personalization) > 0) {
        foreach ($personalization as $personalization) {
            echo $personalization . ' ';
        }
    } else {
        echo "No personalization has been selected";
    }
    ?>

Body:
Review your foreach.
What you do is :

$array = [1, 2, 3];
foreach($array as $array){
  // $array is no more an array, but have the first value of the init array : 1
}

it's like if you do : $array = $array[0]

you have to do something like :

$array = [1, 2, 3];
foreach($array as $ar){
  ...
  // code for $ar
  ...
}


问:
How to change state without re-rendering in react native
I am making an app which is calling an API repeatedly and changing state, and I have another function which is listening to an event and update some state but I want to update it without re-rendering because it causes some unwanted behaviour to chain of repeatedly API calling,

Any help will be appreciated.

答: The problem solved by removing the function call depend on state.</p>


问:
Sorting by relevance of the search phrase by the value in the field in Solr
Version of Solr core 8.10.1
I have a schema with fields: name, price.
For example, in Solr is docs exist records:
[
{
"name":"Кабель питания сист.блок-монитор Gembird 4.5-5.0м, черный, с зазем., пакет [PC-189-15]",
"price_currency":2.09
},
{
"name":"Монитор 15' LG 1510 TFT",
"price_currency":0.0
}
]

I need to sort the result by relevance field (asc) and price (desc). How to correctly compose an expression in the sort field?
In case when I write: sort=price desc, in result the first record is higher than the second, and I need the opposite.
My incorrect query example:
http://localhost/solr/#/catalog/query?q=%D0%BC%D0%BE%D0%BD%D0%B8%D1%82%D0%BE%D1%80%0A15&q.op=AND&indent=true&sort=price%20asc&df=text&rows=100

答:
What you need is something like this: score asc, price desc in the sort field.
Here is the documentation: https://solr.apache.org/guide/8_10/common-query-parameters.html#sort-parameter
This is the relevant info from the documentation (an example)

"inStock desc, price asc

Sorts by the contents of the inStock field in descending order, then when multiple documents have the same value for the inStock field, those results are sorted in ascending order by the contents of the price field."


问:
Run manage.py from AWS EB Linux instance
How to run manage.py from AWS EB (Elastic Beanstalk) Linux instance?

If I run it from '/opt/python/current/app', it shows the below exception.

```<code>Traceback (most recent call last):
  File "./manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
</code>```

I think it's related with virtualenv. Any hints?

答:
As of February 2022 the solution is as follows:

```<code>$ eb ssh
$ sudo su -
$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs)
$ source /var/app/venv/*/bin/activate
$ python3 /var/app/current/manage.py <command name>
</code>```

$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs) is needed to import your environment variables if you have a database connection (most likely you will)

Body:
How to run manage.py from AWS EB (Elastic Beanstalk) Linux instance?

If I run it from '/opt/python/current/app', it shows the below exception.

Traceback (most recent call last):
  File "./manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named django.core.management

I think it's related with virtualenv. Any hints?

Body:
As of February 2022 the solution is as follows:

$ eb ssh
$ sudo su -
$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs)
$ source /var/app/venv/*/bin/activate
$ python3 /var/app/current/manage.py <command name>

$ export $(cat /opt/elasticbeanstalk/deployment/env | xargs) is needed to import your environment variables if you have a database connection (most likely you will)


问:
How to pass list to method and insert element?
I am beginner learning Java and trying to create a method for list to add elements in the list and return the list. But getting this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

language cannot be resolved at karl_language.language(karl_language.java:14) at karl_language.main(karl_language.java:33)

```<code>public class karl_language {

    public boolean isEmpty(List<String> language) {
        if(language.isEmpty())
            return true;
        return false;
    }

    public List<String> language(String languages){
        language.add(languages);

    }

    public static void main(String[] args) {
        karl_language lan = new karl_language();
        List<String> language = new ArrayList<String>();
        Scanner input1 = new Scanner(System.in);
        System.out.println("Enter the number of languages : ");
        int n = input1.nextInt();
        System.out.println("Enter the language : ");
        for(int i=0;i<n;i++){
            language.add(input1.next());
        }
        System.out.println(language);
        System.out.println("Is List Empty? : "+lan.isEmpty(language));
        System.out.println("Enter the number of languages need to be added :");
        int n1 = input1.nextInt();
        for(int i =0 ; i<n1 ;i++) {
            lan.language(input1.next());
        }

    }
}
</code>```

答:
Got the answer..Previously i didnt define the method properly [ addlanguage ].Thanks for your help!!</p>
```<code>public class karl_language {

    public boolean isEmpty(List<String> language) {
        if(language.isEmpty())
            return true;
        return false;
    }

    public void addlanguage(String languages,List<String> language){
        language.add(languages);

    }

    public static void main(String[] args) {
        karl_language lan = new karl_language();
        List<String> language = new ArrayList<String>();
        Scanner input1 = new Scanner(System.in);
        System.out.println("Enter the number of languages : ");
        int n = input1.nextInt();
        System.out.println("Enter the language : ");
        for(int i=0;i<n;i++){
            language.add(input1.next());
        }
        System.out.println(language);
        System.out.println("Is List Empty? : "+lan.isEmpty(language));
        System.out.println("Enter the number of languages need to be added :");
        int n1 = input1.nextInt();
        for(int i =0 ; i<n1 ;i++) {
            lan.addlanguage(input1.next(),language);
        }
        System.out.println(language);
        input1.close();
    }
}
</code>```

Body:
I am beginner learning Java and trying to create a method for list to add elements in the list and return the list. But getting this error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:

language cannot be resolved at karl_language.language(karl_language.java:14) at karl_language.main(karl_language.java:33)

public class karl_language {

    public boolean isEmpty(List<String> language) {
        if(language.isEmpty())
            return true;
        return false;
    }

    public List<String> language(String languages){
        language.add(languages);

    }

    public static void main(String[] args) {
        karl_language lan = new karl_language();
        List<String> language = new ArrayList<String>();
        Scanner input1 = new Scanner(System.in);
        System.out.println("Enter the number of languages : ");
        int n = input1.nextInt();
        System.out.println("Enter the language : ");
        for(int i=0;i<n;i++){
            language.add(input1.next());
        }
        System.out.println(language);
        System.out.println("Is List Empty? : "+lan.isEmpty(language));
        System.out.println("Enter the number of languages need to be added :");
        int n1 = input1.nextInt();
        for(int i =0 ; i<n1 ;i++) {
            lan.language(input1.next());
        }

    }
}

Body:
Got the answer..Previously i didnt define the method properly [ addlanguage ].Thanks for your help!!

public class karl_language {

    public boolean isEmpty(List<String> language) {
        if(language.isEmpty())
            return true;
        return false;
    }

    public void addlanguage(String languages,List<String> language){
        language.add(languages);

    }

    public static void main(String[] args) {
        karl_language lan = new karl_language();
        List<String> language = new ArrayList<String>();
        Scanner input1 = new Scanner(System.in);
        System.out.println("Enter the number of languages : ");
        int n = input1.nextInt();
        System.out.println("Enter the language : ");
        for(int i=0;i<n;i++){
            language.add(input1.next());
        }
        System.out.println(language);
        System.out.println("Is List Empty? : "+lan.isEmpty(language));
        System.out.println("Enter the number of languages need to be added :");
        int n1 = input1.nextInt();
        for(int i =0 ; i<n1 ;i++) {
            lan.addlanguage(input1.next(),language);
        }
        System.out.println(language);
        input1.close();
    }
}


问:
Can't access Microsoft To Do list using the MS Graph API
I try to make programm in python to add appointments to Microsoft To Do
I'm using the Microsoft Graph API with following code:

```<code>import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]

cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)

if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')

</code>```

This is the error I get:

```<code>{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}
</code>```

I tried to google the error but I didn't found any solution that worked for me.

答:
could you please check your token expiry time (exp), might be it got expired. Go to  jwt.ms to check token details, find the attached image to see where to find token time.

If the token got expired ,please the docs get new token.

Body:
I try to make programm in python to add appointments to Microsoft To Do
I'm using the Microsoft Graph API with following code:

import requests
import msal
import atexit
import os.path

TENANT_ID = 'X
CLIENT_ID = 'Y'

AUTHORITY = 'https://login.microsoftonline.com/' + TENANT_ID
ENDPOINT = 'https://graph.microsoft.com/v1.0'

SCOPES = [
    'Files.ReadWrite.All',
    'Sites.ReadWrite.All',
    'User.Read',
    'User.ReadBasic.All',
    'Tasks.ReadWrite'
]

cache = msal.SerializableTokenCache()

if os.path.exists('token_cache.bin'):
    cache.deserialize(open('token_cache.bin', 'r').read())

atexit.register(lambda: open('token_cache.bin', 'w').write(cache.serialize()) if cache.has_state_changed else None)

app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY, token_cache=cache)

accounts = app.get_accounts()
result = None
if len(accounts) > 0:
    result = app.acquire_token_silent(SCOPES, account=accounts[0])

if result is None:
    flow = app.initiate_device_flow(scopes=SCOPES)
    if 'user_code' not in flow:
        raise Exception('Failed to create device flow')

    print(flow['message'])

    result = app.acquire_token_by_device_flow(flow)

if 'access_token' in result:
    print(result['access_token'])
    result = requests.get(f'https://graph.microsoft.com/v1.0/me/todo/lists', headers={'Authorization': 'Bearer ' + result['access_token']})
    print(result.json())

else:
    raise Exception('no access token in result')

This is the error I get:

{'error': {'code': 'UnknownError', 'message': 'The service is unavailable.', 'innerError': {'date': '2022-01-25T18:52:03', 'request-id': 'X', 'client-request-id': 'X'}}}

I tried to google the error but I didn't found any solution that worked for me.


问:
looping through variable from rest api and ading it to a v-list
I am having some difficulties with the vue.js. The main problem is that I am getting this error :

```<code>Property or method `response` is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for `class-based` components, by initializing the property.
</code>```

My main idea is to loop through the response (which is just an array) and add it to my v-list to have it in shape of something like this :

Instead of having create, read etc. to have my elements of array, and I am wondering how to even start with this problem.

like this is the part with my list in vue.js, I know that I think I need to use v-for method but I cant even start it without solving the error.

```<code>            <v-list-group>
              <v-list-item @click="getHosts()">
              {{response}}
              </v-list-item>
              <v-list-item-group>
              </v-list-item-group>
            </v-list-group>
          </v-list>
</code>```

and this is the function that gets the array.

```<code>getHosts(){
      axios.get('http://127.0.0.1:8000/something')
      .then((response)=>{
      console.log(response.data)
      return response
      })
    }
</code>```

I've added this function in export default in section methods, I've read about other sections and thought maybe beforeMount but I still got an error.

Thanks for any clues/help/solutions!

答:
Instead of returning the response directly. You can bind the response in the data property.

Working Demo (For demo purpose I am using v-for instead of v-list) :

var vm = new Vue({
  el: '#vue-instance',
  data() {
    return {
      hostList: []
    }
  },
  methods: {
    getHosts() {
        axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
        this.hostList = response.data;
        }).catch((error) => {
        console.warn('API error');
      });
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="vue-instance">
  <button v-on:click="getHosts">Get Hosts!</button>
  <ul>
    <li v-for="host in hostList">
      {{ host.name }}
    </li>
  </ul>
</div></code>```

Body:
I am having some difficulties with the vue.js. The main problem is that I am getting this error :

Property or method `response` is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for `class-based` components, by initializing the property.

My main idea is to loop through the response (which is just an array) and add it to my v-list to have it in shape of something like this :

Instead of having create, read etc. to have my elements of array, and I am wondering how to even start with this problem.

like this is the part with my list in vue.js, I know that I think I need to use v-for method but I cant even start it without solving the error.

            <v-list-group>
              <v-list-item @click="getHosts()">
              {{response}}
              </v-list-item>
              <v-list-item-group>
              </v-list-item-group>
            </v-list-group>
          </v-list>

and this is the function that gets the array.

getHosts(){
      axios.get('http://127.0.0.1:8000/something')
      .then((response)=>{
      console.log(response.data)
      return response
      })
    }

I've added this function in export default in section methods, I've read about other sections and thought maybe beforeMount but I still got an error.

Thanks for any clues/help/solutions!

Body:
Instead of returning the response directly. You can bind the response in the data property.

Working Demo (For demo purpose I am using v-for instead of v-list) :

var vm = new Vue({
  el: '#vue-instance',
  data() {
    return {
      hostList: []
    }
  },
  methods: {
    getHosts() {
        axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
        this.hostList = response.data;
        }).catch((error) => {
        console.warn('API error');
      });
    }
  }
});

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<div id="vue-instance">
  <button v-on:click="getHosts">Get Hosts!</button>
  <ul>
    <li v-for="host in hostList">
      {{ host.name }}
    </li>
  </ul>
</div>