问:
python multi-threading lock is not working as expected when doing number change
I am learning python3 multi-threading now and trying to test the following code. what the code does is to use multiple thread to modify a global number balance  (initial value = 0) in a function named test_change by first adding and then substracting a same number, and using a thread lock to ensure the balance variable will be changed by one thread at a time. And I am looping it for 100000 or more times to check weather the expected value 0 is displayed, however, quite disappointedly, 0 is not always the answer i can get. Here is the code below. And the editor I am using is Vscode.

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    # print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, target_fun, fun_args, loop=False):
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.threadLock = threading.Lock()

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            # with self.threadLock:  # balance [15]
                # for i in range(1000000):
                    # self.target_fun(self.fun_args)
            for i in range(100000):
                self.threadLock.acquire()
                self.target_fun(self.fun_args)
                self.threadLock.release()

nums = [5, 12]
thread_list = []
for i in range(2):  # create 2 thread object
    t = MyThread(target_fun=test_change, fun_args=nums[i], loop=True)
    thread_list.append(t)

for i in range(len(thread_list)):  # start thread object
    thread_list[i].start()

for i in range(len(thread_list)):  # stop main thread till subthread finishes
    thread_list[i].join()

print("balance [{}]".format(balance))  # expected to be 0 always
print("subthread finishes")

```

<p>and here is part of the execution result that displayed, you can see the last output.</p>

```(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2863 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2870 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3383 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3389 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3394 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3401 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3406 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3414 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [12]  --> this is the result should never happened when using a lock.
subthread finishes

```

I have tried two python grammar for enable a lock which are with self.threadLock: (see the commented out part inside the class run function) and self.threadLock.acquire(), self.threadLock.release(), is there anyone can help to explain this oddity.

答: Each thread you create is given its own instance of a Lock(), and they have nothing to do with each other. To provide mutual exclusion, both threads have to use the same Lock object. For example, create a single instance of a Lock at module level, and pass it to the thread's constructor.

Body:
I am learning python3 multi-threading now and trying to test the following code. what the code does is to use multiple thread to modify a global number balance  (initial value = 0) in a function named test_change by first adding and then substracting a same number, and using a thread lock to ensure the balance variable will be changed by one thread at a time. And I am looping it for 100000 or more times to check weather the expected value 0 is displayed, however, quite disappointedly, 0 is not always the answer i can get. Here is the code below. And the editor I am using is Vscode.

balance = 0
def test_change(n):
    global balance
    balance += n
    balance -= n
    # print("in {}, balance is {}".format(threading.current_thread().name, balance))

class MyThread(threading.Thread):
    """ self-defined threading class """
    def __init__(self, target_fun, fun_args, loop=False):
        threading.Thread.__init__(self)
        self.target_fun = target_fun
        self.fun_args = fun_args
        self.loop = loop
        self.threadLock = threading.Lock()

    def run(self):  # overwrite parent run function
        if not self.loop:
            self.target_fun(*self.fun_args)
        elif self.loop:
            # with self.threadLock:  # balance [15]
                # for i in range(1000000):
                    # self.target_fun(self.fun_args)
            for i in range(100000):
                self.threadLock.acquire()
                self.target_fun(self.fun_args)
                self.threadLock.release()

nums = [5, 12]
thread_list = []
for i in range(2):  # create 2 thread object
    t = MyThread(target_fun=test_change, fun_args=nums[i], loop=True)
    thread_list.append(t)

for i in range(len(thread_list)):  # start thread object
    thread_list[i].start()

for i in range(len(thread_list)):  # stop main thread till subthread finishes
    thread_list[i].join()

print("balance [{}]".format(balance))  # expected to be 0 always
print("subthread finishes")

and here is part of the execution result that displayed, you can see the last output.

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 &ython.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugface_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2863 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 2870 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3383 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3389 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3394 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3401 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3406 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [0]
subthread finishes

(face36) D:\P_project_SRS\face_cumstom_dual_cam_0506> cd d:\P_project_SRS\face_cumstom_dual_cam_0506 && cmd /C "C:\LeeSRSPrgoramFile\A_anaconda\envs\face36\python.exe c:\Users\lijin\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher 3414 -- d:\P_project_SRS\face_cumstom_dual_cam_0506\threading_producer_consumer.py "
balance [12]  --> this is the result should never happened when using a lock.
subthread finishes

I have tried two python grammar for enable a lock which are with self.threadLock: (see the commented out part inside the class run function) and self.threadLock.acquire(), self.threadLock.release(), is there anyone can help to explain this oddity.


来源: stackexchange

问:
how to insert javascript variable into json object
here is the function

```<code>function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { _id:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');
</code>```

Result :

```<code>[
_id:{temp:'20C',
     battery:'60%'
    }
]
</code>```

Expected Result:

```<code>[
Thermometer1:{temp:'20C',
     battery:'60%'
    }
]
</code>```

ignore the text below :v

it looks like your post is mostly code; please add more detail,

i don't know what to write so here is a guitar tab

0 - 3 - 5

0 - 3 - 6 - 5

0 - 3 - 5 - 3 - 0

答:
You can use object[attribute] syntax to refer to a property of an object.

// Example:

let attr = 'candy';
let obj = {};

obj['attr'] = 'cone';
console.log(obj);     // { attr: 'cane' }

obj[attr] = 'cane';
console.log(obj);     // { attr: 'cone', candy: 'cane' }
```

<pre class="lang-js prettyprint-override"><code>// Your Solution:

function createData(_id) {
  var _temp = "20C";
  var _battery = "60%";
  var _data = {};

  _data[_id] = {
    temp: _temp,
    battery: _battery,
  };

  console.log(_data);
}

createData("Thermometer1"); // { Thermometer1: { temp: '20C', battery: '60%' } }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
here is the function

function createData(_id){
var _temp = '20C';
var _battery = '60%';
var _data = { _id:{temp:_temp,battery:_battery} };
console.log(_data);
}
createData('Thermometer1');

Result :

[
_id:{temp:'20C',
     battery:'60%'
    }
]

Expected Result:

[
Thermometer1:{temp:'20C',
     battery:'60%'
    }
]

ignore the text below :v

it looks like your post is mostly code; please add more detail,

i don't know what to write so here is a guitar tab

0 - 3 - 5

0 - 3 - 6 - 5

0 - 3 - 5 - 3 - 0

Body:
You can use object[attribute] syntax to refer to a property of an object.

// Example:

let attr = 'candy';
let obj = {};

obj['attr'] = 'cone';
console.log(obj);     // { attr: 'cane' }

obj[attr] = 'cane';
console.log(obj);     // { attr: 'cone', candy: 'cane' }

// Your Solution:

function createData(_id) {
  var _temp = "20C";
  var _battery = "60%";
  var _data = {};

  _data[_id] = {
    temp: _temp,
    battery: _battery,
  };

  console.log(_data);
}

createData("Thermometer1"); // { Thermometer1: { temp: '20C', battery: '60%' } }


问:
onKeyDown get value from e.target.value?
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

```<code>const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />
    </div>   ); };
</code>```

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

答:
onKeyDown, onKeyUp, and onKeyPress contain the old value of the target element.
 onInput event gets the new value of the target element.

check the below link I add some console log. which help you to understand which event contains the value
https://codesandbox.io/s/ecstatic-framework-c4hkw?file=/src/App.js

Body:
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (

      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />

   ); };

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js


问:
MsBuild StartsWith not Evaluating In Condition?
In trying to get some code coverage tools set up and working on a new Xamarin.Forms project via VisualStudio on Mac, I am trying to use netfx.props as suggested in mac/linux `dotnet build` The reference assemblies for framework ".NETFramework.." were not found.  (I would comment there directly for this question, but alas, I don't have enough reputation points.)

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (c) Microsoft Corporation.  All Rights Reserved.  See License.txt in the project root for license information. -->
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <!-- When compiling .NET SDK 2.0 projects targeting .NET 4.x on Mono using 'dotnet build' you -->
    <!-- have to teach MSBuild where the Mono copy of the reference asssemblies is -->
    <TargetIsMono Condition="($(TargetFramework.StartsWith('net4')) OR $(TargetFrameworkVersion.StartsWith('v4.'))) AND '$(OS)' == 'Unix'">true</TargetIsMono>

    <!-- Look in the standard install locations -->
    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/Library/Frameworks/Mono.framework/Versions/Current/lib/mono')">/Library/Frameworks/Mono.framework/Versions/Current/lib/mono</BaseFrameworkPathOverrideForMono>
    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/usr/lib/mono')">/usr/lib/mono</BaseFrameworkPathOverrideForMono>
    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/usr/local/lib/mono')">/usr/local/lib/mono</BaseFrameworkPathOverrideForMono>

    <!-- If we found Mono reference assemblies, then use them -->
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net45' OR '$(TargetFrameworkVersion)' == 'v4.5')">$(BaseFrameworkPathOverrideForMono)/4.5-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net451' OR '$(TargetFrameworkVersion)' == 'v4.5.1')">$(BaseFrameworkPathOverrideForMono)/4.5.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net452' OR '$(TargetFrameworkVersion)' == 'v4.5.2')">$(BaseFrameworkPathOverrideForMono)/4.5.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net46' OR '$(TargetFrameworkVersion)' == 'v4.6')">$(BaseFrameworkPathOverrideForMono)/4.6-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net461' OR '$(TargetFrameworkVersion)' == 'v4.6.1')">$(BaseFrameworkPathOverrideForMono)/4.6.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net462' OR '$(TargetFrameworkVersion)' == 'v4.6.2')">$(BaseFrameworkPathOverrideForMono)/4.6.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net47' OR '$(TargetFrameworkVersion)' == 'v4.7')">$(BaseFrameworkPathOverrideForMono)/4.7-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net471' OR '$(TargetFrameworkVersion)' == 'v4.7.1')">$(BaseFrameworkPathOverrideForMono)/4.7.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net472' OR '$(TargetFrameworkVersion)' == 'v4.7.2')">$(BaseFrameworkPathOverrideForMono)/4.7.2-api</FrameworkPathOverride>
    <EnableFrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != ''">true</EnableFrameworkPathOverride>

    <!-- Add the Facades directory.  Not sure how else to do this. Necessary at least for .NET 4.5 -->
    <AssemblySearchPaths Condition="'$(BaseFrameworkPathOverrideForMono)' != ''">$(FrameworkPathOverride)/Facades;$(AssemblySearchPaths)</AssemblySearchPaths>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'== 'net472' OR '$(TargetFrameworkVersion)' == 'v4.7.2'">
    <Reference Include="netstandard" />
  </ItemGroup>
</Project>
</code>```

The file is imported via the .csproj fine, but it still wasn't working, so I printed some debug messaging using:

```<code>    <Target Name="test">
        <Message Importance="High" Text="TargetFramework value is '$(TargetFramework)', starts with net4 is '$(TargetFramework.StartsWith('net4'))'" />
        <Message Importance="High" Text="TargetFrameworkVersion value is '$(TargetFrameworkVersion)', starts with v4 is '$(TargetFrameworkVersion.StartsWith('v4'))'" />
        <Message Importance="High" Text="OS value is '$(OS)'" />
        <Message Importance="High" Text="TargetIsMono value is '$(TargetIsMono)'" />
        <Message Importance="High" Text="BaseFrameworkPathOverrideForMono value is '$(BaseFrameworkPathOverrideForMono)'" />
        <Message Importance="High" Text="FrameworkPathOverride value is '$(FrameworkPathOverride)'" />
        <Message Importance="High" Text="EnableFrameworkPathOverride value is '$(EnableFrameworkPathOverride)'" />
    </Target>
</code>```

and saw that:

```<code>  TargetFramework value is '', starts with net4 is 'False'
  TargetFrameworkVersion value is 'v4.7', starts with v4 is 'True'
  OS value is 'Unix'
  TargetIsMono value is ''
  BaseFrameworkPathOverrideForMono value is ''
  FrameworkPathOverride value is '/Library/Frameworks/Mono.framework/Versions/6.6.0/lib/mono/4.7-api'
  EnableFrameworkPathOverride value is ''
</code>```

TargetIsMono remains empty even though it should have been set to 'true' because of the TargetFrameworkVersion.StartsWith and OS.  After playing around with the TargetIsMono Condition, the issue seems to be that even though the StartsWiths have correct boolean values according to the print messages, they are not actually evaluating properly in the Condition.

I.e.,

```<code>    <TargetIsMono Condition="$(TargetFrameworkVersion.StartsWith('v4.'))>true</TargetIsMono>
</code>```

does not set TargetIsMono to 'true' even though it should.

Does anyone have any ideas?  I am new to MsBuild, Xamarin.Forms, and VisualStudio.  Any help would be appreciated!

答: I switched target framework version to 4.8 then back to 4.7, and this resolved itself.  ¯\_(ツ)_/¯</p>

Body:
In trying to get some code coverage tools set up and working on a new Xamarin.Forms project via VisualStudio on Mac, I am trying to use netfx.props as suggested in mac/linux `dotnet build` The reference assemblies for framework ".NETFramework.." were not found.  (I would comment there directly for this question, but alas, I don't have enough reputation points.)

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

<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>

    <TargetIsMono Condition="($(TargetFramework.StartsWith('net4')) OR $(TargetFrameworkVersion.StartsWith('v4.'))) AND '$(OS)' == 'Unix'">true</TargetIsMono>

    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/Library/Frameworks/Mono.framework/Versions/Current/lib/mono')">/Library/Frameworks/Mono.framework/Versions/Current/lib/mono</BaseFrameworkPathOverrideForMono>
    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/usr/lib/mono')">/usr/lib/mono</BaseFrameworkPathOverrideForMono>
    <BaseFrameworkPathOverrideForMono Condition="'$(BaseFrameworkPathOverrideForMono)' == '' AND '$(TargetIsMono)' == 'true' AND EXISTS('/usr/local/lib/mono')">/usr/local/lib/mono</BaseFrameworkPathOverrideForMono>

    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net45' OR '$(TargetFrameworkVersion)' == 'v4.5')">$(BaseFrameworkPathOverrideForMono)/4.5-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net451' OR '$(TargetFrameworkVersion)' == 'v4.5.1')">$(BaseFrameworkPathOverrideForMono)/4.5.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net452' OR '$(TargetFrameworkVersion)' == 'v4.5.2')">$(BaseFrameworkPathOverrideForMono)/4.5.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net46' OR '$(TargetFrameworkVersion)' == 'v4.6')">$(BaseFrameworkPathOverrideForMono)/4.6-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net461' OR '$(TargetFrameworkVersion)' == 'v4.6.1')">$(BaseFrameworkPathOverrideForMono)/4.6.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net462' OR '$(TargetFrameworkVersion)' == 'v4.6.2')">$(BaseFrameworkPathOverrideForMono)/4.6.2-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net47' OR '$(TargetFrameworkVersion)' == 'v4.7')">$(BaseFrameworkPathOverrideForMono)/4.7-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net471' OR '$(TargetFrameworkVersion)' == 'v4.7.1')">$(BaseFrameworkPathOverrideForMono)/4.7.1-api</FrameworkPathOverride>
    <FrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != '' AND ('$(TargetFramework)' == 'net472' OR '$(TargetFrameworkVersion)' == 'v4.7.2')">$(BaseFrameworkPathOverrideForMono)/4.7.2-api</FrameworkPathOverride>
    <EnableFrameworkPathOverride Condition="'$(BaseFrameworkPathOverrideForMono)' != ''">true</EnableFrameworkPathOverride>

    <AssemblySearchPaths Condition="'$(BaseFrameworkPathOverrideForMono)' != ''">$(FrameworkPathOverride)/Facades;$(AssemblySearchPaths)</AssemblySearchPaths>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'== 'net472' OR '$(TargetFrameworkVersion)' == 'v4.7.2'">
    <Reference Include="netstandard" />
  </ItemGroup>
</Project>

The file is imported via the .csproj fine, but it still wasn't working, so I printed some debug messaging using:

    <Target Name="test">
        <Message Importance="High" Text="TargetFramework value is '$(TargetFramework)', starts with net4 is '$(TargetFramework.StartsWith('net4'))'" />
        <Message Importance="High" Text="TargetFrameworkVersion value is '$(TargetFrameworkVersion)', starts with v4 is '$(TargetFrameworkVersion.StartsWith('v4'))'" />
        <Message Importance="High" Text="OS value is '$(OS)'" />
        <Message Importance="High" Text="TargetIsMono value is '$(TargetIsMono)'" />
        <Message Importance="High" Text="BaseFrameworkPathOverrideForMono value is '$(BaseFrameworkPathOverrideForMono)'" />
        <Message Importance="High" Text="FrameworkPathOverride value is '$(FrameworkPathOverride)'" />
        <Message Importance="High" Text="EnableFrameworkPathOverride value is '$(EnableFrameworkPathOverride)'" />
    </Target>

and saw that:

  TargetFramework value is '', starts with net4 is 'False'
  TargetFrameworkVersion value is 'v4.7', starts with v4 is 'True'
  OS value is 'Unix'
  TargetIsMono value is ''
  BaseFrameworkPathOverrideForMono value is ''
  FrameworkPathOverride value is '/Library/Frameworks/Mono.framework/Versions/6.6.0/lib/mono/4.7-api'
  EnableFrameworkPathOverride value is ''

TargetIsMono remains empty even though it should have been set to 'true' because of the TargetFrameworkVersion.StartsWith and OS.  After playing around with the TargetIsMono Condition, the issue seems to be that even though the StartsWiths have correct boolean values according to the print messages, they are not actually evaluating properly in the Condition.

I.e.,

    <TargetIsMono Condition="$(TargetFrameworkVersion.StartsWith('v4.'))>true</TargetIsMono>

does not set TargetIsMono to 'true' even though it should.

Does anyone have any ideas?  I am new to MsBuild, Xamarin.Forms, and VisualStudio.  Any help would be appreciated!


问:
Converting text file in key value format to a JSON object
I have a .env file with this content:

```<code>APP_ENV=local
APP_DEBUG=true
APP_URL=http://example.com.br
</code>```

And I need to transform in something like this:

```<code>"environment": [
    {
        "name": "APP_ENV",
        "value": "local"
    },
    {
        "name": "APP_DEBUG",
        "value": "true"
    },
    {
        "name": "APP_URL",
        "value": "http://example.com.br"
    }
]
</code>```

I try to transform the file into a bash array, then convert to json with jq, but without success.
Can anybody give a tip?

答:
adapted from Convert text file with key=value pair to specific json format in jq</p>

```<code>jq -sR '{"Environment": [ split("\n")[:-1][] | rtrimstr("\\r") | split("=") | {name:.[0],value:.[1]}]}' env
</code>```

Body:
I have a .env file with this content:

APP_ENV=local
APP_DEBUG=true
APP_URL=http://example.com.br

And I need to transform in something like this:

"environment": [
    {
        "name": "APP_ENV",
        "value": "local"
    },
    {
        "name": "APP_DEBUG",
        "value": "true"
    },
    {
        "name": "APP_URL",
        "value": "http://example.com.br"
    }
]

I try to transform the file into a bash array, then convert to json with jq, but without success.
Can anybody give a tip?

Body:
adapted from Convert text file with key=value pair to specific json format in jq

jq -sR '{"Environment": [ split("\n")[:-1][] | rtrimstr("\\r") | split("=") | {name:.[0],value:.[1]}]}' env


问:
unknown error: call function result missing 'value' for Selenium Send Keys even after chromedriver upgrade
I am getting the below error while sending keys.

Result Message:

```<code>System.InvalidOperationException : unknown error: call function result missing 'value'
  (Session info: chrome=65.0.3325.146)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)
</code>```

I have updated the chrome driver to 2.36 but still my code search for 2.33?

Any idea ?

答:
```<code>Use xpaths instead of class names to locate elements
</code>```

After updating chrome and its drivers it didn't helped me at all!!
I don't know how much it makes sense but it worked for me when i replaced class name with xpath. This is the xpath , i used to automate sending whatsapp message using python.

```<code>driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div')
</code>```

previously i Was Using

```<code>driver.find_element_by_class_name('Some class Name Here')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting the below error while sending keys.

Result Message:

System.InvalidOperationException : unknown error: call function result missing 'value'
  (Session info: chrome=65.0.3325.146)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64)

I have updated the chrome driver to 2.36 but still my code search for 2.33?

Any idea ?

Body:
Use xpaths instead of class names to locate elements

After updating chrome and its drivers it didn't helped me at all!!
I don't know how much it makes sense but it worked for me when i replaced class name with xpath. This is the xpath , i used to automate sending whatsapp message using python.

driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div')

previously i Was Using

driver.find_element_by_class_name('Some class Name Here')


问:
How do you present a sequence of UIAlertControllers?
I have an app that can download many publications from a server at once. For each publication that already exists in the app, I want to prompt the user if he wants to overwrite the existing version.

Is there any clean way to present UIAlertControllers so that when the user has answered one, the app presents the next one?

答:
I had the same problem in my app and tried several solutions, but all of them were messy.  Then I thought of a very simple and effective way: use a delay to retry presentation until it can be shown.  This approach is much cleaner in that you don't need coordinated code in multiple places and you don't have to hack your action handlers.

Depending on your use case, you might care that this approach doesn't necassarily preserve the order of the alerts, in which case you can easily adapt it to store the alerts in an array to preserve order, showing and removing only the first on in the array each time.

This code overrides the standard presentation method in UIViewController, use it in your subclass which is presenting the alerts. This could also be adapted to an app level method if needed that descends from the rootViewController to find the top most presented VC and shows from there, etc.

```<code>- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
  // cannot present if already presenting.
  if (self.presentedViewController) {
    // cannot present now, try again in 100ms.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      // make sure we ourselve are still presented and able to present.
      if (self.presentingViewController && !self.isBeingDismissed) {
        // retry on self
        [self presentViewController:viewControllerToPresent animated:flag completion:completion];
      }
    });
  } else {
    // call super to really do it
    [super presentViewController:viewControllerToPresent animated:flag completion:completion];
  }
}
</code>```

Body:
I had the same problem in my app and tried several solutions, but all of them were messy.  Then I thought of a very simple and effective way: use a delay to retry presentation until it can be shown.  This approach is much cleaner in that you don't need coordinated code in multiple places and you don't have to hack your action handlers.

Depending on your use case, you might care that this approach doesn't necassarily preserve the order of the alerts, in which case you can easily adapt it to store the alerts in an array to preserve order, showing and removing only the first on in the array each time.

This code overrides the standard presentation method in UIViewController, use it in your subclass which is presenting the alerts. This could also be adapted to an app level method if needed that descends from the rootViewController to find the top most presented VC and shows from there, etc.

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion {
  // cannot present if already presenting.
  if (self.presentedViewController) {
    // cannot present now, try again in 100ms.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      // make sure we ourselve are still presented and able to present.
      if (self.presentingViewController && !self.isBeingDismissed) {
        // retry on self
        [self presentViewController:viewControllerToPresent animated:flag completion:completion];
      }
    });
  } else {
    // call super to really do it
    [super presentViewController:viewControllerToPresent animated:flag completion:completion];
  }
}


问:
Is there any way to get firebase Auth UID without login?
What i want to know is without login get Auth User UID from firebase
that already registered user

I already read firebase document but all the explain focus on when user logged only at that time  can get UID...

but i just want to get UID and user email address without login situation
Is there any way?

答:
You can apply a trick to do this. Though this is not an optimal solution.

One thing you have to remember that, "There is no way to get a UID without login".

Create a dummy user from your backend with a dummy email and password.

Send the email and password from the backend to your client-side app. You can always hash the password if you want to give an extra security layer.

Now call signInWithEmailAndPassword function from firebase SDK and provide email and password which came from the backend.

The user is already registered in the backend, so now you can get the UID from your client app.


问:
how can i use from methods in other pages?
HI,
i have 2 php pages.first page has some functions like Connect(),... .i want to use from Connect() function in second page but when use from Connect() can not recognize it.i use from header("first.php") but have same error.
how can i solve that problem?</p>

答: Create a class contains that method and include in the page where u want</p>


问:
wrong encoding when using child_process spawn or exec under Windows
Using the dir command in Windows CMD will result in the following output:

```<code>Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 testöäüÄÖÜ.txt
22.12.2013  17:27    <DIR>          testÖÄÜöüäß
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei
</code>```

Using exec or spawn will result in this:

```<code>Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 test������.txt
22.12.2013  17:27    <DIR>          test�������
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei
</code>```

Here is my Node Code:

```<code>var exec = require('child_process').exec,
    child;

child = exec('dir',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});
</code>```

答:
I solved it (Simplified Chinese) by below code, don't know the coding page for other languages, maybe you can find it from Microsoft website:</p>

```<code>  const encoding          = 'cp936';
  const binaryEncoding    = 'binary';

  function iconvDecode(str = '') {
      return iconv.decode(Buffer.from(str, binaryEncoding), encoding);
  }

  const  { exec } = require('child_process');
  exec('xxx', { encoding: 'binary' }, (err, stdout, stderr) => {
        const result = iconvDecode(stdout);
        xxx
  });
</code>```

Body:
Using the dir command in Windows CMD will result in the following output:

Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 testöäüÄÖÜ.txt
22.12.2013  17:27    <DIR>          testÖÄÜöüäß
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei

Using exec or spawn will result in this:

Verzeichnis von D:\workspace\filewalker

22.12.2013  17:27    <DIR>          .
22.12.2013  17:27    <DIR>          ..
22.12.2013  17:48               392 test.js
22.12.2013  17:23                 0 test������.txt
22.12.2013  17:27    <DIR>          test�������
2 Datei(en),            392 Bytes
3 Verzeichnis(se), 273.731.170.304 Bytes frei

Here is my Node Code:

var exec = require('child_process').exec,
    child;

child = exec('dir',
  function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

Body:
I solved it (Simplified Chinese) by below code, don't know the coding page for other languages, maybe you can find it from Microsoft website:

  const encoding          = 'cp936';
  const binaryEncoding    = 'binary';

  function iconvDecode(str = '') {
      return iconv.decode(Buffer.from(str, binaryEncoding), encoding);
  }

  const  { exec } = require('child_process');
  exec('xxx', { encoding: 'binary' }, (err, stdout, stderr) => {
        const result = iconvDecode(stdout);
        xxx
  });


问:
How to call a function after closing a popover?
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

```<code>@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }
</code>```

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

```<code> func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }
</code>```

So with the above I get:

```<code> Use of unresolved identifier 'checkIfPopoverDismissed'
</code>```

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

答:
The best approach would be to call it in the viewWillAppear of the MainViewController. Here's how:

class MainViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        checkIfPopoverDismissed()
    }
}
```

<p>Note: If you don't want this to be called every time the <code>MainViewController</code> has appeared then you can give a check for when the popover is presented and toggle it when the popover is presented and invoke this function only when the condition is satisfied. Here's how you achieve this:</p>

<pre class="lang-swift prettyprint-override"><code>class ViewController: UIViewController {
    var isPopoverPresented = false
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isPopoverPresented {
            isPopoverPresented.toggle()
            checkIfPopoverDismissed()
        }
    }
    func presentPopover() {
        isPopoverPresented.toggle()
        present(PopoverController(), animated: true)
    }
}
</code>```

Body:
I hope someone can give a beginner some guidance, my problem is this:

I have a popover window
I open that popover with a segue from the mainViewController
I want to trigger a function in the mainViewController when the popover is closed
Inside the popover I have a button to close the popover with the following code:

@IBAction func closeButton(_ sender: Any) {

        dismiss(animated: true, completion: {checkIfPopoverDismissed()}) // I want to trigger this function in the mainView
    }

In the mainViewController I have the following function, that I want to be triggered by the closure of the above popover

 func checkIfPopoverDismissed()
    {
      print("the function is triggered")
    }

So with the above I get:

 Use of unresolved identifier 'checkIfPopoverDismissed'

Because obviously checkIfPopoverDismissed() is in the mainViewController and does not exist in the popover view.

Any idea how I can make this work simply?

Body:
The best approach would be to call it in the viewWillAppear of the MainViewController. Here's how:

class MainViewController: UIViewController {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        checkIfPopoverDismissed()
    }
}

Note: If you don't want this to be called every time the MainViewController has appeared then you can give a check for when the popover is presented and toggle it when the popover is presented and invoke this function only when the condition is satisfied. Here's how you achieve this:

class ViewController: UIViewController {
    var isPopoverPresented = false
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if isPopoverPresented {
            isPopoverPresented.toggle()
            checkIfPopoverDismissed()
        }
    }
    func presentPopover() {
        isPopoverPresented.toggle()
        present(PopoverController(), animated: true)
    }
}


问:
I need a function that returns only the titles of my structures in SwiftUI
So this might be simple fix, but I am pretty new to Xcode and SwiftUI. I have a structure that includes a title as a property, and I am trying to list only the titles in a search bar inside a tab view, here is what I got so far, the only function that is working for me is randomElement()!, which only shows one random title in my list obviously

here is where I want to place the function

```<code>TabView {
        Searchbar(duaa: .constant(Duaa.demoDuaa.randomElement()!))
        .tabItem {
        VStack {
               Image(systemName: "book.circle")
                 .renderingMode(.original)
                 Text(verbatim: "PRAYERS")
                }
           }.tag(2)
}
</code>```

and this is the code of my structure

```<code>import SwiftUI

struct Duaa: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var duaaContext: String
  var duaabenefit: String
  var isLiked = false
}

extension Duaa: Equatable {
  static func == (lhs: Duaa, rhs: Duaa) -> Bool {
    return lhs.id == rhs.id
  }

    }
extension Duaa {
  static let demoDuaa = [
    Duaa(title: "blue", imageName: "blueimage"),
    Duaa(title: "yellow", imageName: "yellowimage"),
    Duaa(title: "Orange", imageName: "orangeimage"),
    Duaa(title: "Green", imageName: "greenimage"),
    Duaa(title: "Purple", imageName: "purpleimage")
]
}
</code>```

答:
If you have an array of Duaa objects, you can map over it and pull out the titles easily.

var duaaTitles = arrayOfDuaas.map{ $0.title }

That will create an array of titles.

Even better would be a .compactMap{} because that will eliminate any possible nils.

You’ll need to show more of your code (like your Searchbar implementation) if you want specific help.

Also, you’re doing a lot of work with the static struct definition Duaa (like a blueprint of a Duaa rather than an actual Duaa), rather than an instance of it. Is that on purpose?

Body:
So this might be simple fix, but I am pretty new to Xcode and SwiftUI. I have a structure that includes a title as a property, and I am trying to list only the titles in a search bar inside a tab view, here is what I got so far, the only function that is working for me is randomElement()!, which only shows one random title in my list obviously

here is where I want to place the function

TabView {
        Searchbar(duaa: .constant(Duaa.demoDuaa.randomElement()!))
        .tabItem {
        VStack {
               Image(systemName: "book.circle")
                 .renderingMode(.original)
                 Text(verbatim: "PRAYERS")
                }
           }.tag(2)
}

and this is the code of my structure

import SwiftUI

struct Duaa: Identifiable {
  var id = UUID()
  var title: String
  var imageName: String
  var duaaContext: String
  var duaabenefit: String
  var isLiked = false
}

extension Duaa: Equatable {
  static func == (lhs: Duaa, rhs: Duaa) -> Bool {
    return lhs.id == rhs.id
  }

    }
extension Duaa {
  static let demoDuaa = [
    Duaa(title: "blue", imageName: "blueimage"),
    Duaa(title: "yellow", imageName: "yellowimage"),
    Duaa(title: "Orange", imageName: "orangeimage"),
    Duaa(title: "Green", imageName: "greenimage"),
    Duaa(title: "Purple", imageName: "purpleimage")
]
}


问:
Does View Binding support view binding for Adapter classes
I have just updated Android Studio to 3.6 and enabled View Binding in my project and I can use View Binding in my Fragments.

I have ListItemAdapter class which subclass from BaseExpandableListAdapter and I want to use View Binding for this class also. It seems it is not supported for Adapter Classes ?

As I mentioned above. I am using ExpandableListView. Below is code for inflating GroupView and ChildView inside expandableListView Adapter Class.

For now I am using KotlinX.android.synthetic

```<code>override fun getGroupView(
    groupPosition: Int,
    isExpanded: Boolean,
    convertView: View?,
    parent: ViewGroup?
): View {
    var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_parent_sidemenu, null)
    convertView!!.imgGroupIndicatorIcon.isSelected = isExpanded
    var headerTitle = getGroup(groupPosition) as String
    convertView!!.txtSideMenuParent.text = headerTitle
    return convertView!!
}

override fun getChildView(
    groupPosition: Int,
    childPosition: Int,
    isLastChild: Boolean,
    convertView: View?,
    parent: ViewGroup?
): View {
    var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_child_sidemenu, null)
    var childText = getChild(groupPosition, childPosition) as String
    convertView!!.txtSideMenuChild.text = childText
    return convertView!!
}
</code>```

答:
```<code>enter code here
</code>```

val view  = BistItemParentSidemenuBinding
.inflate(LayoutInflater.from(parent.context),
            parent, false).root

This above should work instead of

var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_child_sidemenu, null)

Body:
I have just updated Android Studio to 3.6 and enabled View Binding in my project and I can use View Binding in my Fragments.

I have ListItemAdapter class which subclass from BaseExpandableListAdapter and I want to use View Binding for this class also. It seems it is not supported for Adapter Classes ?

As I mentioned above. I am using ExpandableListView. Below is code for inflating GroupView and ChildView inside expandableListView Adapter Class.

For now I am using KotlinX.android.synthetic

override fun getGroupView(
    groupPosition: Int,
    isExpanded: Boolean,
    convertView: View?,
    parent: ViewGroup?
): View {
    var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_parent_sidemenu, null)
    convertView!!.imgGroupIndicatorIcon.isSelected = isExpanded
    var headerTitle = getGroup(groupPosition) as String
    convertView!!.txtSideMenuParent.text = headerTitle
    return convertView!!
}

override fun getChildView(
    groupPosition: Int,
    childPosition: Int,
    isLastChild: Boolean,
    convertView: View?,
    parent: ViewGroup?
): View {
    var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_child_sidemenu, null)
    var childText = getChild(groupPosition, childPosition) as String
    convertView!!.txtSideMenuChild.text = childText
    return convertView!!
}

Body:
enter code here

val view  = BistItemParentSidemenuBinding
.inflate(LayoutInflater.from(parent.context),
            parent, false).root

This above should work instead of

var convertView: View? = convertView
        ?: return context.layoutInflater.inflate(R.layout.list_item_child_sidemenu, null)


问:
Login only if user is active using Laravel
I'm currently working on my Laravel app and to prevent spam I decided that only active users are able to login.
I'm currently using Laravel's login system just like in Laravel's official website tutorial, here's my form action:

```<code><form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
</code>```

This works completely fine, however I'd like to check the user's active, if not active it would be redirected to the activation page, otherwise it would login.
Is there a simple way to do this or am I obligated to make a new controller, routes and more verifications? Thank you.

Edit: Forgot to mention that I have a 'active' column in my database.

答:
On laravel 7, you only need to put this method on LoginController:

```<code>/**
 * Custom credentials to validate the status of user.
 */
public function credentials(Request $request)
{
    return [
        'email'     => $request->email,
        'password'  => $request->password,
        'is_active' => '1'
    ];
}
</code>```

In this way, you can validate any condition for login.

Body:
I'm currently working on my Laravel app and to prevent spam I decided that only active users are able to login.
I'm currently using Laravel's login system just like in Laravel's official website tutorial, here's my form action:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">

This works completely fine, however I'd like to check the user's active, if not active it would be redirected to the activation page, otherwise it would login.
Is there a simple way to do this or am I obligated to make a new controller, routes and more verifications? Thank you.

Edit: Forgot to mention that I have a 'active' column in my database.

Body:
On laravel 7, you only need to put this method on LoginController:

/**
 * Custom credentials to validate the status of user.
 */
public function credentials(Request $request)
{
    return [
        'email'     => $request->email,
        'password'  => $request->password,
        'is_active' => '1'
    ];
}

In this way, you can validate any condition for login.


问:
Cannot getText from EditText in AlertDialog that has setView
I made a custom XML layout file, in there I have an EditText.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_margin="20dp"
        android:id="@+id/length"
        android:layout_width="match_parent"
        android:inputType="number"
        android:hint="Vibration time(ms)"
        android:importantForAutofill="no"
        android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

In another activity, I made an AlertDialog, then I setView to this layout. It was successful and I see EditText in the AlertDialog.
But the problem is, when I do this:

```<code>EditText edittext=(EditText)findViewById(R.id.length);
int time=Integer.parseInt(edittext.getText().toString());
</code>```

An error happens and say

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
</code>```

I don't know why it says null object because I gave EditText an ID.

答:
You must use findViewById in alert dialog view

```<code> ViewGroup viewGroup = findViewById(android.R.id.content);

    View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setView(dialogView);

    EditText edittext=dialogView.findViewById(R.id.length);
    int time=Integer.parseInt(edittext.getText().toString());

    AlertDialog alertDialog = builder.create();
    alertDialog.show();
</code>```

Body:
I made a custom XML layout file, in there I have an EditText.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_margin="20dp"
        android:id="@+id/length"
        android:layout_width="match_parent"
        android:inputType="number"
        android:hint="Vibration time(ms)"
        android:importantForAutofill="no"
        android:layout_height="wrap_content"/>
</LinearLayout>

In another activity, I made an AlertDialog, then I setView to this layout. It was successful and I see EditText in the AlertDialog.
But the problem is, when I do this:

EditText edittext=(EditText)findViewById(R.id.length);
int time=Integer.parseInt(edittext.getText().toString());

An error happens and say

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I don't know why it says null object because I gave EditText an ID.

Body:
You must use findViewById in alert dialog view

 ViewGroup viewGroup = findViewById(android.R.id.content);

    View dialogView = LayoutInflater.from(this).inflate(R.layout.my_dialog, viewGroup, false);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setView(dialogView);

    EditText edittext=dialogView.findViewById(R.id.length);
    int time=Integer.parseInt(edittext.getText().toString());

    AlertDialog alertDialog = builder.create();
    alertDialog.show();


问:
Can someone explain this one line of code?
```<code> public static int fiveOfaKind(int dice[]){
</code>```

Obviously it is declaring a method but what I'm confused about is the part that goes "(int dice[])"

dice is an integer array that was declared in the main method.

What does that bit in the parenthesis do? And what is it called, I want to look it up and read about it.

答:
What does that bit in the parenthesis do?

It requires that it is an array of variable length.

what is it called

Square brackets

Hope that helps...

Body:
 public static int fiveOfaKind(int dice[]){

Obviously it is declaring a method but what I'm confused about is the part that goes "(int dice[])"

dice is an integer array that was declared in the main method.

What does that bit in the parenthesis do? And what is it called, I want to look it up and read about it.


答:
It's a parameter for the method. The dice array declared in the main method is in a different scope and unrelated to this method.

```<code>public static void printArr(int arr[]) {
    for(int i = 0; i < arr.length; i++){
        System.out.println(arr[i]);
    }
}

public static void main(String args[]) {
    int[] dice = new int[5];
    ...

    foo(dice);
}
</code>```

In this example you have a method that takes an array and prints the elements in it. In the main method you pass this array to the method as a parameter.

https://www.w3schools.com/java/java_methods_param.asp

Title: Can someone explain this one line of code?

Body:
It's a parameter for the method. The dice array declared in the main method is in a different scope and unrelated to this method.

public static void printArr(int arr[]) {
    for(int i = 0; i < arr.length; i++){
        System.out.println(arr[i]);
    }
}

public static void main(String args[]) {
    int[] dice = new int[5];
    ...

    foo(dice);
}

In this example you have a method that takes an array and prints the elements in it. In the main method you pass this array to the method as a parameter.

https://www.w3schools.com/java/java_methods_param.asp


问:
Rails: How can I remove default version of bundler?
I tried to change default bundle version but it getting updated with 2 default version. How can I modify to single default?

```<code>$ gem list bundler

*** LOCAL GEMS ***

bundler (2.0.1, default: 1.16.6, default: 1.16.2)
</code>```

If I do gem uninstall not removing defaults,

```<code>$ gem uninstall bundler
Successfully uninstalled bundler-2.0.1

$ gem list bundle

*** LOCAL GEMS ***

bundler (default: 1.16.6, default: 1.16.2)
</code>```

How can I set (like the below) default as single version?

```<code>bundler (2.0.1, default: 1.16.6)
</code>```

答:
For those who use rbenv, let say by accidentally you have two default versions

$ gem list | grep bundler
bundler (default: 2.1.4, default: 1.17.2)
```

<p>Check your gem installation path</p>

<pre class="lang-sh prettyprint-override"><code>$ gem environment
RubyGems Environment:
.
.
- INSTALLATION DIRECTORY: /home/yohanes/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0
.
</code>```

Go to the specifications/default directory and look for bundlers gemspec

$ cd /home/yohanes/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/specifications/default
$ ls -lah
total 200K
drwxr-xr-x 2 yohanes yohanes 4,0K Jun  1 10:05 .
drwxr-xr-x 3 yohanes yohanes  20K Jun  1 10:05 ..
.
.
-rw-r--r-- 1 yohanes yohanes  16K Jun  1 10:05 bundler-1.17.2.gemspec
-rw-r--r-- 1 yohanes yohanes  15K Jun  1 09:31 bundler-2.1.4.gemspec
.
.
```

<p>Remove the version that you need to remove</p>

<pre class="lang-sh prettyprint-override"><code>$ rm bundler-2.1.4.gemspec
</code>```

Check again

$ gem list | grep bundler
bundler (default: 1.17.2)
$ gem list bundler

*** LOCAL GEMS ***

bundler (default: 1.17.2)
```

<p>but, if you check bundle version, you still get the deleted version as default</p>

<pre class="lang-sh prettyprint-override"><code>$ bundler -v
Bundler version 2.1.4
</code>```

So we have to overrides it by reinstalling the required bundler version again

$ gem install bundler --version '1.17.2'
Successfully installed bundler-1.17.2
Parsing documentation for bundler-1.17.2
Done installing documentation for bundler after 1 seconds
1 gem installed
```

<p>Then, if you check again it will show you the desired version</p>

<pre class="lang-sh prettyprint-override"><code>$ bundle -v
Bundler version 1.17.2
</code>```

Body:
I tried to change default bundle version but it getting updated with 2 default version. How can I modify to single default?

$ gem list bundler

*** LOCAL GEMS ***

bundler (2.0.1, default: 1.16.6, default: 1.16.2)

If I do gem uninstall not removing defaults,

$ gem uninstall bundler
Successfully uninstalled bundler-2.0.1

$ gem list bundle

*** LOCAL GEMS ***

bundler (default: 1.16.6, default: 1.16.2)

How can I set (like the below) default as single version?

bundler (2.0.1, default: 1.16.6)

Body:
For those who use rbenv, let say by accidentally you have two default versions

$ gem list | grep bundler
bundler (default: 2.1.4, default: 1.17.2)

Check your gem installation path

$ gem environment
RubyGems Environment:
.
.
- INSTALLATION DIRECTORY: /home/yohanes/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0
.

Go to the specifications/default directory and look for bundlers gemspec

$ cd /home/yohanes/.rbenv/versions/2.6.5/lib/ruby/gems/2.6.0/specifications/default
$ ls -lah
total 200K
drwxr-xr-x 2 yohanes yohanes 4,0K Jun  1 10:05 .
drwxr-xr-x 3 yohanes yohanes  20K Jun  1 10:05 ..
.
.
-rw-r--r-- 1 yohanes yohanes  16K Jun  1 10:05 bundler-1.17.2.gemspec
-rw-r--r-- 1 yohanes yohanes  15K Jun  1 09:31 bundler-2.1.4.gemspec
.
.

Remove the version that you need to remove

$ rm bundler-2.1.4.gemspec

Check again

$ gem list | grep bundler
bundler (default: 1.17.2)
$ gem list bundler

*** LOCAL GEMS ***

bundler (default: 1.17.2)

but, if you check bundle version, you still get the deleted version as default

$ bundler -v
Bundler version 2.1.4

So we have to overrides it by reinstalling the required bundler version again

$ gem install bundler --version '1.17.2'
Successfully installed bundler-1.17.2
Parsing documentation for bundler-1.17.2
Done installing documentation for bundler after 1 seconds
1 gem installed

Then, if you check again it will show you the desired version

$ bundle -v
Bundler version 1.17.2


问:
Remove duplicate values in each column in every row pandas python
I have 4 columns ( Name, Area, State, Email). In column Email has duplicate email after i group by and join the value. The output turns out to be:

```<code>Area    Group   Shift         Email
KM      MFG     A1,A2,A3      a@gmail.com,a@gmail.com,b@gmail.com
RIM     TEST    A1,B1         c@gmail.com,b@gmail.com,c@gmail.com
PNG    FINISH   C1,C2,C3      a@gmail.com,c@gmail.com,a@gmail.com
KL     Manager  NORMAL,B1,B1  b@gmail.com,a@gmail.com,c@gmail.com,a@gmail.com
</code>```

I need to remove the duplicate email in column 'Email'. Anyone can help me?

答:
Let us try </p>

```<code>df.Email=df.Email.str.split(',').apply(set).str.join(',')
df
  Area    Group         Shift                                Email
0   KM      MFG      A1,A2,A3              a@gmail.com,b@gmail.com
1  RIM     TEST         A1,B1              c@gmail.com,b@gmail.com
2  PNG   FINISH      C1,C2,C3              c@gmail.com,a@gmail.com
3   KL  Manager  NORMAL,B1,B1  c@gmail.com,a@gmail.com,b@gmail.com
</code>```

Body:
I have 4 columns ( Name, Area, State, Email). In column Email has duplicate email after i group by and join the value. The output turns out to be:

Area    Group   Shift         Email
KM      MFG     A1,A2,A3      a@gmail.com,a@gmail.com,b@gmail.com
RIM     TEST    A1,B1         c@gmail.com,b@gmail.com,c@gmail.com
PNG    FINISH   C1,C2,C3      a@gmail.com,c@gmail.com,a@gmail.com
KL     Manager  NORMAL,B1,B1  b@gmail.com,a@gmail.com,c@gmail.com,a@gmail.com

I need to remove the duplicate email in column 'Email'. Anyone can help me?

Body:
Let us try

df.Email=df.Email.str.split(',').apply(set).str.join(',')
df
  Area    Group         Shift                                Email
0   KM      MFG      A1,A2,A3              a@gmail.com,b@gmail.com
1  RIM     TEST         A1,B1              c@gmail.com,b@gmail.com
2  PNG   FINISH      C1,C2,C3              c@gmail.com,a@gmail.com
3   KL  Manager  NORMAL,B1,B1  c@gmail.com,a@gmail.com,b@gmail.com


答:
you need to call e.preventDefault(), but also you need to add onChange handler to input:

```<code>  const handleKeyDown = e => {
    console.log(e.key);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
      e.preventDefault();
    }
  };

const handleChange = e => setInputValue(e.target.value);
...

  <input
    type="text"
    value={inputValue}
    onChange={handleChange}
    onKeyDown={handleKeyDown}
    placeholder={placeholder}
  />
</code>```

Title: onKeyDown get value from e.target.value?

Body:
What's wrong with my way to handle input in react? I want to detect keycode and prevent them to be entered into the input, but now below code doesn't seem working.

const Input = ({ placeholder }) => {   const [inputValue, setInputValue] = useState("");

  const handleKeyDown = e => {
    console.log(e.target.value);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }   };

  return (

      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />

   ); };

https://codesandbox.io/s/ancient-waterfall-43not?file=/src/App.js

Body:
you need to call e.preventDefault(), but also you need to add onChange handler to input:

  const handleKeyDown = e => {
    console.log(e.key);
    if ([188].includes(e.keyCode)) {
      console.log("comma");
      e.preventDefault();
    }
  };

const handleChange = e => setInputValue(e.target.value);
...

  <input
    type="text"
    value={inputValue}
    onChange={handleChange}
    onKeyDown={handleKeyDown}
    placeholder={placeholder}
  />


答:
Pass the value from Parent to child. Please check the below code.</p>

```<code>import React, { useState } from "react";
import "./styles.css";

const Input = ({ placeholder, inputValue, handleKeyDown }) => {
  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />
    </div>
  );
};

export default function App() {
  const [inputValue, setInputValue] = useState();

  const handleKeyDown = e => {
    console.log(e.keyCode);
    console.log(e.target.value);
    if ([40].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }
  };
  return (
    <div className="App">
      <Input
        placeholder="xx"
        value={inputValue}
        handleKeyDown={handleKeyDown}
      />
    </div>
  );
}
</code>```

Body:
Pass the value from Parent to child. Please check the below code.

import React, { useState } from "react";
import "./styles.css";

const Input = ({ placeholder, inputValue, handleKeyDown }) => {
  return (
    <div>
      <input
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        placeholder={placeholder}
      />
    </div>
  );
};

export default function App() {
  const [inputValue, setInputValue] = useState();

  const handleKeyDown = e => {
    console.log(e.keyCode);
    console.log(e.target.value);
    if ([40].includes(e.keyCode)) {
      console.log("comma");
    } else {
      setInputValue(e.target.value);
    }
  };
  return (
    <div className="App">
      <Input
        placeholder="xx"
        value={inputValue}
        handleKeyDown={handleKeyDown}
      />
    </div>
  );
}


问:
Can't change nav-link color in bootstrap 4
```<code><nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
        <div class="mx-auto my-2 order-0 order-md-1 position-relative">
            <div id="top_logo" class="container-fluid">
                <span>VirtualQR</span>
            </div>
        </div>
        <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#section_navbar">Home</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_pricing">Pricings</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#section_contact">Contacts</a>
                </li>
            </ul>
</code>```

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

答:
With the following CSS selector, you will be able to change the color of the nav-link class.

.nav-link {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
  <div class="mx-auto my-2 order-0 order-md-1 position-relative">
    <div id="top_logo" class="container-fluid">
      <span>VirtualQR</span>
    </div>
  </div>
  <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        Home
      </li>
      <li class="nav-item">
        How does it work?
      </li>
      <li class="nav-item">
        Pricings
      </li>
      <li class="nav-item">
        Contacts
      </li>
    </ul>
  </div>
</nav></code>```

Body:
                VirtualQR

                    Home

                    How does it work?

                    Pricings

                    Contacts

I can't get the nav-link to change color. I've tried other posts solutions but couldn't get it to work anyways.
I don't know if it has something to do with my code.

Body:
With the following CSS selector, you will be able to change the color of the nav-link class.

.nav-link {
  color: red;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

<nav id="section_navbar" class="navbar navbar-expand-lg fixed-top">
  <div class="mx-auto my-2 order-0 order-md-1 position-relative">
    <div id="top_logo" class="container-fluid">
      <span>VirtualQR</span>
    </div>
  </div>
  <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-1">
    <ul class="navbar-nav ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#section_navbar">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section_howdoesitwork">How does it work?</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section_pricing">Pricings</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#section_contact">Contacts</a>
      </li>
    </ul>
  </div>
</nav>


问:
ERROR: No matching distribution found for re
I am trying to run a Python script on Cpanel using Python Application and when I add all module in a text file and run pip install I am getting this error.

ERROR: Could not find a version that satisfies the requirement re
ERROR: No matching distribution found for re

答:
re is Python's regex module, in fact, most of the modules listed there are python's built in modules. They don't need to be installed via pip and should be available automatically when you use import statements.

You can refer to built in modules here:
https://docs.python.org/3/library/index.html


答:
You need to include the PHP file which contains your function(s).

In this case, if you're "index" page is called index.php and your function, Connect() is stored in functions.php then you would do:

index.php:

```<code>include "functions.php";
Connect();
</code>```

Title: how can i use from methods in other pages?

Body:
HI,
i have 2 php pages.first page has some functions like Connect(),... .i want to use from Connect() function in second page but when use from Connect() can not recognize it.i use from header("first.php") but have same error.
how can i solve that problem?

Body:
You need to include the PHP file which contains your function(s).

In this case, if you're "index" page is called index.php and your function, Connect() is stored in functions.php then you would do:

index.php:

include "functions.php";
Connect();


问:
POSTGRESQL error working with Spring MVC/Hibernate 'Large Objects may not be used in auto-commit mode'
Of course this one seems easy enough per Here but I added the following to my application context...

```<code><property name="dataSource">
    <ref bean="dataSource"/>
</property>

<property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.autocommit">false</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>com.gleason.gt.server.model.database.PlayListEntry</value>
            <value>com.gleason.gt.server.model.database.MusicFile</value>
        </list>
    </property>
</bean>
</code>```

I still get the same error, any ideas?

UPDATE
Adding Service/DAO

```<code>@Repository("musicFileDao")
public class MusicFileDAOImpl extends GroovyTimeHibernateDAOSupport{
@Transactional()
public MusicFile getMusicFile(Integer i){
    @SuppressWarnings("unchecked")
    List<MusicFile> returnValue = (List<MusicFile>)getHibernateTemplate().find("from MusicFile where id=?",i);
    if(returnValue.size()>0){
        return returnValue.get(0);
    }
    return null;
}
}
@Service("musicFileService")
public class MusicFileService {
@Autowired
private MusicFileDAOImpl dao;

@Transactional
public MusicFile getMusicFile(Integer i){
    return dao.getMusicFile(i);
}
}

@Lob
@Column(name="file")
private byte[] file;
</code>```

答:
Using Spring boot 2+
There are two ways:

Create a configuration class that configures the datasource, and change Hikari behavior

```<code>@Configuration
public class DataSourceConfiguration {

    // (...) some @Value(s) (...)

    @Bean
    public DataSource getDataSource() {

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);

        // these are optional
        config.setMinimumIdle(minumunIdle);
        config.setMaximumPoolSize(maximunPoolSize);
        config.setPoolName(poolName);
        config.setConnectionTimeout(connectionTimeout);
        config.setIdleTimeout(idleTimeout);
        config.setMaxLifetime(maxLifetime);

        // sets auto-commit to false
        config.setAutoCommit(false);

        return new HikariDataSource(config);
    }
}
</code>```

or in application.properties, this key/value can be set:

```<code>spring.datasource.hikari.auto-commit=false
</code>```

Body:
Of course this one seems easy enough per Here but I added the following to my application context...

<property name="dataSource">
    <ref bean="dataSource"/>
</property>

<property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.autocommit">false</prop>
        </props>
    </property>
    <property name="annotatedClasses">
        <list>
            <value>com.gleason.gt.server.model.database.PlayListEntry</value>
            <value>com.gleason.gt.server.model.database.MusicFile</value>
        </list>
    </property>
</bean>

I still get the same error, any ideas?

UPDATE
Adding Service/DAO

@Repository("musicFileDao")
public class MusicFileDAOImpl extends GroovyTimeHibernateDAOSupport{
@Transactional()
public MusicFile getMusicFile(Integer i){
    @SuppressWarnings("unchecked")
    List<MusicFile> returnValue = (List<MusicFile>)getHibernateTemplate().find("from MusicFile where id=?",i);
    if(returnValue.size()>0){
        return returnValue.get(0);
    }
    return null;
}
}
@Service("musicFileService")
public class MusicFileService {
@Autowired
private MusicFileDAOImpl dao;

@Transactional
public MusicFile getMusicFile(Integer i){
    return dao.getMusicFile(i);
}
}

@Lob
@Column(name="file")
private byte[] file;

Body:
Using Spring boot 2+
There are two ways:

Create a configuration class that configures the datasource, and change Hikari behavior

@Configuration
public class DataSourceConfiguration {

    // (...) some @Value(s) (...)

    @Bean
    public DataSource getDataSource() {

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(driverClassName);
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);

        // these are optional
        config.setMinimumIdle(minumunIdle);
        config.setMaximumPoolSize(maximunPoolSize);
        config.setPoolName(poolName);
        config.setConnectionTimeout(connectionTimeout);
        config.setIdleTimeout(idleTimeout);
        config.setMaxLifetime(maxLifetime);

        // sets auto-commit to false
        config.setAutoCommit(false);

        return new HikariDataSource(config);
    }
}

or in application.properties, this key/value can be set:

spring.datasource.hikari.auto-commit=false


问:
Mongo search query .net c#
Suppose i have the following variables:
string SKU, string Purchase, string Slider, string Category

.. and the "ID" field in Mongo must contain string value in SKU or if its null or empty, it does not apply.
.. Field "URL" in Mongo must contain string value in Purchase or if its null or empty, it does not apply.
.. Field "Refer" in Mongo must contain string value in Slider or if its null or empty, it does not apply.
.. Field "Category" must contain string value in Category or if its null or empty, it does not apply.

i finally need the count of number of findings.

how do i construct the query in .net?

答:
Since you mentioned that the fields must contain the string values, I assume you want to apply .Contains() not check for string equality.
The following should work, as well as being case-insensitive.

With collection as your IMongoCollection<Record>, and strongly typed Record as in derloopkat's answer:

```<code>var query = collection.AsQueryable();

if (!string.IsNullOrEmpty(sku))
{
    query = query.Where(r => r.ID.ToLower().Contains(sku));
}

if (!string.IsNullOrEmpty(purchase))
{
    query = query.Where(r => r.URL.ToLower().Contains(purchase));
}

if (!string.IsNullOrEmpty(slider))
{
    query = query.Where(r => r.Refer.ToLower().Contains(slider));
}

if (!string.IsNullOrEmpty(category))
{
    query = query.Where(r => r.Category.ToLower().Contains(category));
}

// Commented out, since you mentioned you only want the count
// var results = query.ToList();

var count = query.Count();
</code>```

Another option, if you want to extend this filtering support dynamically...

```<code>public static class MongoExtensions
{
    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        Expression<Func<T, object>> field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<T>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }

    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        string field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<BsonDocument>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }
}
</code>```

```<code>var query = collection
    .AsQueryable()
    .Filter("ID", sku) // Refer to the field with a string...
    .Filter("URL", purchase)
    .Filter(r => r.Refer, slider) // ... or use a lambda expression
    .Filter(r => r.Category, category);

var count = query.Count();
</code>```

Title: Mongo search query .net c#

Body:
Since you mentioned that the fields must contain the string values, I assume you want to apply .Contains() not check for string equality.
The following should work, as well as being case-insensitive.

With collection as your IMongoCollection<Record>, and strongly typed Record as in derloopkat's answer:

var query = collection.AsQueryable();

if (!string.IsNullOrEmpty(sku))
{
    query = query.Where(r => r.ID.ToLower().Contains(sku));
}

if (!string.IsNullOrEmpty(purchase))
{
    query = query.Where(r => r.URL.ToLower().Contains(purchase));
}

if (!string.IsNullOrEmpty(slider))
{
    query = query.Where(r => r.Refer.ToLower().Contains(slider));
}

if (!string.IsNullOrEmpty(category))
{
    query = query.Where(r => r.Category.ToLower().Contains(category));
}

// Commented out, since you mentioned you only want the count
// var results = query.ToList();

var count = query.Count();

Another option, if you want to extend this filtering support dynamically...

public static class MongoExtensions
{
    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        Expression<Func<T, object>> field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<T>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }

    public static IMongoQueryable<T> Filter<T>(
        this IMongoQueryable<T> query,
        string field,
        string searchValue)
    {
        if (string.IsNullOrEmpty(searchValue))
        {
            return query;
        }

        var rx = new BsonRegularExpression(Regex.Escape(searchValue), "i");
        var filter = Builders<BsonDocument>.Filter.Regex(field, rx);
        return query.Where(_ => filter.Inject());
    }
}

var query = collection
    .AsQueryable()
    .Filter("ID", sku) // Refer to the field with a string...
    .Filter("URL", purchase)
    .Filter(r => r.Refer, slider) // ... or use a lambda expression
    .Filter(r => r.Category, category);

var count = query.Count();


问:
anchor not sizing buttons properly and text disappearing how to fix it?
in the video below you can see how my buttons behave when i try to resize the window after anchoring them. My application does not have an exist button for some reason either, could not find a solution online and have no clue on how to fix it for the time being. Sorry for potato quality....

https://youtu.be/6WY_19Qdy4c

答:
Did you know that sometimes anchor cannot fix of what will you want to achieve?

Instead of anchoring you can use tableLayoutPanel?

The only properties of tableLayoutPanel is Dock = Fill;

After that you can now add columns and rows in the table and button inside the cell, it will automatically resize your button.

Add a tableLayoutPanel set Dock to Fill

Click tableLayoutPanel

Edit Rows and Columns (Add Column or Rows Change Absolute to Percent it should be 50%)

Press OK

If you want to span Rows and Columns click the control inside the Cell and find ColumnSpan and RowSpan in the properties


问:
SQL conditional sum of nutritional values
I have a simple enough table like this.

```<code>NutritionID | Value
----------------------
1           |    10
2           |    11
3           |    12
1           |    N
1           |    Tr
1           |    NULL
</code>```

Expected result

```<code>NutritionID   | Value
----------------------
 1            |   N
 2            |   11
 3            |   12
</code>```

I need to get the sum for each NutritionID. But there are rules that determine the final value.
For example,

N + N = N

N + Tr = N

N + a value = N

Tr + a value = value

Tr + NULL = Tr

NULL + 0 = 0

Solution in mind

Create a cursor for NutritionID

keep the running sum in a variable

implement the above rules in if/else statements

problem

Is there a better way to get the sum efficiently and with a non-cursor solution? perhaps using case statements?

Thanks a lot.

答:
You should not be mixing strings and numeric values in the same column - and your computation rules are quite convoluted.

I think that you can do what you want with conditional logic:

```<code>select
    nutritionID,
    case
        when max(value = 'N' then 1 else 0 end) = 1
            then 'N'
        when sum(try_cast(value as int)) is not null
            then cast(sum(try_cast(value as int)) as varchar(10))
        when max(value = 'Tr' then 1 else 0 end) = 1
            then 'Tr'
    end
from mytable
group by nutritionID
</code>```

Basically this gives priority to 'N', then to a non-null sum of integer values, then to Tr, and yields null if none of these conditions match.

Body:
I have a simple enough table like this.

NutritionID | Value
----------------------
1           |    10
2           |    11
3           |    12
1           |    N
1           |    Tr
1           |    NULL

Expected result

NutritionID   | Value
----------------------
 1            |   N
 2            |   11
 3            |   12

I need to get the sum for each NutritionID. But there are rules that determine the final value.
For example,

N + N = N

N + Tr = N

N + a value = N

Tr + a value = value

Tr + NULL = Tr

NULL + 0 = 0

Solution in mind

Create a cursor for NutritionID

keep the running sum in a variable

implement the above rules in if/else statements

problem

Is there a better way to get the sum efficiently and with a non-cursor solution? perhaps using case statements?

Thanks a lot.

Body:
You should not be mixing strings and numeric values in the same column - and your computation rules are quite convoluted.

I think that you can do what you want with conditional logic:

select
    nutritionID,
    case
        when max(value = 'N' then 1 else 0 end) = 1
            then 'N'
        when sum(try_cast(value as int)) is not null
            then cast(sum(try_cast(value as int)) as varchar(10))
        when max(value = 'Tr' then 1 else 0 end) = 1
            then 'Tr'
    end
from mytable
group by nutritionID

Basically this gives priority to 'N', then to a non-null sum of integer values, then to Tr, and yields null if none of these conditions match.


问:
Django Forms Newbie Question
Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point.

I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following:

invalid literal for int() with base 10: 'test'

So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks.

For what it's worth here are the models:

```<code>class Quiz(models.Model):
    label = models.CharField(blank=True, max_length=400)
    slug = models.SlugField()

    def __unicode__(self):
        return self.label

class Question(models.Model):
    label = models.CharField(blank=True, max_length=400)
    quiz = models.ForeignKey(Quiz)

    def __unicode__(self):
        return self.label

class Answer(models.Model):
    label = models.CharField(blank=True, max_length=400)
    question = models.ForeignKey(Question)
    correct = models.BooleanField()

    def __unicode__(self):
        return self.label
</code>```

答:
First, you create a ModelForm for a given Model. In this example I'm doing it for Quiz but you can rinse and repeat for your other models. For giggles, I'm making the "label" be a Select box with preset choices:

```<code>from django.models import BaseModel
from django import forms
from django.forms import ModelForm

CHOICES_LABEL = (
    ('label1', 'Label One'),
    ('label2', 'Label Two')

)

class Quiz(models.Model):
    label = models.CharField(blank=True, max_length=400)
    slug = models.SlugField()

    def __unicode__(self):
        return self.label

class QuizForm(ModelForm):
    # Change the 'label' widget to a select box.
    label = forms.CharField(widget=forms.Select(choices=CHOICES_LABEL))

    class Meta:
       # This tells django to get attributes from the Quiz model
       model=Quiz
</code>```

Next, in your views.py you might have something like this:

```<code>from django.shortcuts import render_to_response
from forms import *
import my_quiz_model

def displayQuizForm(request, *args, **kwargs):
   if request.method == 'GET':
       # Create an empty Quiz object.
       # Alternately you can run a query to edit an existing object.

       quiz = Quiz()
       form = QuizForm(instance=Quiz)
       # Render the template and pass the form object along to it.
       return render_to_response('form_template.html',{'form': form})

   elif request.method == 'POST' and request.POST.get('action') == 'Save':
       form = Quiz(request.POST, instance=account)
       form.save()
       return HttpResponseRedirect("http://example.com/myapp/confirmsave")
</code>```

Finally your template would look like this:

```<code><html>
  <title>My Quiz Form</title>
  <body>

  <form id="form" method="post" action=".">

   <ul>
    {{ form.as_ul }}
   </ul>

   <input type="submit" name="action" value="Save">
   <input type="submit" name="action" value="Cancel">
  </form>

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

ContentLicense: CC BY-SA 2.5

Title: Django Forms Newbie Question

Body:
Alright, I'm at a loss with the Django Forms, as the documentation just doesn't seem to quite cover what I'm looking for. At least it seems to come to a screeching halt once you get past the most rudimentary of forms. I'm more than willing to take a link to good documentation, or a link to a good book that covers this topic, as an answer. Basically, this is how it breaks down, I have 3 models (quiz, questions, answers). I have 20 questions, with 4 potential answers (multi-choice), per quiz. The numbers can vary, but you get the point.

I need to create a form for these items, much like you'd expect in a multiple choice quiz. However, when I create the form by hand in the templates, rather than using django.forms, I get the following:

invalid literal for int() with base 10: 'test'

So I'm trying to mess with the django.forms, but I guess I'm just not grasping the idea of how to build a proper form out of those. Any help would be greatly appreciated, thanks.

For what it's worth here are the models:

class Quiz(models.Model):
    label = models.CharField(blank=True, max_length=400)
    slug = models.SlugField()

    def __unicode__(self):
        return self.label

class Question(models.Model):
    label = models.CharField(blank=True, max_length=400)
    quiz = models.ForeignKey(Quiz)

    def __unicode__(self):
        return self.label

class Answer(models.Model):
    label = models.CharField(blank=True, max_length=400)
    question = models.ForeignKey(Question)
    correct = models.BooleanField()

    def __unicode__(self):
        return self.label

Body:
First, you create a ModelForm for a given Model. In this example I'm doing it for Quiz but you can rinse and repeat for your other models. For giggles, I'm making the "label" be a Select box with preset choices:

from django.models import BaseModel
from django import forms
from django.forms import ModelForm

CHOICES_LABEL = (
    ('label1', 'Label One'),
    ('label2', 'Label Two')

)

class Quiz(models.Model):
    label = models.CharField(blank=True, max_length=400)
    slug = models.SlugField()

    def __unicode__(self):
        return self.label

class QuizForm(ModelForm):
    # Change the 'label' widget to a select box.
    label = forms.CharField(widget=forms.Select(choices=CHOICES_LABEL))

    class Meta:
       # This tells django to get attributes from the Quiz model
       model=Quiz

Next, in your views.py you might have something like this:

from django.shortcuts import render_to_response
from forms import *
import my_quiz_model

def displayQuizForm(request, *args, **kwargs):
   if request.method == 'GET':
       # Create an empty Quiz object.
       # Alternately you can run a query to edit an existing object.

       quiz = Quiz()
       form = QuizForm(instance=Quiz)
       # Render the template and pass the form object along to it.
       return render_to_response('form_template.html',{'form': form})

   elif request.method == 'POST' and request.POST.get('action') == 'Save':
       form = Quiz(request.POST, instance=account)
       form.save()
       return HttpResponseRedirect("http://example.com/myapp/confirmsave")

Finally your template would look like this:

<html>
  <title>My Quiz Form</title>
  <body>

  <form id="form" method="post" action=".">

   <ul>
    {{ form.as_ul }}
   </ul>

   <input type="submit" name="action" value="Save">
   <input type="submit" name="action" value="Cancel">
  </form>

  </body>
</html>