问:
Angular.js unable to change scope variable value just after a different function call
I'm trying to implement a Refresh button for fetching latest search results from an external index. When I click on the Refresh button the icon is supposed to spin. My plan was to have a scope variable for deciding if the icon should spin or not. For that I'm using a variable called $scope.refreshing

My view

<button class="refresh-button" ng-click="refresh()">

         Refresh
</button>
```
<p><strong>My controller</strong></p>
```      $scope.refreshing ={state: false};
      $scope.refresh = function(){
        $scope.refreshing.state = true;
        $scope.search();
        $scope.refreshing.state = false;
      }
```

The $scope.search() sends an HTTP request to a server and displays the new results. But I'm having the problem such that the $scope.refreshing variable change doesn't happen sequentially such that it becomes false only after calling the search function due to the asynchronous nature. Because of that the icon doesn't spin.

Actual

Expected

Would it be possible to perform this without doing any changes to the search() function.

答:
This is most likely because angular isn't refreshing the digest quickly enough. You can give it a 'nudge' with $timeout (and there are other methods as well). Something like

```<code>  $scope.refreshing ={state: false};
  $scope.refresh = function(){
    $scope.refreshing.state = true;
    $timeout( function() {
       $scope.search();
       $scope.refreshing.state = false;
    }, 100)
  }
</code>```

Of course, you'll need to include $timeout as a dependency in your controller/directive whatever.

Body:
I'm trying to implement a Refresh button for fetching latest search results from an external index. When I click on the Refresh button the icon is supposed to spin. My plan was to have a scope variable for deciding if the icon should spin or not. For that I'm using a variable called $scope.refreshing

My view

<button class="refresh-button" ng-click="refresh()">

         Refresh
</button>

My controller

      $scope.refreshing ={state: false};
      $scope.refresh = function(){
        $scope.refreshing.state = true;
        $scope.search();
        $scope.refreshing.state = false;
      }

The $scope.search() sends an HTTP request to a server and displays the new results. But I'm having the problem such that the $scope.refreshing variable change doesn't happen sequentially such that it becomes false only after calling the search function due to the asynchronous nature. Because of that the icon doesn't spin.

Actual

Expected

Would it be possible to perform this without doing any changes to the search() function.

Body:
This is most likely because angular isn't refreshing the digest quickly enough. You can give it a 'nudge' with $timeout (and there are other methods as well). Something like

  $scope.refreshing ={state: false};
  $scope.refresh = function(){
    $scope.refreshing.state = true;
    $timeout( function() {
       $scope.search();
       $scope.refreshing.state = false;
    }, 100)
  }

Of course, you'll need to include $timeout as a dependency in your controller/directive whatever.


来源: stackexchange

问:
Can't use TorBrowser with Selenium ? (Python Linux)
I'd like to run TorBrowser through selenium.

I've been able to use the tor network through selenium using the tor daemon and a firefox instance.

I'd like to use TorBrowser to be able to run multiple instances using different tor exit relay.
I know it's possible to run multiple TorBrowser instances (without selenium) by specifying the ports we want to use in each TorBrowser bundle by adding this lines to Browser/TorBrowser/Data/Browser/profile.default/user.js :

```<code>user_pref("network.proxy.socks_port", ChangeToTheDesiredPort1);
user_pref("extensions.torlauncher.control_port", ChangeToTheDesiredPort2);
</code>```

Here is the code I used to try and launch TorBrowser through Selenium. I'm trying to do the things step by step so, in this test, I'm using a freshly new TorBrowser archive without the personalized profile :

```<code>#!/usr/bin/python
# -*- coding: UTF-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

profile = FirefoxProfile("tor-browser_en-US/Browser/TorBrowser/Data/Browser/profile.default")
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9050)

options = FirefoxOptions()
options.profile = profile
binary = FirefoxBinary("tor-browser_en-US/Browser/start-tor-browser")

print "0"
driver = webdriver.Firefox(options=options, firefox_binary=binary)
print "1"
driver.get('https://check.torproject.org/')
</code>```

My script gets blocked once I try to instanciate the webdriver.
The output of the script prints 0, never prints 1 and the TorBrowser never tries to connect to https://check.torproject.org/

If I replace

```<code>binary = FirefoxBinary("tor-browser_en-US/Browser/start-tor-browser")
</code>```

by

```<code>binary = FirefoxBinary("tor-browser_en-US/Browser/firefox")
</code>```

the script is not blocking anymore and TorBrowser tries to contact https://check.torproject.org/ but the TorBrowser never connects to the tor network, resulting in the following error :

selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=proxyConnectFailure&u=https://check.torproject.org/&c=UTF-8&d=Firefox is configured to use a proxy server that is refusing connections.

Some info about my config (64 bits):

geckodriver 0.30.0

TorBrowser 11.0.4

Python 2.7.17

Ubuntu 18.04.1

I've made my example script as simple as possible but I've tested a lot of things in the last 2 days and found nothing relevant.

Thank in advance for your answers.

答:
I finally solved my problem (tested on a VM with Ubuntu 20.04 to be able to install selenium4).
I've been able to launch multiple TorBrowser instances with different exit nodes using tbselenium (requires selenium4).
https://github.com/webfp/tor-browser-selenium

Here is a sample code

```<code>from stem.control import Controller
from tbselenium.tbdriver import TorBrowserDriver
import tbselenium.common as cm
from tbselenium.utils import launch_tbb_tor_with_stem
from selenium.webdriver.common.utils import free_port
import tempfile
from os.path import join
import time

tbb_dir = "PathToTorBrowserBundle"
gecko = "PathToGeckodriver"

socks_port = free_port()
control_port = free_port()
tor_data_dir = tempfile.mkdtemp()
torrc = {'ControlPort': str(control_port),
        'SOCKSPort': str(socks_port),
        'DataDirectory': tor_data_dir}
tor_binary = join(tbb_dir, cm.DEFAULT_TOR_BINARY_PATH)
tor_process = launch_tbb_tor_with_stem(tbb_path=tbb_dir, torrc=torrc, tor_binary=tor_binary)

Controller.from_port(port=control_port).authenticate()
driver = TorBrowserDriver(tbb_dir, socks_port=socks_port, control_port=control_port, tor_cfg=cm.USE_STEM, executable_path=gecko)
driver.load_url("https://check.torproject.org")
time.sleep(5000)
tor_process.kill()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to run TorBrowser through selenium.

I've been able to use the tor network through selenium using the tor daemon and a firefox instance.

I'd like to use TorBrowser to be able to run multiple instances using different tor exit relay.
I know it's possible to run multiple TorBrowser instances (without selenium) by specifying the ports we want to use in each TorBrowser bundle by adding this lines to Browser/TorBrowser/Data/Browser/profile.default/user.js :

user_pref("network.proxy.socks_port", ChangeToTheDesiredPort1);
user_pref("extensions.torlauncher.control_port", ChangeToTheDesiredPort2);

Here is the code I used to try and launch TorBrowser through Selenium. I'm trying to do the things step by step so, in this test, I'm using a freshly new TorBrowser archive without the personalized profile :

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile

profile = FirefoxProfile("tor-browser_en-US/Browser/TorBrowser/Data/Browser/profile.default")
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9050)

options = FirefoxOptions()
options.profile = profile
binary = FirefoxBinary("tor-browser_en-US/Browser/start-tor-browser")

print "0"
driver = webdriver.Firefox(options=options, firefox_binary=binary)
print "1"
driver.get('https://check.torproject.org/')

My script gets blocked once I try to instanciate the webdriver.
The output of the script prints 0, never prints 1 and the TorBrowser never tries to connect to https://check.torproject.org/

If I replace

binary = FirefoxBinary("tor-browser_en-US/Browser/start-tor-browser")

by

binary = FirefoxBinary("tor-browser_en-US/Browser/firefox")

the script is not blocking anymore and TorBrowser tries to contact https://check.torproject.org/ but the TorBrowser never connects to the tor network, resulting in the following error :

selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=proxyConnectFailure&u=https://check.torproject.org/&c=UTF-8&d=Firefox is configured to use a proxy server that is refusing connections.

Some info about my config (64 bits):

geckodriver 0.30.0

TorBrowser 11.0.4

Python 2.7.17

Ubuntu 18.04.1

I've made my example script as simple as possible but I've tested a lot of things in the last 2 days and found nothing relevant.

Thank in advance for your answers.

Body:
I finally solved my problem (tested on a VM with Ubuntu 20.04 to be able to install selenium4).
I've been able to launch multiple TorBrowser instances with different exit nodes using tbselenium (requires selenium4).
https://github.com/webfp/tor-browser-selenium

Here is a sample code

from stem.control import Controller
from tbselenium.tbdriver import TorBrowserDriver
import tbselenium.common as cm
from tbselenium.utils import launch_tbb_tor_with_stem
from selenium.webdriver.common.utils import free_port
import tempfile
from os.path import join
import time

tbb_dir = "PathToTorBrowserBundle"
gecko = "PathToGeckodriver"

socks_port = free_port()
control_port = free_port()
tor_data_dir = tempfile.mkdtemp()
torrc = {'ControlPort': str(control_port),
        'SOCKSPort': str(socks_port),
        'DataDirectory': tor_data_dir}
tor_binary = join(tbb_dir, cm.DEFAULT_TOR_BINARY_PATH)
tor_process = launch_tbb_tor_with_stem(tbb_path=tbb_dir, torrc=torrc, tor_binary=tor_binary)

Controller.from_port(port=control_port).authenticate()
driver = TorBrowserDriver(tbb_dir, socks_port=socks_port, control_port=control_port, tor_cfg=cm.USE_STEM, executable_path=gecko)
driver.load_url("https://check.torproject.org")
time.sleep(5000)
tor_process.kill()


问:
A href pointed to nowhere added # to url
I have a href which pointed to #

```<code><a href="#" id="bla" >Bla<a>
</code>```

I have onclick function which displaying popup on click on that a href.

```<code>function doingClick()
{
   //display popup
   return false;
}
</code>```

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

答:
To avoid this try adding return false;

```<code><a href="#" onclick="doingClick(); return false;">Link</a>
</code>```

You could also use void(0)

```<code><a href="javascript:void(0)" onclick="doingClick();">Link</a>
</code>```

There's a popular question related to this (small religious war!) at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

ContentLicense: CC BY-SA 3.0

Body:
I have a href which pointed to #

Bla

I have onclick function which displaying popup on click on that a href.

function doingClick()
{
   //display popup
   return false;
}

But after click symbol # every time added to the url in browser.

So for example if url was like that before I click on my link http://mywebsite.com

But after click on a href the url looking like that: http://mywebsite.com#

Is there any way to avoid such behavior?

Body:
To avoid this try adding return false;

<a href="#" onclick="doingClick(); return false;">Link</a>

You could also use void(0)

<a href="javascript:void(0)" onclick="doingClick();">Link</a>

There's a popular question related to this (small religious war!) at Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?


问:
How to understand the requirement of `std::lower_bound`?
As per the document about std::lower_bound, which says that:

The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.

I have a little difficulty to fully understand it.

1.What's element < value? It seems that element (or value) is never mentioned before this paragraph in the aforementioned document. Does the said element mean the elements before the current element, and the said value means the value of the current element?

UPDATED:

2.Since whether a specific sequence is valid(i.e. suits the requirement) or not depends the value, the requirement for a specific sequence could not be always be guaranteed when the value is different. I think it's meaningless to define such a requirement. It's seems that a fully sorted seuqence is more reliable and practical.

答:
From cppreference

Returns an iterator pointing to the first element in the range [first,
last) that is not less than (i.e. greater or equal to) value, or last
if no such element is found.

The range [first, last) must be partitioned with respect to the
expression element < value or comp(element, value), i.e., all elements
for which the expression is true must precede all elements for which
the expression is false. A fully-sorted range meets this criterion.

From your question:

What's element < value? It seems that element (or value) is never
mentioned before this paragraph in the aforementioned document. Does
the said element mean the elements before the current element, and the
said value means the value of the current element?

value and comp are mentioned in the function signatures at the beginning of the page. value is the argument with which you call std::lower_bound, and comp an optional comparison function; shouldn't a comparison function be provided, < would be used instead.

element refers to each element in the range [first, last).

So, what std::lower_bound does is to compare value to the elements in the range until it finds the first one that is not "less than" (through < or comp) value.

The requirement for std::lower_bound to work is that the input range is partitioned in such a way that all the elements that are "less than"  value are placed before the rest; that requirement is met, for example, if the range is fully sorted.

(As @Passerby mentions in the comments below, std::lower_bound won't need to compare against all the elements that are "less than" value, due to the partitioned range requirement, but that is an implementation detail.)


问:
Error when trying to find an element using SELENIUM
Hopefully someone can help me out here.

My goal is to successfully connect to this website using Python (Selenium + Chromedriver) and successfully search for an address in the search bar. Im struggling to manage to find the actual search bar itself using Selenium. The HTML code doesn't have an ID or NAME to distinguish it by, all it has is a class and when i search for the class, i get an error saying it cannot be found.

Hopefully this is an easy fix and im just being silly. Thanks a lot.

P.S First post - please drop some hints on what to change next time :)

CODE

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://creeper.banano.cc/")
search = driver.find_element_by_class_name("ValidatedSearch form-control form-control-lg ")
```
<p>ERROR CODE</p>
```NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ValidatedSearch form-control form-control-lg "}
```

Python Code + HTML of Website

答:
ValidatedSearch form-control form-control-lg

is what are referred to as multiple class names.

In order to find the element we use css selector.

```<code>driver.find_element(By.CSS_SELECTOR,".ValidatedSearch.form-control.form-control-lg")
</code>```

Also don't use driver.find_element_by since they are depreciated instead import By and use that.

Body:
Hopefully someone can help me out here.

My goal is to successfully connect to this website using Python (Selenium + Chromedriver) and successfully search for an address in the search bar. Im struggling to manage to find the actual search bar itself using Selenium. The HTML code doesn't have an ID or NAME to distinguish it by, all it has is a class and when i search for the class, i get an error saying it cannot be found.

Hopefully this is an easy fix and im just being silly. Thanks a lot.

P.S First post - please drop some hints on what to change next time :)

CODE

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

driver.get("https://creeper.banano.cc/")
search = driver.find_element_by_class_name("ValidatedSearch form-control form-control-lg ")

ERROR CODE

NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":".ValidatedSearch form-control form-control-lg "}

Python Code + HTML of Website

Body:
ValidatedSearch form-control form-control-lg

is what are referred to as multiple class names.

In order to find the element we use css selector.

driver.find_element(By.CSS_SELECTOR,".ValidatedSearch.form-control.form-control-lg")

Also don't use driver.find_element_by since they are depreciated instead import By and use that.


问:
How to strip certain characters from a string in python
I am trying to strip certain characters from a string. The string I have is -

```<code>test_list = ['INFO:      196ns ### Starting ABC Test ###\n', 'INFO:     310ns ### Starting write_def_test ###\n', 'INFO:     752ns ### Starting write_55s_test ###\n', 'INFO:    152ns ### Starting rands_test ###\n', 'INFO:    237ns ### Starting dog_wffs_test ###\n']
</code>```

The code I have is -

```<code>test_list_1 = []
for i in test_list:
    m = i.strip("INFO:      ")
    m = m.strip("###")
    test_list_1.append(m)
print(test_list_1)
</code>```

The output I am looking for is -

```<code>['ABC Test', 'write_def_test', 'write_55s_test', 'rands_test', 'dog_wffs_test']
</code>```

How can I get it?

答:
You're better off using regex here, i.e.:

```<code>import re

out = re.findall('Starting ([^#]+)', '|'.join(test_list))
</code>```

Body:
I am trying to strip certain characters from a string. The string I have is -

test_list = ['INFO:      196ns ### Starting ABC Test ###\n', 'INFO:     310ns ### Starting write_def_test ###\n', 'INFO:     752ns ### Starting write_55s_test ###\n', 'INFO:    152ns ### Starting rands_test ###\n', 'INFO:    237ns ### Starting dog_wffs_test ###\n']

The code I have is -

test_list_1 = []
for i in test_list:
    m = i.strip("INFO:      ")
    m = m.strip("###")
    test_list_1.append(m)
print(test_list_1)

The output I am looking for is -

['ABC Test', 'write_def_test', 'write_55s_test', 'rands_test', 'dog_wffs_test']

How can I get it?

Body:
You're better off using regex here, i.e.:

import re

out = re.findall('Starting ([^#]+)', '|'.join(test_list))


问:
How to have an anchor tag inside another
I have read other questions (1, 2) asked on this site and how it is said that it is not possible to have an anchor inside another anchor, however I recently saw a website that is achieving this and I want to know how it's done.

You can see in the following website link where there are cards and each card is a link (whole thing wrapped in an anchor tag), but there are also other links inside the card.

https://opensea.io/collection/clonex

Looking at the HTML, you can see that there are actually two anchor tags (one nested inside the other). So this is not some JavaScript hack.

When I try the same HTML, the browser destructures my anchor tags. Anyone knows how this website manages to do this?

答:
According to https://css-tricks.com/nested-links/, you can possibly do that by just simply putting an anchor within an anchor by doing what is said

#one {
  background-color: yellow;
}

#two {
  background-color: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
  Some text...
 <!--You can add a <br> tag here if you want-->

    Some more text...

<!--The CSS is not necessary but is used to show this example--></code>```

In the snippet above you can see it being done Notice that when you click on the links they are separate.

If it still does not work check your devtools if you do not find a solution you can search the web or browse youtube for an answer that is most clear to you.

Body:
According to https://css-tricks.com/nested-links/, you can possibly do that by just simply putting an anchor within an anchor by doing what is said

#one {
  background-color: yellow;
}

#two {
  background-color: lightgreen;
}

<a id="one" href="#linkone">
  Some text...
 <!--You can add a <br> tag here if you want-->
  <a id="two" href="#linktwo">
    Some more text...
  </a>
</a>

<!--The CSS is not necessary but is used to show this example-->

In the snippet above you can see it being done Notice that when you click on the links they are separate.

If it still does not work check your devtools if you do not find a solution you can search the web or browse youtube for an answer that is most clear to you.


问:
Using Go to make a POST request using a JSON file
I am very new to Go and searched around for this question but did not find anything, so I apologize if this is a duplicate that I missed.

I need to send a POST request using Go and have the body come from a JSON file. Below is a modified version of the code from https://golangtutorial.dev/tips/http-post-json-go/ that I am using as a starting point.

I am thinking that I can just substitute the jsonData var with a JSON file that I pull in but I just wanted to know if this is the correct approach and how to best go about doing this. Thanks!

```<code>package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    httpposturl := "https://reqres.in/api/users"

    // I think this is the block I need to alter?:
    var jsonData = []byte(`{
        "name": "morpheus",
        "job": "leader"
    }`)

    request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
    request.Header.Set("Content-Type", "application/json; charset=UTF-8")

    client := &http.Client{}
    response, error := client.Do(request)
    if error != nil {
        panic(error)
    }
    defer response.Body.Close()

    fmt.Println("response Status:", response.Status)
}
</code>```

答:
To post a file, use the opened file as the HTTP request body:</p>
```<code>f, err := os.Open("file.json")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

httpposturl := "https://reqres.in/api/users"
request, err := http.NewRequest("POST", httpposturl, f)
if err != nil {
    log.Fatal(err)
}
request.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := http.DefaultClient.Do(request)
if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()

fmt.Println("response Status:", response.Status)
</code>```

Body:
I am very new to Go and searched around for this question but did not find anything, so I apologize if this is a duplicate that I missed.

I need to send a POST request using Go and have the body come from a JSON file. Below is a modified version of the code from https://golangtutorial.dev/tips/http-post-json-go/ that I am using as a starting point.

I am thinking that I can just substitute the jsonData var with a JSON file that I pull in but I just wanted to know if this is the correct approach and how to best go about doing this. Thanks!

package main

import (
    "bytes"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    httpposturl := "https://reqres.in/api/users"

    // I think this is the block I need to alter?:
    var jsonData = []byte(`{
        "name": "morpheus",
        "job": "leader"
    }`)

    request, error := http.NewRequest("POST", httpposturl, bytes.NewBuffer(jsonData))
    request.Header.Set("Content-Type", "application/json; charset=UTF-8")

    client := &http.Client{}
    response, error := client.Do(request)
    if error != nil {
        panic(error)
    }
    defer response.Body.Close()

    fmt.Println("response Status:", response.Status)
}

Body:
To post a file, use the opened file as the HTTP request body:

f, err := os.Open("file.json")
if err != nil {
    log.Fatal(err)
}
defer f.Close()

httpposturl := "https://reqres.in/api/users"
request, err := http.NewRequest("POST", httpposturl, f)
if err != nil {
    log.Fatal(err)
}
request.Header.Set("Content-Type", "application/json; charset=UTF-8")

response, err := http.DefaultClient.Do(request)
if err != nil {
    log.Fatal(err)
}
defer response.Body.Close()

fmt.Println("response Status:", response.Status)


答:
```<code><a href="#" id="bla" onclick="return doingClick()">Link</a>
</code>```

Do not forget to return the return of your function. Otherwise you will just call it without suspending the subsequent events.

Title: A href pointed to nowhere added # to url

Body:
<a href="#" id="bla" onclick="return doingClick()">Link</a>

Do not forget to return the return of your function. Otherwise you will just call it without suspending the subsequent events.


问:
How to tell distutils to use gcc?
I want to wrap a test project containing C++ and OpenMP code with Cython, and build it with distutils via a setup.py file. The content of my file looks like this:

```<code>from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext

modules = [Extension("Interface",
                     ["Interface.pyx", "Parallel.cpp"],
                     language = "c++",
                     extra_compile_args=["-fopenmp"],
                     extra_link_args=["-fopenmp"])]

for e in modules:
    e.cython_directives = {"embedsignature" : True}

setup(name="Interface",
     cmdclass={"build_ext": build_ext},
     ext_modules=modules)
</code>```

The -fopenmp flag is used with gcc to compile and link against OpenMP. However, if I just invoke

```<code>cls ~/workspace/CythonOpenMP/src $ python3 setup.py build
</code>```

this flag is not recognized, because the compiler is clang:

```<code>running build
running build_ext
skipping 'Interface.cpp' Cython extension (up-to-date)
building 'Interface' extension
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Interface.cpp -o build/temp.macosx-10.8-x86_64-3.3/Interface.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Parallel.cpp -o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
Parallel.cpp:24:10: warning: unknown pragma ignored [-Wunknown-pragmas]
        #pragma omp parallel for
                ^
1 warning generated.
c++ -bundle -undefined dynamic_lookup -L/usr/local/lib -L/usr/local/opt/sqlite/lib build/temp.macosx-10.8-x86_64-3.3/Interface.o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -o build/lib.macosx-10.8-x86_64-3.3/Interface.so -fopenmp
ld: library not found for -lgomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'c++' failed with exit status 1
</code>```

I've unsucessfully tried to specify gcc:

```<code>cls ~/workspace/CythonOpenMP/src $ python3 setup.py build --compiler=g++-4.7
running build
running build_ext
error: don't know how to compile C/C++ code on platform 'posix' with 'g++-4.7' compiler
</code>```

How can I tell distutils to use gcc?

答:
On linux while using distutils.ccompiler do
os.environ('CC')='gcc' and then call distutils.sysconfig.customize_compiler(compiler)

It will do the job.

Title: How to tell distutils to use gcc?

Body:
I want to wrap a test project containing C++ and OpenMP code with Cython, and build it with distutils via a setup.py file. The content of my file looks like this:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext

modules = [Extension("Interface",
                     ["Interface.pyx", "Parallel.cpp"],
                     language = "c++",
                     extra_compile_args=["-fopenmp"],
                     extra_link_args=["-fopenmp"])]

for e in modules:
    e.cython_directives = {"embedsignature" : True}

setup(name="Interface",
     cmdclass={"build_ext": build_ext},
     ext_modules=modules)

The -fopenmp flag is used with gcc to compile and link against OpenMP. However, if I just invoke

cls ~/workspace/CythonOpenMP/src $ python3 setup.py build

this flag is not recognized, because the compiler is clang:

running build
running build_ext
skipping 'Interface.cpp' Cython extension (up-to-date)
building 'Interface' extension
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Interface.cpp -o build/temp.macosx-10.8-x86_64-3.3/Interface.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
cc -Wno-unused-result -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python3/3.3.0/Frameworks/Python.framework/Versions/3.3/include/python3.3m -c Parallel.cpp -o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -fopenmp
clang: warning: argument unused during compilation: '-fopenmp'
Parallel.cpp:24:10: warning: unknown pragma ignored [-Wunknown-pragmas]
        #pragma omp parallel for
                ^
1 warning generated.
c++ -bundle -undefined dynamic_lookup -L/usr/local/lib -L/usr/local/opt/sqlite/lib build/temp.macosx-10.8-x86_64-3.3/Interface.o build/temp.macosx-10.8-x86_64-3.3/Parallel.o -o build/lib.macosx-10.8-x86_64-3.3/Interface.so -fopenmp
ld: library not found for -lgomp
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'c++' failed with exit status 1

I've unsucessfully tried to specify gcc:

cls ~/workspace/CythonOpenMP/src $ python3 setup.py build --compiler=g++-4.7
running build
running build_ext
error: don't know how to compile C/C++ code on platform 'posix' with 'g++-4.7' compiler

How can I tell distutils to use gcc?


问:
How do I write a Java Application that reads docker container logs
I have a Docker container running a game server on another computer, and on this system I have a simple Java application that I wish to simply take the "docker logs -f " and output that into JAVA APPLICATIONS system console.

Is there a simple, repeatable solution to this issue?

答:
One solution I've found is to connect to the hosting machine via SSH with the JSch library, this lets me execute the command I wish to execute talking to the docker container and gives me a ByteArrayOutputStream to work with, perhaps not the most ideal but is functional

Edit: I've updated this to be more appropriate to my needs, appears to be working thus far. Although I'm having threading issues. Kinks to work out.

public static void main(String[] args) {
        Connection projectZomboidServer = new Connection(USER_NAME, PASSWORD, MACHINE_HOST, MACHINE_PORT);
        ThreadController threadController = new ThreadController();
        String dockerCommand = "docker logs -f mason-project-zomboid-1";

        Runnable sshConnectionRunnable = () -> {
            try {
                executeDockerCommand( projectZomboidServer, dockerCommand, threadController);
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
        Thread sshConnectionThread = new Thread(sshConnectionRunnable);
        sshConnectionThread.start();

}

public static void executeDockerCommand(Connection connection, String command, ThreadController controller) throws Exception {

        String username = connection.getUsername();
        String host = connection.getMachineHost();
        int port = connection.getMachinePort();
        String password = connection.getPassword();

        Session session = null;
        ChannelExec channel = null;

        try {
            session = new JSch().getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
            channel.setOutputStream(responseStream);
            channel.connect();
            String cachedResponseStream = responseStream.toString();
            String output = "";
            while (channel.isConnected() && controller.isContThread()) {
                Thread.sleep(100);
                if (!cachedResponseStream.equalsIgnoreCase(responseStream.toString())) {
                    output = cachedResponseStream = responseStream.toString();
                    if (output.length() > OUTPUT_CHAR_LIMIT) {
                        output = cachedResponseStream.substring(cachedResponseStream.length() - OUTPUT_CHAR_LIMIT);
                    }
                    controller.setOutput(output);
                }
            }
        } finally {
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }
}
```


问:
How do I reduce the nex lines of Ruby code?
```<code>    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end
</code>```

So I want to reduce this case when is there another way of implementing this?

答:
One possibility would be to have an array of message names to send based on the action input which is used as an index, and by determining which controller to send to by dividing by 5. Inputs from 1 to 4 will yield 0, while 5 to 8 will yield 1.

```<code>def route_action
  actions = [:add, :list, :edit, :delete]

  case action
    when 1..8
      controller = action / 5 < 1 ? @meals_controller : @customers_controller
      msg = actions[(action - 1) % 4]
      controller.send(msg)
    when 0
      stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
  end
end
</code>```

Body:
    def route_action(action)
    case action
    when 1 then @meals_controller.add
    when 2 then @meals_controller.list
    when 3 then @meals_controller.edit
    when 4 then @meals_controller.delete
    when 5 then @customers_controller.add
    when 6 then @customers_controller.list
    when 7 then @customers_controller.edit
    when 8 then @customers_controller.delete
    when 0 then stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
    end
  end

So I want to reduce this case when is there another way of implementing this?

Body:
One possibility would be to have an array of message names to send based on the action input which is used as an index, and by determining which controller to send to by dividing by 5. Inputs from 1 to 4 will yield 0, while 5 to 8 will yield 1.

def route_action
  actions = [:add, :list, :edit, :delete]

  case action
    when 1..8
      controller = action / 5 < 1 ? @meals_controller : @customers_controller
      msg = actions[(action - 1) % 4]
      controller.send(msg)
    when 0
      stop
    else
      puts "Please press 1, 2, 3, 4, 5, 6, 7, 8 or 0"
  end
end


问:
Find each instance and replace with unique value in string
I have some text in a string as below:

```<code>{121:SOMETHING1}}{4:
.
.
.
{121:SOMETHING2}}{4:
.
.
.
{121:SOMETHING3}}{4:
</code>```

I want to sequentially find and replace the value between 121: and the first }. I can successfully do this using the following code in C#

```<code>       var rx = @"121:(?<value>[\s\S]+?)}";
       string temp = tag121;

       string stringToChange = //as above
       for (var m = Regex.Match(stringToChange , rx); m.Success; m = m.NextMatch())
       {
           temp = generateUniqueValue()

           stringToChange= Regex.Replace(stringToChange, m.Value, temp);

        }
</code>```

However, if instead of having different values between 121: and } I have exactly the same value for all the tags e.g instead of SOMETHING1, SOMETHING 2 etc, I just have SOMETHING for all the lines, then this code does not work. It ends up setting just one value for all the lines instead of unique values for each.

答:
When all the lines in the string are all {121:SOMETHING}}{4:, the first cycle of the loop already replaced every SOMETHING in the string to first call result of generateUniqueValue(). You can see that happening by printing out stringToChange in the end of every for-loop cycle. (A good way to debug when working around regex, too)

You need to consider a new approach or look at what you trying to achieve again:

Is it acceptable that there are at least 2 lines with same value in the input?

Should lines with same values be replaced into different UniqueValue?

If answers to both questions are yes, one approach I suggest is replace line by line. Not optimal I guess though...

Split the string by lines. String.Split("\\n") Maybe?

Foreach through that split string array.

Find part to replace by regex {121:([^}]+)} - Group 1 of the match is the string you need to replace.

After foreach loop, concat the array into one single string again.

Reference:

Match.Groups

Body:
I have some text in a string as below:

{121:SOMETHING1}}{4:
.
.
.
{121:SOMETHING2}}{4:
.
.
.
{121:SOMETHING3}}{4:

I want to sequentially find and replace the value between 121: and the first }. I can successfully do this using the following code in C#

       var rx = @"121:(?<value>[\s\S]+?)}";
       string temp = tag121;

       string stringToChange = //as above
       for (var m = Regex.Match(stringToChange , rx); m.Success; m = m.NextMatch())
       {
           temp = generateUniqueValue()

           stringToChange= Regex.Replace(stringToChange, m.Value, temp);

        }

However, if instead of having different values between 121: and } I have exactly the same value for all the tags e.g instead of SOMETHING1, SOMETHING 2 etc, I just have SOMETHING for all the lines, then this code does not work. It ends up setting just one value for all the lines instead of unique values for each.


问:
Why does Html5 video player area react only on mouse click, but not on finger touch?
I am trying to make it so that I can use my finger (touch) anywhere on a video player to start and stop it.

However, I can only start and stop the video if I press the audio controls with the finger:

Alternatively, I can click anywhere on the videoplayer with the mouse. This mouse click will start or stop the video.

I don't know if the problem is that a finger touch (unlike a mouse click) does not raise a certain event or if touching the video is generally not starting / stopping it, and I need a function for that.

Here is an example that I found. However, it's not working: When I click the video with the mouse, it shortly stops, then starts right again.

Thank you for any hint on what might be going on here and how to fix it.

```<code><html>
<head><meta name="viewport" content="width=device-width">
</head>
<body>

<video onclick="playPause()" id="video_player" controls="controls" poster="">
    <source  id="video_mp4" src="file:///C:/Users/Kommunikation/Desktop/affen.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>

<script>
var myVideo = document.getElementById("video_player");
function playPause() {
    if (myVideo.paused)
        myVideo.play();
    else
        myVideo.pause();
}
</script>

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

答:
I got it:

I need to react on the ontouchstart (or ontouchend):

```<code><html>
<head><meta name="viewport" content="width=device-width">
</head>
<body>

<video ontouchstart="playPause()" id="video1" controls="controls" poster="">
    <source  id="somevideoID" src="file:///C:/Users/Kommunikation/Desktop/affen.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>

<script>
function playPause(e) {

  var myVideo = document.getElementById("video1");
  if (myVideo.paused) myVideo.play();
  else myVideo.pause();
}
</script>

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

Body:
I am trying to make it so that I can use my finger (touch) anywhere on a video player to start and stop it.

However, I can only start and stop the video if I press the audio controls with the finger:

Alternatively, I can click anywhere on the videoplayer with the mouse. This mouse click will start or stop the video.

I don't know if the problem is that a finger touch (unlike a mouse click) does not raise a certain event or if touching the video is generally not starting / stopping it, and I need a function for that.

Here is an example that I found. However, it's not working: When I click the video with the mouse, it shortly stops, then starts right again.

Thank you for any hint on what might be going on here and how to fix it.

<meta name="viewport" content="width=device-width">

<video onclick="playPause()" id="video_player" controls="controls" poster="">
    <source  id="video_mp4" src="file:///C:/Users/Kommunikation/Desktop/affen.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>

Body:
I got it:

I need to react on the ontouchstart (or ontouchend):

<html>
<head><meta name="viewport" content="width=device-width">
</head>
<body>

<video ontouchstart="playPause()" id="video1" controls="controls" poster="">
    <source  id="somevideoID" src="file:///C:/Users/Kommunikation/Desktop/affen.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' />
</video>

<script>
function playPause(e) {

  var myVideo = document.getElementById("video1");
  if (myVideo.paused) myVideo.play();
  else myVideo.pause();
}
</script>

</body>
</html>


问:
Initializing the Date Picker with Date Other Than Today
I need help with dates. How do you initialize the DatePicker with a stored date? Say, for example, that the user entered an entry with a date. He then determines the date is wrong and would like to change the date. But currently the DatePicker in this code will always default to today's date instead of the stored date.

The state parameter startDate can't be initialized with a stored date above the body. It appears that I need to set startDate in the body.

```<code>import SwiftUI
import Combine

struct GetDate: View {

    @ObservedObject var userData : UserData = UserData()
    @State private var startDate = Date()

    var body: some View {

        //let startDate = userData.startDate

        VStack (alignment: .leading) {

            Form {

                Text("startdate 1 = \(startDate)")

                // enter start date
                Section(header: Text("Enter Start Date")) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .resizable()
                            .foregroundColor(Color(.systemRed))
                            .frame(width: 35, height: 35)

                        Spacer()

                        DatePicker("", selection: $startDate, in: ...Date(), displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                    }
                }

                Button ( action: {
                    userData.saveDates(startDate: startDate)
                }) {

                    HStack {
                        Spacer()
                        Text("Save Dates?")
                        Spacer()
                    }
                }
            }
            .font(.body)
            .navigationBarTitle("Get Date", displayMode: .inline)
        }
    }
}

class UserData:  ObservableObject {

    @Published var startDate: Date = Date()  {
        didSet {
            UserDefaults.standard.set(startDate, forKey: "startDate")  // save
        }
    }

    init() {
        // save / retrieve trip dates
        if let sdate = UserDefaults.standard.object(forKey: "startDate") as? Date {
            startDate = sdate
            print("startDate 2 = \(startDate)")
        } else {
            UserDefaults.standard.set(Date(), forKey: "startDate")
        }
    }

    func saveDates(startDate: Date) -> () {

        self.startDate = startDate
        UserDefaults.standard.set(self.startDate, forKey: "startDate")

        print("startDate 3 = \(self.startDate)")
    }
}
</code>```

答:
Use @AppStorage property wrapper:

struct GetDate: View {
  @AppStorage("startDate") var startDate = Date()
  @State private var selectedDate = Date()

  var body: some View {
    VStack (alignment: .leading) {
      Form {
        Text("startdate 1 = \(startDate)")
        Section(header: Text("Enter Start Date")) {
          HStack {
            Image(systemName: "calendar.badge.clock")
              .resizable()
              .foregroundColor(Color(.systemRed))
              .frame(width: 35, height: 35)
            Spacer()
            DatePicker("", selection: $selectedDate, in: ...Date(), displayedComponents: .date)
              .datePickerStyle(CompactDatePickerStyle())
          }
        }

        Button ( action: {
          startDate = selectedDate // save
        }) {
          HStack {
            Spacer()
            Text("Save Dates?")
            Spacer()
          }
        }
      }
      .font(.body)
      .navigationBarTitle("Get Date", displayMode: .inline)
    }
    .onAppear {
      selectedDate = startDate
    }
  }
}

// Support @AppStorage for `Date` type.
extension Date: RawRepresentable {
  private static let formatter = ISO8601DateFormatter()

  public var rawValue: String {
    Date.formatter.string(from: self)
  }

  public init?(rawValue: String) {
    self = Date.formatter.date(from: rawValue) ?? Date()
  }
}
```

Body:
I need help with dates. How do you initialize the DatePicker with a stored date? Say, for example, that the user entered an entry with a date. He then determines the date is wrong and would like to change the date. But currently the DatePicker in this code will always default to today's date instead of the stored date.

The state parameter startDate can't be initialized with a stored date above the body. It appears that I need to set startDate in the body.

import SwiftUI
import Combine

struct GetDate: View {

    @ObservedObject var userData : UserData = UserData()
    @State private var startDate = Date()

    var body: some View {

        //let startDate = userData.startDate

        VStack (alignment: .leading) {

            Form {

                Text("startdate 1 = \(startDate)")

                // enter start date
                Section(header: Text("Enter Start Date")) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .resizable()
                            .foregroundColor(Color(.systemRed))
                            .frame(width: 35, height: 35)

                        Spacer()

                        DatePicker("", selection: $startDate, in: ...Date(), displayedComponents: .date)
                            .datePickerStyle(CompactDatePickerStyle())
                    }
                }

                Button ( action: {
                    userData.saveDates(startDate: startDate)
                }) {

                    HStack {
                        Spacer()
                        Text("Save Dates?")
                        Spacer()
                    }
                }
            }
            .font(.body)
            .navigationBarTitle("Get Date", displayMode: .inline)
        }
    }
}

class UserData:  ObservableObject {

    @Published var startDate: Date = Date()  {
        didSet {
            UserDefaults.standard.set(startDate, forKey: "startDate")  // save
        }
    }

    init() {
        // save / retrieve trip dates
        if let sdate = UserDefaults.standard.object(forKey: "startDate") as? Date {
            startDate = sdate
            print("startDate 2 = \(startDate)")
        } else {
            UserDefaults.standard.set(Date(), forKey: "startDate")
        }
    }

    func saveDates(startDate: Date) -> () {

        self.startDate = startDate
        UserDefaults.standard.set(self.startDate, forKey: "startDate")

        print("startDate 3 = \(self.startDate)")
    }
}


答:
What's element < value

value is the parameter to lower_bound, see at the beginning of that page:

template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt
first, ForwardIt last, const T& value );

The value in question is mentioned right here, the last parameter to the template. And element, references to some element and every element in the sequence.

This is rather a terse way to define the following: take every element in the sequence, one element at a time. When you do that, all elements for which the expression element < value returns true must appear in the sequence before all other elements, for which the same expression is false. It is explicitly intentional for the requirements to be defined in this manner, here's the explanation:

For example, if value is 4, and we're talking about natural integers, here's one such sequence:

1, 2, 3, 4, 5, 6
```
<p>Here, all the elements for which this expression is true (1, 2, and 3), appear before all the elements for which this expression is false (4, 5, and 6).</p>
<p>The following sequence is also a valid sequence, in this case:</p>
<pre class="lang-none prettyprint-override"><code>3, 2, 1, 6, 5, 4
</code>```

Here, same thing: 3, 2, and 1, for which the expression element < 4 is true, appears before value 4, 5 and 6 for which the expression element < 4 would be false. So, yes, this would also be a valid sequence for a call to lower_bound for the value of 4.

The following sequence will NOT be a valid sequence for this specific case of using std::lower_bound:

1, 2, 4, 3, 5, 6
```

And as far as why is this lower_bound requirement specified in such an strange manner, well, that would be a different question. But this is what it means.

Title: How to understand the requirement of `std::lower_bound`?

Body:
As per the document about std::lower_bound, which says that:

The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.

I have a little difficulty to fully understand it.

1.What's element < value? It seems that element (or value) is never mentioned before this paragraph in the aforementioned document. Does the said element mean the elements before the current element, and the said value means the value of the current element?

UPDATED:

2.Since whether a specific sequence is valid(i.e. suits the requirement) or not depends the value, the requirement for a specific sequence could not be always be guaranteed when the value is different. I think it's meaningless to define such a requirement. It's seems that a fully sorted seuqence is more reliable and practical.

Body:
What's element < value

value is the parameter to lower_bound, see at the beginning of that page:

template< class ForwardIt, class T > ForwardIt lower_bound( ForwardIt
first, ForwardIt last, const T& value );

The value in question is mentioned right here, the last parameter to the template. And element, references to some element and every element in the sequence.

This is rather a terse way to define the following: take every element in the sequence, one element at a time. When you do that, all elements for which the expression element < value returns true must appear in the sequence before all other elements, for which the same expression is false. It is explicitly intentional for the requirements to be defined in this manner, here's the explanation:

For example, if value is 4, and we're talking about natural integers, here's one such sequence:

1, 2, 3, 4, 5, 6

Here, all the elements for which this expression is true (1, 2, and 3), appear before all the elements for which this expression is false (4, 5, and 6).

The following sequence is also a valid sequence, in this case:

3, 2, 1, 6, 5, 4

Here, same thing: 3, 2, and 1, for which the expression element < 4 is true, appears before value 4, 5 and 6 for which the expression element < 4 would be false. So, yes, this would also be a valid sequence for a call to lower_bound for the value of 4.

The following sequence will NOT be a valid sequence for this specific case of using std::lower_bound:

1, 2, 4, 3, 5, 6

And as far as why is this lower_bound requirement specified in such an strange manner, well, that would be a different question. But this is what it means.


问:
Visual Studio keeps saying "error CS1002: ; expected"
I am new to coding with C# in unity and am trying to animate an object in unity, but its saying that I need a semicolon but I can't find where I need one. This is my code:

```<code>{
  public GameObject arm;
  public float time = 0f;
  public bool timedone = false;
  void Update()
  {
     if(time == 1f)
     {
         timedone = true;
     }
     if (Input.GetButtonDown("Fire1"))
     {
         arm.GetComponent<Animator>().Play("New Animation");
     }
     else
     {
         if(!timedone)
         {
             time += Time.deltaTime;
         }
         if (timedone)
         {
            arm.GetComponent<Animator>().Play("New State");
            Timereset()
         }
      }
  }
  void Timereset()
  {
    time == 0f;
  }
}
</code>```

If you can help me I would be very grateful.

答: The Update method is called every time a new frame is rendered. In the if condition judgment of the Update method, the Timereset() method has no semicolon, and should be written as Timereset();.

Body:
I am new to coding with C# in unity and am trying to animate an object in unity, but its saying that I need a semicolon but I can't find where I need one. This is my code:

{
  public GameObject arm;
  public float time = 0f;
  public bool timedone = false;
  void Update()
  {
     if(time == 1f)
     {
         timedone = true;
     }
     if (Input.GetButtonDown("Fire1"))
     {
         arm.GetComponent<Animator>().Play("New Animation");
     }
     else
     {
         if(!timedone)
         {
             time += Time.deltaTime;
         }
         if (timedone)
         {
            arm.GetComponent<Animator>().Play("New State");
            Timereset()
         }
      }
  }
  void Timereset()
  {
    time == 0f;
  }
}

If you can help me I would be very grateful.


问:
How to save all the output from a .ipynb file as a txt file?
I have a few .ipynb notebooks with similar outputs (time series data). I want to export all the outputs from all the notebooks to a .txt file. If that is complicated to do, then one txt file for each of the notebooks is fine too.</p>

答:
As you mentioned yourself in the comments, you can save it as a .txt file by using:

%%capture cap --no-stderr
```

By using pd.set_option('display.max_rows', None) you can then assure that all rows are shown in your jupyter notebook.

Body:
As you mentioned yourself in the comments, you can save it as a .txt file by using:

%%capture cap --no-stderr

By using pd.set_option('display.max_rows', None) you can then assure that all rows are shown in your jupyter notebook.


问:
how to stop make -n from echoing same command multiple times
I am using GNU make and have a Makefile which looks like this:

```<code>AB = A.txt B.txt

${AB}: makeAB.py
    python makeAB.py

C.txt: ${AB} makeC.py
    python makeC.py
</code>```

When I type make -n C.txt, assuming makeAB.py needs to run, I get the output:

```<code>python makeAB.py
python makeAB.py
python makeC.py
</code>```

Is there any way to write the Makefile so that the line python makeAB.py is not repeated? This is just a toy example, but in my actual application AB consists of many files, so I potentially get a whole screen of unnecessary output.

p.s. When called without -n, make (sensibly) only runs python makeAB.py once. So my problem is just with make -n.

答:
The double output arises because the recipe is scheduled to run twice, once to build A.txt and again to build B.txt.  This is normal behavior for make.  In particular a rule such as your (as expanded) ...

```<code>A.txt B.txt: makeAB.py
    python makeAB.py
</code>```

... means that each of those two targets can be built via the associated recipe, not that a single execution of the recipe builds both (regardless of whether a single run does build both).  It is 100% equivalent to:

```<code>A.txt: makeAB.py
    python makeAB.py

B.txt: makeAB.py
    python makeAB.py
</code>```

When called without -n, make (sensibly) only runs python makeAB.py once. So my problem is just with make -n.

When you run with -n, make does not execute the recipe, so it cannot evaluate whether doing so to update (say) A.txt might also update B.txt.  All it knows is that both targets are out of date, so it outputs the recipes that would be executed to update each one.  This is completely sensible.

When you run make without -n, it has the opportunity to to observe that after updating one of A.txt and B.txt, the other is up to date.  It might very naturally not even have noticed that the other was initially out of date.  Having observed this, of course it does not execute the recipe again.  The output would be clearer about what was happening if the recipe executions expressed which target was being built.  For example, try this variation on the rule, which is more like how a multiple-target rule would ordinarily be written.

```<code>A.txt B.txt: makeAB.py
    python makeAB.py $@
</code>```

So, both make outputs are right in their own ways. Arguably, however, the makefile is wrong, because it does not capture the expectation and fact that running the recipe once would generate both outputs.  This is a situation that the makefile language traditionally has difficulty expressing, and you will find other question about that here on SO and elsewhere.

If you are using a new enough version of GNU Make, then you can make use of its concept of "grouped target" rules, which addresses exactly this issue.  By using &: as the separator in the first line of the rule, you communicate (only to pretty recent versions of GNU Make) that one execution of the rule creates all the designated targets.  Example:

```<code>A.txt B.txt &: makeAB.py
    python makeAB.py
</code>```

Traditional makes and older GNU Make will just interpret the & as another target name.  That means that those makes will accept such makefiles, but not behave the same as recent GNU make.  Among other things, it means that if asked to build target &, they would try to do so, quite possibly with a surprising effect owing to the special significance of & to the shell.

Body:
I am using GNU make and have a Makefile which looks like this:

AB = A.txt B.txt

${AB}: makeAB.py
    python makeAB.py

C.txt: ${AB} makeC.py
    python makeC.py

When I type make -n C.txt, assuming makeAB.py needs to run, I get the output:

python makeAB.py
python makeAB.py
python makeC.py

Is there any way to write the Makefile so that the line python makeAB.py is not repeated? This is just a toy example, but in my actual application AB consists of many files, so I potentially get a whole screen of unnecessary output.

p.s. When called without -n, make (sensibly) only runs python makeAB.py once. So my problem is just with make -n.

Body:
The double output arises because the recipe is scheduled to run twice, once to build A.txt and again to build B.txt.  This is normal behavior for make.  In particular a rule such as your (as expanded) ...

A.txt B.txt: makeAB.py
    python makeAB.py

... means that each of those two targets can be built via the associated recipe, not that a single execution of the recipe builds both (regardless of whether a single run does build both).  It is 100% equivalent to:

A.txt: makeAB.py
    python makeAB.py

B.txt: makeAB.py
    python makeAB.py

When called without -n, make (sensibly) only runs python makeAB.py once. So my problem is just with make -n.

When you run with -n, make does not execute the recipe, so it cannot evaluate whether doing so to update (say) A.txt might also update B.txt.  All it knows is that both targets are out of date, so it outputs the recipes that would be executed to update each one.  This is completely sensible.

When you run make without -n, it has the opportunity to to observe that after updating one of A.txt and B.txt, the other is up to date.  It might very naturally not even have noticed that the other was initially out of date.  Having observed this, of course it does not execute the recipe again.  The output would be clearer about what was happening if the recipe executions expressed which target was being built.  For example, try this variation on the rule, which is more like how a multiple-target rule would ordinarily be written.

A.txt B.txt: makeAB.py
    python makeAB.py $@

So, both make outputs are right in their own ways. Arguably, however, the makefile is wrong, because it does not capture the expectation and fact that running the recipe once would generate both outputs.  This is a situation that the makefile language traditionally has difficulty expressing, and you will find other question about that here on SO and elsewhere.

If you are using a new enough version of GNU Make, then you can make use of its concept of "grouped target" rules, which addresses exactly this issue.  By using &: as the separator in the first line of the rule, you communicate (only to pretty recent versions of GNU Make) that one execution of the rule creates all the designated targets.  Example:

A.txt B.txt &: makeAB.py
    python makeAB.py

Traditional makes and older GNU Make will just interpret the & as another target name.  That means that those makes will accept such makefiles, but not behave the same as recent GNU make.  Among other things, it means that if asked to build target &, they would try to do so, quite possibly with a surprising effect owing to the special significance of & to the shell.


问:
Git stash error "Cannot save the current status"
I'm getting this error when running "git stash"

```<code>Cannot save the current status
</code>```

with no other information.

Why is that?

答: I solve this problem by git stash clear.

Body:
I'm getting this error when running "git stash"

Cannot save the current status

with no other information.

Why is that?


问:
How to delete multiple rows from MYSQL database with PHP no frameworks
I'm trying to handle a query to delete multiple items with checkboxes. I'm using react for my frontend and php for my backend.

My frontend sends the payload form data like this :
P.S My Primary Key is the SKU.

```<code>sku: DVD0004
sku: DVD0005
</code>```

I need to combine these values into 1 bracket like this (DVD0004,DVD0005) in order to put them in my query which is

My API

```<code>    public function deleteProduct($prdt_sku)
    {
        try {
            $this->db->query("DELETE FROM products WHERE product_sku = :sku");
            $this->db->bind(":sku", $prdt_sku);

            if ($this->db->execute()) {
                return true;
            } else {
                return false;
            }
        } catch (\Throwable) {
            header("HTTP/1.1 406 Error deleting product from database");
        }
    }
</code>```

*My actual form destination *

```<code>$response = array();

if (isset($_POST['sku'])) {

    $sku = $_POST['sku'];

    $result = $api->deleteProduct($sku);

    if ($result) {
        header("HTTP/1.1 200 OK");
        header("Location: http://localhost:3000/");
        exit();
    } else {
        header("HTTP/1.1 406 Error deleting product");
    }
} else {
    header("HTTP/1.1 499 Required parameters missing");
}
</code>```

答:
On the frontend I turned the multiple SKUs into an array using name="sku[]" & on the backend with the help of https://stackoverflow.com/users/9437124/stillkonfuzed by putting the database query into a foreach loop using

```<code>$sku = $_POST['sku'];
foreach($sku as $Deletables){
  $result = $api->deleteProduct($Deletables);
}
</code>```

It was fixed.

Body:
I'm trying to handle a query to delete multiple items with checkboxes. I'm using react for my frontend and php for my backend.

My frontend sends the payload form data like this :
P.S My Primary Key is the SKU.

sku: DVD0004
sku: DVD0005

I need to combine these values into 1 bracket like this (DVD0004,DVD0005) in order to put them in my query which is

My API

    public function deleteProduct($prdt_sku)
    {
        try {
            $this->db->query("DELETE FROM products WHERE product_sku = :sku");
            $this->db->bind(":sku", $prdt_sku);

            if ($this->db->execute()) {
                return true;
            } else {
                return false;
            }
        } catch (\Throwable) {
            header("HTTP/1.1 406 Error deleting product from database");
        }
    }

*My actual form destination *

$response = array();

if (isset($_POST['sku'])) {

    $sku = $_POST['sku'];

    $result = $api->deleteProduct($sku);

    if ($result) {
        header("HTTP/1.1 200 OK");
        header("Location: http://localhost:3000/");
        exit();
    } else {
        header("HTTP/1.1 406 Error deleting product");
    }
} else {
    header("HTTP/1.1 499 Required parameters missing");
}

Body:
On the frontend I turned the multiple SKUs into an array using name="sku[]" & on the backend with the help of https://stackoverflow.com/users/9437124/stillkonfuzed by putting the database query into a foreach loop using

$sku = $_POST['sku'];
foreach($sku as $Deletables){
  $result = $api->deleteProduct($Deletables);
}

It was fixed.


问:
Looping regression over increasing sample sizes in R
I am trying to store the coefficients & SEs of a linear regression in R. The regression starts with a sample size of 10 and needs to add 1 for each loop up to 1000. I have generated random variables (using rnorm), created variables to store the values in and can get the code to store the first regression, but it stops after 1 loop (sample size 10). What am I missing in my code here? Thank you for your help.</p>
```<code>matrix_coef <-NULL
df <- data.frame(yi, x1, x2)
for (i in 10:1000) {
  lm(df)
  matrix_coef <- summary(lm(df))
  b0[i]<- coef(matrix_coef)[1:1, 1:1]
  bx1[i] <- coef(matrix_coef)[2:2, 1:1 ]
  bx2[i] <- coef(matrix_coef)[3:3, 1:1]
  sd0[i] <- coef(matrix_coef)[1:1, 2:2]
  sdx1[i] <- coef(matrix_coef)[2:2, 2:2]
  sdx2[i] <- coef(matrix_coef)[3:3, 2:2]
}
</code>```

答:
You've got a few issues:

Inside the loop, df doesn't change, you're always fitting lm to the full data. You need to use i to change the data that the model trains on. Something like lm(df[1:i, ]), perhaps (assuming your full data has 1000 rows and you want the iterations to fit the first 10, then 11, then 12, ... 1000 rows, rather than, say, resampling each time)

The line lm(df) by itself fits a model, but you don't do store the results and your next line summary(lm(df)) fits the exact same model again.

You initialize the wrong object. matrix_coef <- NULL essentially does nothing. The line matrix_coef <- summary(lm(df)) inside your loop will have no problem creating the matrix_coef object. (And we can save a bunch of typing by defining it as coef(summary(lm(df))) and not typing coef() on all the subsequent lines.) However, the objects that you index should be initialized, and preferably to the correct length.

1:1 is the same as 1. 2:2 is the same as 2, etc.

Addressing all of these gives us this:

```<code>set.seed(47)
n <- 15 ## small n for demonstration purposes
df <- data.frame(yi = rnorm(n), x1 = rnorm(n), x2 = rnorm(n))

b0 <- numeric(n)
bx1 <- numeric(n)
bx2 <- numeric(n)
sd0 <- numeric(n)
sdx1 <- numeric(n)
sdx2 <- numeric(n)

for (i in 10:n) {
  matrix_coef <- coef(summary(lm(df[1:i, ])))
  b0[i]   <- matrix_coef[1, 1]
  bx1[i]  <- matrix_coef[2, 1]
  bx2[i]  <- matrix_coef[3, 1]
  sd0[i]  <- matrix_coef[1, 2]
  sdx1[i] <- matrix_coef[2, 2]
  sdx2[i] <- matrix_coef[3, 2]
}

b0
# [1]  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000
# [9]  0.00000000 -0.17267676 -0.17490218 -0.08251370 -0.04048010 -0.04976162 -0.03881043

sdx2
#  [1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.4888940
# [11] 0.4470402 0.4569932 0.4724890 0.4669553 0.4323498
</code>```

Body:
I am trying to store the coefficients & SEs of a linear regression in R. The regression starts with a sample size of 10 and needs to add 1 for each loop up to 1000. I have generated random variables (using rnorm), created variables to store the values in and can get the code to store the first regression, but it stops after 1 loop (sample size 10). What am I missing in my code here? Thank you for your help.

matrix_coef <-NULL
df <- data.frame(yi, x1, x2)
for (i in 10:1000) {
  lm(df)
  matrix_coef <- summary(lm(df))
  b0[i]<- coef(matrix_coef)[1:1, 1:1]
  bx1[i] <- coef(matrix_coef)[2:2, 1:1 ]
  bx2[i] <- coef(matrix_coef)[3:3, 1:1]
  sd0[i] <- coef(matrix_coef)[1:1, 2:2]
  sdx1[i] <- coef(matrix_coef)[2:2, 2:2]
  sdx2[i] <- coef(matrix_coef)[3:3, 2:2]
}

Body:
You've got a few issues:

Inside the loop, df doesn't change, you're always fitting lm to the full data. You need to use i to change the data that the model trains on. Something like lm(df[1:i, ]), perhaps (assuming your full data has 1000 rows and you want the iterations to fit the first 10, then 11, then 12, ... 1000 rows, rather than, say, resampling each time)

The line lm(df) by itself fits a model, but you don't do store the results and your next line summary(lm(df)) fits the exact same model again.

You initialize the wrong object. matrix_coef <- NULL essentially does nothing. The line matrix_coef <- summary(lm(df)) inside your loop will have no problem creating the matrix_coef object. (And we can save a bunch of typing by defining it as coef(summary(lm(df))) and not typing coef() on all the subsequent lines.) However, the objects that you index should be initialized, and preferably to the correct length.

1:1 is the same as 1. 2:2 is the same as 2, etc.

Addressing all of these gives us this:

set.seed(47)
n <- 15 ## small n for demonstration purposes
df <- data.frame(yi = rnorm(n), x1 = rnorm(n), x2 = rnorm(n))

b0 <- numeric(n)
bx1 <- numeric(n)
bx2 <- numeric(n)
sd0 <- numeric(n)
sdx1 <- numeric(n)
sdx2 <- numeric(n)

for (i in 10:n) {
  matrix_coef <- coef(summary(lm(df[1:i, ])))
  b0[i]   <- matrix_coef[1, 1]
  bx1[i]  <- matrix_coef[2, 1]
  bx2[i]  <- matrix_coef[3, 1]
  sd0[i]  <- matrix_coef[1, 2]
  sdx1[i] <- matrix_coef[2, 2]
  sdx2[i] <- matrix_coef[3, 2]
}

b0
# [1]  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000  0.00000000
# [9]  0.00000000 -0.17267676 -0.17490218 -0.08251370 -0.04048010 -0.04976162 -0.03881043

sdx2
#  [1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.4888940
# [11] 0.4470402 0.4569932 0.4724890 0.4669553 0.4323498


问:
Need help to sorting an array in a complicated way c# linq
I have a strict similar to this :

```<code>struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }
</code>```

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

```<code>chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();
</code>```

But I don't know how to make it alternate one after another.

答:
Not sure if you can do it with only one line of code.

I wrote a method that would only require the Array to be sorted once. Then, it enters either the next closest or furthest chunk based on the current index of the for loop (odd = closest, even = furthest). I remove the item from the sorted list to ensure that it will not be reentered in the results list. Finally, I return the results as an Array.

```<code>public Chunk[] SortArray(List<Chunk> list_to_sort)
{
    //Setup Variables
    var results = new List<Chunk>();
    int count = list_to_sort.Count;

    //Tracking the sorting list so that we only need to sort the list once
    list_to_sort = list_to_sort.OrderBy(x => x.active).ThenBy(x => x.d).ToList();

    //Loop through the list
    for (int i = 0; i < count; i++)
    {
        results.Add(list_to_sort[i % 2 == 0 ? list_to_sort.Count - 1 : 0]);
        list_to_sort.RemoveAt(i % 2 == 0 ? list_to_sort.Count - 1 : 0);
    }

    // Return Results
    return results.ToArray();
}
</code>```

There is probably a better way of doing this but hopefully it helps. Please note that I did not test this method.

Body:
I have a strict similar to this :

struct Chunk
 {
   public float d; // distance from player
   public bool active; // is it active
 }

I have an array of this struct.

What I need:

I need to sort it so the first element is an inactive chunk that is also the furthest from the player, than the next element is active and is also the closest to the player and that is the pattern,

Inactive, furthest

Active, closest

Inactive, furthest

Active, closest

Inactive, furthest
And so on...

Currently I'm using LINQ,
And I'm doing this :

chunk = chunk.AsParallel().OrderBy(x => x.active ? x.d : -x.d).ToArray();

But I don't know how to make it alternate one after another.

Body:
Not sure if you can do it with only one line of code.

I wrote a method that would only require the Array to be sorted once. Then, it enters either the next closest or furthest chunk based on the current index of the for loop (odd = closest, even = furthest). I remove the item from the sorted list to ensure that it will not be reentered in the results list. Finally, I return the results as an Array.

public Chunk[] SortArray(List<Chunk> list_to_sort)
{
    //Setup Variables
    var results = new List<Chunk>();
    int count = list_to_sort.Count;

    //Tracking the sorting list so that we only need to sort the list once
    list_to_sort = list_to_sort.OrderBy(x => x.active).ThenBy(x => x.d).ToList();

    //Loop through the list
    for (int i = 0; i < count; i++)
    {
        results.Add(list_to_sort[i % 2 == 0 ? list_to_sort.Count - 1 : 0]);
        list_to_sort.RemoveAt(i % 2 == 0 ? list_to_sort.Count - 1 : 0);
    }

    // Return Results
    return results.ToArray();
}

There is probably a better way of doing this but hopefully it helps. Please note that I did not test this method.


问:
Protobuf-net KeyedCollection serialization
I need to serialize/deserialize a KeyedCollection with protobuf-net, can I just serialize a list?

If so, what is the most efficient way to convert-back the List to the KeyedCollection?

Here follows a sample code that shows the case:

```<code>public class FamilySurrogate
{
    public List<Person> PersonList { get; set; }

    public FamilySurrogate(List<Person> personList)
    {
        PersonList = personList;
    }

    public static implicit operator Family(FamilySurrogate surrogate)
    {
        if (surrogate == null) return null;

        var people = new PersonKeyedCollection();
        foreach (var person in surrogate.PersonList)  // Is there a most efficient way?
            people.Add(person);

        return new Family(people);

    }

    public static implicit operator FamilySurrogate(Family source)
    {
        return source == null ? null : new FamilySurrogate(source.People.ToList());
    }

}

public class Person
{
    public Person(string name, string surname)
    {
        Name = name;
        Surname = surname;
    }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Fullname { get { return $"{Name} {Surname}"; } }
}

public class PersonKeyedCollection : System.Collections.ObjectModel.KeyedCollection<string, Person>
{
    protected override string GetKeyForItem(Person item) { return item.Fullname; }
}

public class Family
{
    public Family(PersonKeyedCollection people)
    {
        People = people;
    }

    public PersonKeyedCollection People { get; set; }
}
</code>```

答:
Solution?

.NET Platform Extensions 6 has an implementation of the KeyedCollection, KeyedByTypeCollection Class. This has a constructor which accepts an IEnumerable. The downside to this implementation is that the keys are the items, and it doesn't appear to allow you to change that. If you're already inheriting KeyedCollection, you may as well follow the implementation here and go by Microsoft's lead; they just iterate and call Add().

See also

Uses of KeyedByTypeCollection in .Net?

Can't seem to resolve KeyedByTypeCollection?

What are .NET Platform Extensions on learn.microsoft.com?

Linq with custom base collection

Collection Initializers

Previous thoughts

I'm also trying to tackle this issue from a Linq query perspective, possibly related posts:

Cannot implicitly convert type System.Collections.Generic.List back to Object after linq query

dotnet/runtime: Why is KeyedCollection abstract?

The core issue seems to be that KeyedCollectedion does not contain a constructor that takes any form of ICollection to initialize its data with. The base class of KeyedCollection, Collection, does however. The only option seems to be writing your own constructor for your KeyedCollection class that iterates over a collection and adds each element to the current instance.

```<code>using System.Collections.Generic;
using System.Collections.ObjectModel;

public class VariableList<T> : KeyedCollection<string, T>
{
    // KeyedCollection does not seem to support explicitly casting from an IEnumerable,
    // so we're creating a constructor who's sole purpose is to build a new KeyedCollection.
    public VariableList(IEnumerable<T> items)
    {
        foreach (T item in items)
            Add(item);
    }

    // insert other code here
}
</code>```

This seems really inefficient though, so I hope someone corrects me...

Edit: John Franco wrote a blogpost wherein they hack together a solution for genericly casting a List with covariants (in 2009!) This doesn't look like a very good way to do things.

Looking at System.Linq.Enumerable's implementation of ToList, Linq also iterates and Adds to the new collection.

Body:
I need to serialize/deserialize a KeyedCollection with protobuf-net, can I just serialize a list?

If so, what is the most efficient way to convert-back the List to the KeyedCollection?

Here follows a sample code that shows the case:

public class FamilySurrogate
{
    public List<Person> PersonList { get; set; }

    public FamilySurrogate(List<Person> personList)
    {
        PersonList = personList;
    }

    public static implicit operator Family(FamilySurrogate surrogate)
    {
        if (surrogate == null) return null;

        var people = new PersonKeyedCollection();
        foreach (var person in surrogate.PersonList)  // Is there a most efficient way?
            people.Add(person);

        return new Family(people);

    }

    public static implicit operator FamilySurrogate(Family source)
    {
        return source == null ? null : new FamilySurrogate(source.People.ToList());
    }

}

public class Person
{
    public Person(string name, string surname)
    {
        Name = name;
        Surname = surname;
    }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Fullname { get { return $"{Name} {Surname}"; } }
}

public class PersonKeyedCollection : System.Collections.ObjectModel.KeyedCollection<string, Person>
{
    protected override string GetKeyForItem(Person item) { return item.Fullname; }
}

public class Family
{
    public Family(PersonKeyedCollection people)
    {
        People = people;
    }

    public PersonKeyedCollection People { get; set; }
}

Body:
Solution?

.NET Platform Extensions 6 has an implementation of the KeyedCollection, KeyedByTypeCollection Class. This has a constructor which accepts an IEnumerable. The downside to this implementation is that the keys are the items, and it doesn't appear to allow you to change that. If you're already inheriting KeyedCollection, you may as well follow the implementation here and go by Microsoft's lead; they just iterate and call Add().

See also

Uses of KeyedByTypeCollection in .Net?

Can't seem to resolve KeyedByTypeCollection?

What are .NET Platform Extensions on learn.microsoft.com?

Linq with custom base collection

Collection Initializers

Previous thoughts

I'm also trying to tackle this issue from a Linq query perspective, possibly related posts:

Cannot implicitly convert type System.Collections.Generic.List back to Object after linq query

dotnet/runtime: Why is KeyedCollection abstract?

The core issue seems to be that KeyedCollectedion does not contain a constructor that takes any form of ICollection to initialize its data with. The base class of KeyedCollection, Collection, does however. The only option seems to be writing your own constructor for your KeyedCollection class that iterates over a collection and adds each element to the current instance.

using System.Collections.Generic;
using System.Collections.ObjectModel;

public class VariableList<T> : KeyedCollection<string, T>
{
    // KeyedCollection does not seem to support explicitly casting from an IEnumerable,
    // so we're creating a constructor who's sole purpose is to build a new KeyedCollection.
    public VariableList(IEnumerable<T> items)
    {
        foreach (T item in items)
            Add(item);
    }

    // insert other code here
}

This seems really inefficient though, so I hope someone corrects me...

Edit: John Franco wrote a blogpost wherein they hack together a solution for genericly casting a List with covariants (in 2009!) This doesn't look like a very good way to do things.

Looking at System.Linq.Enumerable's implementation of ToList, Linq also iterates and Adds to the new collection.


问:
Send E-mail using SMTP with HTML Body & Signature
Managed to get this sending using Excel with SMTP.

When sending one e-mail at a time, the first one has the signature  displayed where it should be.

Second e-mail sent has the signature but adds the signature as an attachment.

Third e-mail sent has the signature but adds the signature as an attachment twice, and it will repeat the the cycle adding more signature images as attachments.

TLDR:

1 e-mail sent = 0 attachment

2 e-mails sent = 1 attachment

3 e-mails sent = 2 attachments

I don't want any attached files.

Sub SendMail()
    Set MyEmail = CreateObject("CDO.Message")
    Path = "C:\Users\Users1\Desktop\Signature\"

    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Set sh2 = ThisWorkbook.Sheets("Sheet2")

    Dim nDateTime As Date, oDateTime As Date
    nDateTime = Now
    oDateTime = nDateTime - 3

    Dim last_row As Integer
    last_row = Application.CountA(sh.Range("A:A"))
    For i = 2 To last_row
    Set emailConfig = MyEmail.Configuration

With MyEmail
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername")
= redacted
    emailConfig.Fields.Update
    MyEmail.Configuration.Fields.Update

End With

mail_body_message = sh2.Range("D2")
serial_number = sh.Range("A" & i).Value
mail_body_message = Replace(mail_body_message, "replace_serial_here", serial_number)
Attachment = Path + Filename
signaturelogo = "userSignature.png"

With MyEmail

Attachment = Path + Filename
signaturelogo = "userSignature.png"
Path = "C:\Users\Users1\Desktop\Signature\"
.Subject = "Hello there (HTTPS) Serial: " & serial_number
.From = "redacted"
.To = sh.Range("B" & i).Value
.HTMLBody = mail_body_message
.Attachments.Add Path & signaturelogo, 0

End With

If sh.Range("C" & i).Value <= oDateTime Then
    MyEmail.Send
End If

Next i

End Sub
```

答:
Ended up removing .Attachments.Add Path & signaturelogo, 0

For .HTMLBody = mail_body_message
Changed to below, (the fix)
.HTMLBody = mail_body_message & " "


问:
How to create a blob in an Azure Storage Container using Python & Azure Functions
I am having a lot of difficulty writing an API response as json to a blob within an Azure Storage Container.  I have tried multiple solutions online but have not managed to see any through to success.  I would like to share 2 attempts I have made and hopefully there is someone out there that can assist me in getting at least one methodology correct

Attempt/Method 1

I have tried to use a Service Principle to authenticate my BlobServiceClient from Azure-Storage-Blob.  My service principal has been assigned the role of Storage Blob Data Contributor for the Container within which I am trying to create the blob. However on execution of the script I receive an error along the lines of "Unsupported Credential".  Below is my script and the error:

My script and resulting error are:

```<code>import azure.functions as func
import requests
import json
import uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from msrestazure.azure_active_directory import ServicePrincipalCredentials
from azure.storage.common import TokenCredential

# Initialise parameters to obtain data from Rest API
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token()}

# Get response.  I want to save the response output to a blob.
response = requests.get(url, headers=headers)
response = response.json()

# Initialise parameters for credentials
CLIENT = "bxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx7" # Azure App/Service Principal ID
KEY = "Gxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1" # Azure App/Service Principal Key
TENANT_ID = "cxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx7" # Tenant where Storage Account is which is different to the Tenant the App resides
RESOURCE = f"https://storageaccountxxxxxxxxx.blob.core.windows.net"

# Create credentials & token
credentials = ServicePrincipalCredentials(
    client_id = CLIENT,
    secret = KEY,
    #tenant = TENANT_ID,
    resource = RESOURCE
)
tokenCre = TokenCredential(credentials.token["access_token"])

# Initialise parameters for BlobServiceClient
ACCOUNT_URL = "https://storageaccountxxxxxxxxx.blob.core.windows.net/pbiactivity" # includes container name at end of url

#Create BlobServiceClient
blobService = BlobServiceClient(account_url = ACCOUNT_URL, token_credential=tokenCre)

#Create blobClient
blobClient = BlobClient(account_url = RESOURCE,container_name=CONTAINER_NAME, blob_name="response.json", credential = tokenCre )

#Upload response json as blob
blobClient.upload_blob(response, blob_type = "BlockBlob")
</code>```

Click here for the error that comes after the upload_blob method call]1

Attempt/Method 2

In my second attempt I tried to create ,my BlobServiceClient using Azure-Storage-Blob using my storage account connection string.  This method actually allows me to create containers, however when I try to upload a blob as in the script below, However I am unable to create blobs within a container as I get a 403 Forbidden response.

My script and resulting error are:

```<code>import requests
import json
import uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

# Initialise parameters to obtain data from Rest API
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token()}

# Get response.  I want to save the response output to a blob.
response = requests.get(url, headers=headers)
response = response.json()

# Initialise parameters
CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=storageaccountxxxxxxxxx;AccountKey=rxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxQ==;EndpointSuffix=core.windows.net"

# Create blobServiceClient from connection string
blobServiceClient = BlobServiceClient.from_connection_string(conn_str=CONNECTION_STRING)

#Create blobClient
blobClient = blobServiceClient.get_blob_client(container = "pbiactivity", blob = "response.json")

#Upload response json to blob
blobClient.upload_blob(response, blob_type = "BlockBlob")
</code>```

Click Here for the errors that come after the upload_blob method call]2

答:
Here is one of the workaround that worked for me:-

import os
import logging
from azure.storage.blob import BlobServiceClient, BlobClient

#Initialise parameters
url = "<YourURL>"
headers = {'Authorization': get_access_token()}

#Get response
response = requests.get(url, headers=headers)
response = response.json()

connectionString= "<Your_Connection_String>"
containerName = "<Name_of_your_container>"

blobServiceClient = BlobServiceClient.from_connection_string(connectionString)
blobContainerClient = blobServiceClient.get_container_client(containerName)

#To create Container (If the container has already been created you can ignore this)
#blobContainerClient.create_container()

#Create blobClient
blobClient = blobServiceClient.get_blob_client(container = "<Name_of_your_container>", blob = "response.json")

with open("response", "rb") as blob_file:
    blobClient.upload_blob(data=blob_file)
```

In my Storage Account:-

Body:
I am having a lot of difficulty writing an API response as json to a blob within an Azure Storage Container.  I have tried multiple solutions online but have not managed to see any through to success.  I would like to share 2 attempts I have made and hopefully there is someone out there that can assist me in getting at least one methodology correct

Attempt/Method 1

I have tried to use a Service Principle to authenticate my BlobServiceClient from Azure-Storage-Blob.  My service principal has been assigned the role of Storage Blob Data Contributor for the Container within which I am trying to create the blob. However on execution of the script I receive an error along the lines of "Unsupported Credential".  Below is my script and the error:

My script and resulting error are:

import azure.functions as func
import requests
import json
import uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from msrestazure.azure_active_directory import ServicePrincipalCredentials
from azure.storage.common import TokenCredential

# Initialise parameters to obtain data from Rest API
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token()}

# Get response.  I want to save the response output to a blob.
response = requests.get(url, headers=headers)
response = response.json()

# Initialise parameters for credentials
CLIENT = "bxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx7" # Azure App/Service Principal ID
KEY = "Gxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1" # Azure App/Service Principal Key
TENANT_ID = "cxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx7" # Tenant where Storage Account is which is different to the Tenant the App resides
RESOURCE = f"https://storageaccountxxxxxxxxx.blob.core.windows.net"

# Create credentials & token
credentials = ServicePrincipalCredentials(
    client_id = CLIENT,
    secret = KEY,
    #tenant = TENANT_ID,
    resource = RESOURCE
)
tokenCre = TokenCredential(credentials.token["access_token"])

# Initialise parameters for BlobServiceClient
ACCOUNT_URL = "https://storageaccountxxxxxxxxx.blob.core.windows.net/pbiactivity" # includes container name at end of url

#Create BlobServiceClient
blobService = BlobServiceClient(account_url = ACCOUNT_URL, token_credential=tokenCre)

#Create blobClient
blobClient = BlobClient(account_url = RESOURCE,container_name=CONTAINER_NAME, blob_name="response.json", credential = tokenCre )

#Upload response json as blob
blobClient.upload_blob(response, blob_type = "BlockBlob")

Click here for the error that comes after the upload_blob method call]1

Attempt/Method 2

In my second attempt I tried to create ,my BlobServiceClient using Azure-Storage-Blob using my storage account connection string.  This method actually allows me to create containers, however when I try to upload a blob as in the script below, However I am unable to create blobs within a container as I get a 403 Forbidden response.

My script and resulting error are:

import requests
import json
import uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient

# Initialise parameters to obtain data from Rest API
url = "https://api.powerbi.com/v1.0/myorg/admin/groups?$top=1000&$expand=datasets,dataflows,reports,users,dashboards"
headers = {'Authorization': get_access_token()}

# Get response.  I want to save the response output to a blob.
response = requests.get(url, headers=headers)
response = response.json()

# Initialise parameters
CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=storageaccountxxxxxxxxx;AccountKey=rxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxQ==;EndpointSuffix=core.windows.net"

# Create blobServiceClient from connection string
blobServiceClient = BlobServiceClient.from_connection_string(conn_str=CONNECTION_STRING)

#Create blobClient
blobClient = blobServiceClient.get_blob_client(container = "pbiactivity", blob = "response.json")

#Upload response json to blob
blobClient.upload_blob(response, blob_type = "BlockBlob")

Click Here for the errors that come after the upload_blob method call]2

Body:
Here is one of the workaround that worked for me:-

import os
import logging
from azure.storage.blob import BlobServiceClient, BlobClient

#Initialise parameters
url = "<YourURL>"
headers = {'Authorization': get_access_token()}

#Get response
response = requests.get(url, headers=headers)
response = response.json()

connectionString= "<Your_Connection_String>"
containerName = "<Name_of_your_container>"

blobServiceClient = BlobServiceClient.from_connection_string(connectionString)
blobContainerClient = blobServiceClient.get_container_client(containerName)

#To create Container (If the container has already been created you can ignore this)
#blobContainerClient.create_container()

#Create blobClient
blobClient = blobServiceClient.get_blob_client(container = "<Name_of_your_container>", blob = "response.json")

with open("response", "rb") as blob_file:
    blobClient.upload_blob(data=blob_file)

In my Storage Account:-


问:
How to strip certain characters from a string in python
I am trying to strip certain characters from a string. The string I have is -

```<code>test_list = ['INFO:      196ns ### Starting ABC Test ###\n', 'INFO:     310ns ### Starting write_def_test ###\n', 'INFO:     752ns ### Starting write_55s_test ###\n', 'INFO:    152ns ### Starting rands_test ###\n', 'INFO:    237ns ### Starting dog_wffs_test ###\n']
</code>```

The code I have is -

```<code>test_list_1 = []
for i in test_list:
    m = i.strip("INFO:      ")
    m = m.strip("###")
    test_list_1.append(m)
print(test_list_1)
</code>```

The output I am looking for is -

```<code>['ABC Test', 'write_def_test', 'write_55s_test', 'rands_test', 'dog_wffs_test']
</code>```

How can I get it?

答:
I agree regex is probably the way to go for complex pattern matching, if you cant use that or don't want to learn it for whatever reason, the string.find() method is very useful for simple cases like this/one offs where cooking up regex may take a little too much time:

test_list_1 = []
for i in test_list:
    test_list_1.append(i[i.find('### ') + 13 : i.find('###\n') - 1])
print(test_list_1)
```

Body:
I am trying to strip certain characters from a string. The string I have is -

test_list = ['INFO:      196ns ### Starting ABC Test ###\n', 'INFO:     310ns ### Starting write_def_test ###\n', 'INFO:     752ns ### Starting write_55s_test ###\n', 'INFO:    152ns ### Starting rands_test ###\n', 'INFO:    237ns ### Starting dog_wffs_test ###\n']

The code I have is -

test_list_1 = []
for i in test_list:
    m = i.strip("INFO:      ")
    m = m.strip("###")
    test_list_1.append(m)
print(test_list_1)

The output I am looking for is -

['ABC Test', 'write_def_test', 'write_55s_test', 'rands_test', 'dog_wffs_test']

How can I get it?