问:
Problem with oddo v11 = ERROR ? werkzeug: Error on request:
I'm new working with oddo v11, and I'm getting the next error when try to running odoo

This the output:

```<code>(Leyendo la base de datos ... 167764 ficheros o directorios instalados actualmente.)
Preparando para desempaquetar wkhtmltox-0.12.1_linux-trusty-amd64.deb ...
Desempaquetando wkhtmltox (0.12.1) sobre (0.12.1) ...
Configurando wkhtmltox (0.12.1) ...
Procesando disparadores para man-db (2.8.3-2ubuntu0.1) ...
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ sudo cp /usr/local/bin/wkhtmltoimage /usr/bin/wkhtmltoimage
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ sudo cp /usr/local/bin/wkhtmltopdf /usr/bin/wkhtmltopdf
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ cd /opt/odoo/odoo
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo/odoo$ ./odoo-bin
2020-02-15 04:34:46,420 18404 INFO ? odoo: Odoo version 11.0
2020-02-15 04:34:46,421 18404 INFO ? odoo: addons paths: ['/home/jose/.local/share/Odoo/addons/11.0', '/opt/odoo/odoo/odoo/addons', '/opt/odoo/odoo/addons']
2020-02-15 04:34:46,421 18404 INFO ? odoo: database: default@default:default
2020-02-15 04:34:46,460 18404 INFO ? odoo.service.server: HTTP service (werkzeug) running on jose-Lenovo-ideapad-330-15AST:8069
2020-02-15 04:34:46,621 18404 INFO ? odoo.addons.base.ir.ir_actions_report: Will use the Wkhtmltopdf binary at /usr/local/bin/wkhtmltopdf

2020-02-15 04:35:33,745 18404 INFO ? odoo.addons.sms.wizard.send_sms: The `phonenumbers` Python module is not available. Phone number validation will be skipped. Try `pip3 install phonenumbers` to install it.
2020-02-15 04:35:34,213 18404 INFO ? odoo.http: HTTP Configuring static files
2020-02-15 04:35:34,218 18404 INFO ? odoo.sql_db: Connection to the database failed
2020-02-15 04:35:34,221 18404 INFO ? werkzeug: 127.0.0.1 - - [15/Feb/2020 04:35:34] "GET / HTTP/1.1" 500 -
2020-02-15 04:35:34,226 18404 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 205, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 193, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 348, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 166, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 154, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1321, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1295, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/wsgi.py", line 599, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1458, in dispatch
    self.setup_db(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1390, in setup_db
    httprequest.session.db = db_monodb(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1542, in db_monodb
    dbs = db_list(True, httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1509, in db_list
    dbs = odoo.service.db.list_dbs(force)
  File "/opt/odoo/odoo/odoo/service/db.py", line 369, in list_dbs
    with closing(db.cursor()) as cr:
  File "/opt/odoo/odoo/odoo/sql_db.py", line 637, in cursor
    return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 178, in __init__
    self._cnx = pool.borrow(dsn)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 520, in _locked
    return fun(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 588, in borrow
    **connection_info)
  File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  no existe el rol «jose»
2020-02-15 04:45:23,773 18404 INFO ? odoo.sql_db: Connection to the database failed
2020-02-15 04:45:23,775 18404 INFO ? werkzeug: 127.0.0.1 - - [15/Feb/2020 04:45:23] "GET / HTTP/1.1" 500 -
2020-02-15 04:45:23,785 18404 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 205, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 193, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 348, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 166, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 154, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1321, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1295, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/wsgi.py", line 599, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1458, in dispatch
    self.setup_db(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1390, in setup_db
    httprequest.session.db = db_monodb(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1542, in db_monodb
    dbs = db_list(True, httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1509, in db_list
    dbs = odoo.service.db.list_dbs(force)
  File "/opt/odoo/odoo/odoo/service/db.py", line 369, in list_dbs
    with closing(db.cursor()) as cr:
  File "/opt/odoo/odoo/odoo/sql_db.py", line 637, in cursor
    return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 178, in __init__
    self._cnx = pool.borrow(dsn)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 520, in _locked
    return fun(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 588, in borrow
    **connection_info)
  File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  no existe el rol «jose»
</code>```

And if someone could you help me with this problem I'd thank you a lot. I've configured Oddo with these commands.

https://github.com/mtsoftware2016/odoo11/blob/master/commands.txt#L32

Thx for reading.

答:
no existe el rol «jose»

This error means you are trying to connect with Postgresql Database with db_user jose which doesn't exists.

Create DB user for Odoo and provide db_user and db_password accordingly in the Odoo config file by :

sudo su postgres

createuser -s odoo

createuser -s your_user_name

exit

and try to connect again by change directory to cd /odoo/odoo-server
then type and run ./odoo-bin

Body:
I'm new working with oddo v11, and I'm getting the next error when try to running odoo

This the output:

(Leyendo la base de datos ... 167764 ficheros o directorios instalados actualmente.)
Preparando para desempaquetar wkhtmltox-0.12.1_linux-trusty-amd64.deb ...
Desempaquetando wkhtmltox (0.12.1) sobre (0.12.1) ...
Configurando wkhtmltox (0.12.1) ...
Procesando disparadores para man-db (2.8.3-2ubuntu0.1) ...
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ sudo cp /usr/local/bin/wkhtmltoimage /usr/bin/wkhtmltoimage
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ sudo cp /usr/local/bin/wkhtmltopdf /usr/bin/wkhtmltopdf
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo$ cd /opt/odoo/odoo
jose@jose-Lenovo-ideapad-330-15AST:/opt/odoo/odoo$ ./odoo-bin
2020-02-15 04:34:46,420 18404 INFO ? odoo: Odoo version 11.0
2020-02-15 04:34:46,421 18404 INFO ? odoo: addons paths: ['/home/jose/.local/share/Odoo/addons/11.0', '/opt/odoo/odoo/odoo/addons', '/opt/odoo/odoo/addons']
2020-02-15 04:34:46,421 18404 INFO ? odoo: database: default@default:default
2020-02-15 04:34:46,460 18404 INFO ? odoo.service.server: HTTP service (werkzeug) running on jose-Lenovo-ideapad-330-15AST:8069
2020-02-15 04:34:46,621 18404 INFO ? odoo.addons.base.ir.ir_actions_report: Will use the Wkhtmltopdf binary at /usr/local/bin/wkhtmltopdf

2020-02-15 04:35:33,745 18404 INFO ? odoo.addons.sms.wizard.send_sms: The `phonenumbers` Python module is not available. Phone number validation will be skipped. Try `pip3 install phonenumbers` to install it.
2020-02-15 04:35:34,213 18404 INFO ? odoo.http: HTTP Configuring static files
2020-02-15 04:35:34,218 18404 INFO ? odoo.sql_db: Connection to the database failed
2020-02-15 04:35:34,221 18404 INFO ? werkzeug: 127.0.0.1 - - [15/Feb/2020 04:35:34] "GET / HTTP/1.1" 500 -
2020-02-15 04:35:34,226 18404 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 205, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 193, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 348, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 166, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 154, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1321, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1295, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/wsgi.py", line 599, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1458, in dispatch
    self.setup_db(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1390, in setup_db
    httprequest.session.db = db_monodb(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1542, in db_monodb
    dbs = db_list(True, httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1509, in db_list
    dbs = odoo.service.db.list_dbs(force)
  File "/opt/odoo/odoo/odoo/service/db.py", line 369, in list_dbs
    with closing(db.cursor()) as cr:
  File "/opt/odoo/odoo/odoo/sql_db.py", line 637, in cursor
    return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 178, in __init__
    self._cnx = pool.borrow(dsn)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 520, in _locked
    return fun(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 588, in borrow
    **connection_info)
  File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  no existe el rol «jose»
2020-02-15 04:45:23,773 18404 INFO ? odoo.sql_db: Connection to the database failed
2020-02-15 04:45:23,775 18404 INFO ? werkzeug: 127.0.0.1 - - [15/Feb/2020 04:45:23] "GET / HTTP/1.1" 500 -
2020-02-15 04:45:23,785 18404 ERROR ? werkzeug: Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 205, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/serving.py", line 193, in execute
    application_iter = app(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/server.py", line 348, in app
    return self.app(e, s)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 166, in application
    return application_unproxied(environ, start_response)
  File "/opt/odoo/odoo/odoo/service/wsgi_server.py", line 154, in application_unproxied
    result = handler(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1321, in __call__
    return self.dispatch(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1295, in __call__
    return self.app(environ, start_wrapped)
  File "/usr/local/lib/python3.6/dist-packages/werkzeug/wsgi.py", line 599, in __call__
    return self.app(environ, start_response)
  File "/opt/odoo/odoo/odoo/http.py", line 1458, in dispatch
    self.setup_db(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1390, in setup_db
    httprequest.session.db = db_monodb(httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1542, in db_monodb
    dbs = db_list(True, httprequest)
  File "/opt/odoo/odoo/odoo/http.py", line 1509, in db_list
    dbs = odoo.service.db.list_dbs(force)
  File "/opt/odoo/odoo/odoo/service/db.py", line 369, in list_dbs
    with closing(db.cursor()) as cr:
  File "/opt/odoo/odoo/odoo/sql_db.py", line 637, in cursor
    return Cursor(self.__pool, self.dbname, self.dsn, serialized=serialized)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 178, in __init__
    self._cnx = pool.borrow(dsn)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 520, in _locked
    return fun(self, *args, **kwargs)
  File "/opt/odoo/odoo/odoo/sql_db.py", line 588, in borrow
    **connection_info)
  File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 130, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  no existe el rol «jose»

And if someone could you help me with this problem I'd thank you a lot. I've configured Oddo with these commands.

https://github.com/mtsoftware2016/odoo11/blob/master/commands.txt#L32

Thx for reading.


来源: stackexchange

问:
asyncio - How can coroutines be used in signal handlers?
I am developing an application that uses asyncio from python3.4 for networking. When this application shuts down cleanly, a node needs to "disconnect" from the hub. This disconnect is an active process that requires a network connection so the loop needs to wait for this to complete before shutting down.

My issue is that using a coroutine as a signal handler will result in the application not shutting down. Please consider the following example:

```<code>import asyncio
import functools
import os
import signal

@asyncio.coroutine
def ask_exit(signame):
    print("got signal %s: exit" % signame)
    yield from asyncio.sleep(10.0)
    loop.stop()

loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
    loop.add_signal_handler(getattr(signal, signame),
                                        functools.partial(ask_exit, signame))

print("Event loop running forever, press CTRL+c to interrupt.")
print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
loop.run_forever()
</code>```

If you run this example and then press Ctrl+C, nothing will happen.
The question is, how do I make this behavior happen with siganls and coroutines?

答:
python3.8

1st attempt: used async def handler_shutdown, and wrapped it in  loop.create_task() when passing to add_signal_handler()

2nd attempt: don't use async for def handler_shutdown().

3rd attempt: wrap handler_shutdown and param in functools.partial()

e.g.

```<code>import asyncio
import functools
def handler_shutdown(signal, loop, tasks, http_runner, ):
    ...
    ...
def main():
    loop = asyncio.get_event_loop()
    for signame in ('SIGINT', 'SIGTERM', 'SIGQUIT'):
                print(f"add signal handler {signame} ...")
                loop.add_signal_handler(
                    getattr(signal, signame),
                    functools.partial(handler_shutdown,
                            signal=signame, loop=loop, tasks=tasks,
                            http_runner=http_runner
                            )
                    )
</code>```

The main issue i had was error

raise TypeError("coroutines cannot be used "

solved it by wrapping the routine in loop.create_task()

then solved it by removing async form signal handler function

for named param to handler also use functools.partial

ContentLicense: CC BY-SA 3.0

Body:
I am developing an application that uses asyncio from python3.4 for networking. When this application shuts down cleanly, a node needs to "disconnect" from the hub. This disconnect is an active process that requires a network connection so the loop needs to wait for this to complete before shutting down.

My issue is that using a coroutine as a signal handler will result in the application not shutting down. Please consider the following example:

import asyncio
import functools
import os
import signal

@asyncio.coroutine
def ask_exit(signame):
    print("got signal %s: exit" % signame)
    yield from asyncio.sleep(10.0)
    loop.stop()

loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
    loop.add_signal_handler(getattr(signal, signame),
                                        functools.partial(ask_exit, signame))

print("Event loop running forever, press CTRL+c to interrupt.")
print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
loop.run_forever()

If you run this example and then press Ctrl+C, nothing will happen.
The question is, how do I make this behavior happen with siganls and coroutines?

Body:
python3.8

1st attempt: used async def handler_shutdown, and wrapped it in  loop.create_task() when passing to add_signal_handler()

2nd attempt: don't use async for def handler_shutdown().

3rd attempt: wrap handler_shutdown and param in functools.partial()

e.g.

import asyncio
import functools
def handler_shutdown(signal, loop, tasks, http_runner, ):
    ...
    ...
def main():
    loop = asyncio.get_event_loop()
    for signame in ('SIGINT', 'SIGTERM', 'SIGQUIT'):
                print(f"add signal handler {signame} ...")
                loop.add_signal_handler(
                    getattr(signal, signame),
                    functools.partial(handler_shutdown,
                            signal=signame, loop=loop, tasks=tasks,
                            http_runner=http_runner
                            )
                    )

The main issue i had was error

raise TypeError("coroutines cannot be used "

solved it by wrapping the routine in loop.create_task()

then solved it by removing async form signal handler function

for named param to handler also use functools.partial

ContentLicense: CC BY-SA 4.0


问:
Tizen Studio 3.3: Device Manager and Emulator Manager fail to launch due to "The code execution cannot proceed because MSVCP120.dll was not found."
I have recently installed Tizen Studio 3.3 (web-ide_Tizen_Studio_3.3_windows-64.exe) and also install all necessary packages through Package Manager. After the process of installation had finished, I tried to launch Device Manager and Emulator Manager, but failed because of the system Error: "The code execution cannot proceed because MSVCP120.dll was not found. Reinstalling the program may fix this problem".

However, this file exists in the folder C:\Windows\system32 and all versions of Microsoft Visual C++ Redistributable Versions are installed.

Please, help me to overcome this issue. Thank you in advance.

答:
You need to install Visual C++ Redistributable Packages for Visual Studio 2013 (x86)
https://www.microsoft.com/en-us/download/details.aspx?id=40784


问:
android socket connection in android 8.0
I am using sockets for android real time push notifications, but the trouble is here, In android 8.0 or higher when app is killed , then socket is disconnected, however we achieved connection alive with foreground notification, but ideal user wont be happy with that, is there any solution so that I can run sockets in background or hide foreground notification ? (I dont want to use FCM notifications for some reasons), however I can use job schedulers or workers but there will be atleast 15minutes delay which is not real time</p>

答:
Using broadcast and service together are a good solution for your problem they can call and run even when your app killed

Just check the below link, I hope that it might help you :

How to keep a CountDownTimer running even if the app is closed?
https://stackoverflow.com/a/32028234/7485788


问:
Detect if HTML5 Video element is playing
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.

This is my current code:

```<code>var stream = document.getElementsByTagName('video');

function pauseStream() {
  if (stream.playing) {
    for (var i = 0; i < stream.length; i++) {
      stream[i].pause();
      $("body > header").addClass("paused_note");
      $(".paused_note").text("Stream Paused");
      $('.paused_note').css("opacity", "1");
    }
  }
}
</code>```

答:
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.

<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
  <source src="your source" type="video/mp4">
</video>
```

<p>inside <strong>app.component.ts</strong></p>

```playIfPaused(file){
    file.paused ? file.play(): file.pause();
}
```

Body:
I've looked through a couple of questions to find out if an HTML5 element is playing, but can't find the answer. I've looked at the W3 documentation and it has an event named "playing" but I can't seem to get it to work.

This is my current code:

var stream = document.getElementsByTagName('video');

function pauseStream() {
  if (stream.playing) {
    for (var i = 0; i < stream.length; i++) {
      stream[i].pause();
      $("body > header").addClass("paused_note");
      $(".paused_note").text("Stream Paused");
      $('.paused_note').css("opacity", "1");
    }
  }
}

Body:
My requirement was to click on the video and pause if it was playing or play if it was paused. This worked for me.

<video id="myVideo" #elem width="320" height="176" autoplay (click)="playIfPaused(elem)">
  <source src="your source" type="video/mp4">
</video>

inside app.component.ts

playIfPaused(file){
    file.paused ? file.play(): file.pause();
}


问:
Search item in list in another list in C#
I want to match any string items in the list with substring items in another list, then put substring and repetition in the dictionary without for loop because the substring list contains 24345000 cells.</p>

```<code> string[] folders = Directory.GetDirectories(@"..\Raw Data", "*");
 Dictionary<string, int> freq = new Dictionary<string, int>();
 var letters= File.ReadAllLines(@"..\letters.txt").ToList();
 foreach (string folder in folders)
        {
            string name_folder = Path.GetFileName(folder);

            string[] N_F = Directory.GetFiles(@"..\items\" + folder, "*.txt");
            foreach (string f in N_F)
            {
                List<string> s = File.ReadAllText(f).Split(' ').ToList();
                s.RemoveAll(string.IsNullOrWhiteSpace);
                foreach(string t in letters)
                    if(s.Contains(t))
                if (freq.ContainsKey(t))
                        freq[t]++;
                    else
                        freq[t] = 1;
            }
}
</code>```

答:
You are looking for a way to search count of occurrence of words from a list in another list.

```<code>// Sample Data
var letters = new string[] { "Apple", "Orange", "Mango", "Cherry" };
var masterList = new string[]
                { "Apple", "Tea", "Mango", "Apple", "Wheat", "Mango",
                  "Bread", "Orange", "Mango", "Apple", "Orange", "Mango",
                  "Apple", "Bread", "Mango", "Apple", "Bread", "Tea"
                };
</code>```

You can try:

```<code>var freq = words.Select(w => new { Word = w, Count = masterList.Count(m => m == w) })
                              .ToList();
</code>```

freq will contain:

```<code>Word = Apple    Count = 5
Word = Orange    Count = 2
Word = Mango    Count = 5
Word = Cherry    Count = 0
</code>```

Body:
I want to match any string items in the list with substring items in another list, then put substring and repetition in the dictionary without for loop because the substring list contains 24345000 cells.

 string[] folders = Directory.GetDirectories(@"..\Raw Data", "*");
 Dictionary<string, int> freq = new Dictionary<string, int>();
 var letters= File.ReadAllLines(@"..\letters.txt").ToList();
 foreach (string folder in folders)
        {
            string name_folder = Path.GetFileName(folder);

            string[] N_F = Directory.GetFiles(@"..\items\" + folder, "*.txt");
            foreach (string f in N_F)
            {
                List<string> s = File.ReadAllText(f).Split(' ').ToList();
                s.RemoveAll(string.IsNullOrWhiteSpace);
                foreach(string t in letters)
                    if(s.Contains(t))
                if (freq.ContainsKey(t))
                        freq[t]++;
                    else
                        freq[t] = 1;
            }
}

Body:
You are looking for a way to search count of occurrence of words from a list in another list.

// Sample Data
var letters = new string[] { "Apple", "Orange", "Mango", "Cherry" };
var masterList = new string[]
                { "Apple", "Tea", "Mango", "Apple", "Wheat", "Mango",
                  "Bread", "Orange", "Mango", "Apple", "Orange", "Mango",
                  "Apple", "Bread", "Mango", "Apple", "Bread", "Tea"
                };

You can try:

var freq = words.Select(w => new { Word = w, Count = masterList.Count(m => m == w) })
                              .ToList();

freq will contain:

Word = Apple    Count = 5
Word = Orange    Count = 2
Word = Mango    Count = 5
Word = Cherry    Count = 0


问:
How to get char from string by index?
Lets say I have a string that consists of x unknown chars. How could I get char nr. 13 or char nr. x-14?</p>

答:
I think this is more clear than describing it in words</p>

```<code>s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'
</code>```

Title: How to get char from string by index?

Body:
I think this is more clear than describing it in words

s = 'python'
print(len(s))
6
print(s[5])
'n'
print(s[len(s) - 1])
'n'
print(s[-1])
'n'


问:
How to call methods on Python class descriptor objects?
I created a class String() with __get__(), __set__(), and a method to_db(); however, when I do name = String(), I can't do self.name.to_db() because it's calling to_db() on the value returned by __get__(), not the object "name".

```<code>class String(object):

    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type':'string', 'value': self.value}

class Example(object):

    name = String()
    age = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def save():
        data = dict(name=self.name.to_db(), age=self.age.to_db())
        db.save(data)
</code>```

One way to deal with this is to not call self.name.to_db() directly and instead set a flag in instance and create a conditional in __get__() to check for it and call to_db() if it's True, but this seems kludgy. Is there a better way?

Also, I'm new to descriptors -- what are the pros/cons of using instance and/or instance.__dict__ to store state vs storing it in self?

答:
Inside method to_db you may access directly the value via

```<code>self.__dict__['value'] # value as key is not ideal, but that's what OP used
</code>```

or, if you are using new style classes only,

```<code>object.__set__(self, name, value)
</code>```

Since you are using magic attributes, accessing the magic __dict__ is perfectly reasonable.

This is also referred in the documentation for __setattr__ [1] (sorry, there is no direct reference to __dict__ in __set__ but it's the same problem domain)

```<code>If __setattr__() wants to assign to an instance attribute, it should not
simply execute   self.name = value — this would cause a recursive call to itself.
Instead, it should insert the value in the dictionary of instance attributes, e.g.,
self.__dict__[name] = value. For new-style classes, rather than accessing the instance
dictionary, it should call the base class method with the same name, for example,
object.__setattr__(self, name, value).
</code>```

[1] http://docs.python.org/2/reference/datamodel.html#customizing-attribute-access

Body:
I created a class String() with __get__(), __set__(), and a method to_db(); however, when I do name = String(), I can't do self.name.to_db() because it's calling to_db() on the value returned by __get__(), not the object "name".

class String(object):

    def __init__(self, value=None):
        if value:
            self.value = str(value)

    def __get__(self, instance, owner):
        return self.value

    def __set__(self, instance, value):
        self.value = str(value)

    def to_db(self):
        return {'type':'string', 'value': self.value}

class Example(object):

    name = String()
    age = Integer()

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def save():
        data = dict(name=self.name.to_db(), age=self.age.to_db())
        db.save(data)

One way to deal with this is to not call self.name.to_db() directly and instead set a flag in instance and create a conditional in __get__() to check for it and call to_db() if it's True, but this seems kludgy. Is there a better way?

Also, I'm new to descriptors -- what are the pros/cons of using instance and/or instance.__dict__ to store state vs storing it in self?

Body:
Inside method to_db you may access directly the value via

self.__dict__['value'] # value as key is not ideal, but that's what OP used

or, if you are using new style classes only,

object.__set__(self, name, value)

Since you are using magic attributes, accessing the magic __dict__ is perfectly reasonable.

This is also referred in the documentation for __setattr__ [1] (sorry, there is no direct reference to __dict__ in __set__ but it's the same problem domain)

If __setattr__() wants to assign to an instance attribute, it should not
simply execute   self.name = value — this would cause a recursive call to itself.
Instead, it should insert the value in the dictionary of instance attributes, e.g.,
self.__dict__[name] = value. For new-style classes, rather than accessing the instance
dictionary, it should call the base class method with the same name, for example,
object.__setattr__(self, name, value).

[1] http://docs.python.org/2/reference/datamodel.html#customizing-attribute-access


问:
DataTable: Print Not working in Angular 9 and Electron
I have an android 9 app recently converted to Electron app.
For DataTable, I have enabled Print and Excel options. Excel upload is fine and exporting data.
But Print is not working.
Its giving the following error

```<code>TypeError: Cannot read property 'close' of undefined at _Api.action (buttons.print.js:140) at action (dataTables.buttons.js:559)
</code>```

I could see that win.document is null in  buttons.print.js.

Also if I build it as normal ANgular app ( ng serve) , print is working fine too

In Angular.JSON I have loaded the script in following order

```<code>"node_modules/jquery/dist/jquery.min.js",
"node_modules/jquery/dist/jquery.js",
"node_modules/datatables.net/js/jquery.dataTables.js",
"node_modules/datatables.net-buttons/js/dataTables.buttons.js",
"node_modules/datatables.net-buttons/js/buttons.colVis.js",
"node_modules/datatables.net-buttons/js/buttons.flash.js",
"node_modules/datatables.net-buttons/js/buttons.html5.js",
"node_modules/datatables.net-buttons/js/buttons.print.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"node_modules/jszip/dist/jszip.js"
</code>```

The package.json file is as follows

```<code>"dependencies": {
    "jquery": "^3.4.1",
    "datatables.net": "^1.10.19",
    "datatables.net-buttons": "^1.5.4",
    "datatables.net-buttons-dt": "^1.5.4",
    "datatables.net-dt": "^1.10.19",
    "@angular-devkit/build-angular": "^0.900.2",
    "@angular/animations": "~9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/localize": "9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.14",
    "@fortawesome/free-solid-svg-icons": "^5.7.1",
    "@ng-bootstrap/ng-bootstrap": "4.2.2",
    "angular-datatables": "^7.0.0",
    "bootstrap": "^4.3.1",
    "core-js": "^2.5.4",
    "cors": "^2.8.5",
    "express": "^4.16.4",
    "indexeddb-angular": "^0.1.8",
    "jszip": "^3.1.5",
    "luxon": "^1.16.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.23",
    "ngx-indexed-db": "^2.0.5",
    "ngx-material-timepicker": "^3.1.0",
    "ngx-multi-window": "0.3.2",
    "ngx-print": "^1.1.4",
    "popper.js": "^1.14.6",
    "rxjs": "~6.5.4",
    "tslib": "1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "8.4.1",
    "@angular-eslint/builder": "0.0.1-alpha.18",
    "@angular/cli": "9.0.2",
    "@angular/compiler-cli": "9.0.1",
    "@angular/language-service": "9.0.1",
    "@ngx-translate/core": "12.0.0",
    "@ngx-translate/http-loader": "4.0.0",
    "@types/datatables.net": "^1.10.14",
    "@types/datatables.net-buttons": "^1.4.0",
    "@types/jasmine": "3.3.16",
    "@types/jasminewd2": "2.0.8",
    "@types/jquery": "^3.3.29",
    "@types/mocha": "5.2.7",
    "@types/node": "12.11.1",
    "@typescript-eslint/eslint-plugin": "2.19.0",
    "@typescript-eslint/parser": "2.19.0",
    "chai": "4.2.0",
    "codelyzer": "5.1.2",
    "conventional-changelog-cli": "2.0.32",
    "core-js": "3.1.4",
    "cross-env": "7.0.0",
    "electron": "8.0.0",
    "electron-builder": "22.3.2",
    "electron-reload": "1.5.0",
    "eslint": "6.8.0",
    "eslint-plugin-import": "2.20.1",
    "jasmine-core": "3.4.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "4.2.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "2.1.1",
    "karma-electron": "6.3.0",
    "karma-jasmine": "2.0.1",
    "karma-jasmine-html-reporter": "1.4.2",
    "mocha": "6.2.2",
    "ngx-electron": "2.2.0",
    "npm-run-all": "4.1.5",
    "protractor": "~5.4.0",
    "spectron": "10.0.1",
    "ts-node": "8.3.0",
    "tslint": "~5.11.0",
    "typescript": "3.7.5",
    "wait-on": "4.0.0",
    "webdriver-manager": "12.1.7"
  },
</code>```

Any pointers on this will be helpful

答:
The information given in the post helped me ( angular application build in electron print a div shows blank window ).

The answer is : in main.ts for electron, need to add
nativeWindowOpen: true  as below.

```<code>win = new BrowserWindow({
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    webPreferences: {
      nodeIntegration: true,
      nativeWindowOpen: true, //**** add this**
      allowRunningInsecureContent: (serve) ? true : false,
    },
  });
</code>```

Body:
I have an android 9 app recently converted to Electron app.
For DataTable, I have enabled Print and Excel options. Excel upload is fine and exporting data.
But Print is not working.
Its giving the following error

TypeError: Cannot read property 'close' of undefined at _Api.action (buttons.print.js:140) at action (dataTables.buttons.js:559)

I could see that win.document is null in  buttons.print.js.

Also if I build it as normal ANgular app ( ng serve) , print is working fine too

In Angular.JSON I have loaded the script in following order

"node_modules/jquery/dist/jquery.min.js",
"node_modules/jquery/dist/jquery.js",
"node_modules/datatables.net/js/jquery.dataTables.js",
"node_modules/datatables.net-buttons/js/dataTables.buttons.js",
"node_modules/datatables.net-buttons/js/buttons.colVis.js",
"node_modules/datatables.net-buttons/js/buttons.flash.js",
"node_modules/datatables.net-buttons/js/buttons.html5.js",
"node_modules/datatables.net-buttons/js/buttons.print.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js",
"node_modules/jszip/dist/jszip.js"

The package.json file is as follows

"dependencies": {
    "jquery": "^3.4.1",
    "datatables.net": "^1.10.19",
    "datatables.net-buttons": "^1.5.4",
    "datatables.net-buttons-dt": "^1.5.4",
    "datatables.net-dt": "^1.10.19",
    "@angular-devkit/build-angular": "^0.900.2",
    "@angular/animations": "~9.0.1",
    "@angular/common": "~9.0.1",
    "@angular/compiler": "~9.0.1",
    "@angular/core": "~9.0.1",
    "@angular/forms": "~9.0.1",
    "@angular/localize": "9.0.1",
    "@angular/platform-browser": "~9.0.1",
    "@angular/platform-browser-dynamic": "~9.0.1",
    "@angular/router": "~9.0.1",
    "@fortawesome/angular-fontawesome": "^0.3.0",
    "@fortawesome/fontawesome-svg-core": "^1.2.14",
    "@fortawesome/free-solid-svg-icons": "^5.7.1",
    "@ng-bootstrap/ng-bootstrap": "4.2.2",
    "angular-datatables": "^7.0.0",
    "bootstrap": "^4.3.1",
    "core-js": "^2.5.4",
    "cors": "^2.8.5",
    "express": "^4.16.4",
    "indexeddb-angular": "^0.1.8",
    "jszip": "^3.1.5",
    "luxon": "^1.16.0",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.23",
    "ngx-indexed-db": "^2.0.5",
    "ngx-material-timepicker": "^3.1.0",
    "ngx-multi-window": "0.3.2",
    "ngx-print": "^1.1.4",
    "popper.js": "^1.14.6",
    "rxjs": "~6.5.4",
    "tslib": "1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-builders/custom-webpack": "8.4.1",
    "@angular-eslint/builder": "0.0.1-alpha.18",
    "@angular/cli": "9.0.2",
    "@angular/compiler-cli": "9.0.1",
    "@angular/language-service": "9.0.1",
    "@ngx-translate/core": "12.0.0",
    "@ngx-translate/http-loader": "4.0.0",
    "@types/datatables.net": "^1.10.14",
    "@types/datatables.net-buttons": "^1.4.0",
    "@types/jasmine": "3.3.16",
    "@types/jasminewd2": "2.0.8",
    "@types/jquery": "^3.3.29",
    "@types/mocha": "5.2.7",
    "@types/node": "12.11.1",
    "@typescript-eslint/eslint-plugin": "2.19.0",
    "@typescript-eslint/parser": "2.19.0",
    "chai": "4.2.0",
    "codelyzer": "5.1.2",
    "conventional-changelog-cli": "2.0.32",
    "core-js": "3.1.4",
    "cross-env": "7.0.0",
    "electron": "8.0.0",
    "electron-builder": "22.3.2",
    "electron-reload": "1.5.0",
    "eslint": "6.8.0",
    "eslint-plugin-import": "2.20.1",
    "jasmine-core": "3.4.0",
    "jasmine-spec-reporter": "4.2.1",
    "karma": "4.2.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "2.1.1",
    "karma-electron": "6.3.0",
    "karma-jasmine": "2.0.1",
    "karma-jasmine-html-reporter": "1.4.2",
    "mocha": "6.2.2",
    "ngx-electron": "2.2.0",
    "npm-run-all": "4.1.5",
    "protractor": "~5.4.0",
    "spectron": "10.0.1",
    "ts-node": "8.3.0",
    "tslint": "~5.11.0",
    "typescript": "3.7.5",
    "wait-on": "4.0.0",
    "webdriver-manager": "12.1.7"
  },

Any pointers on this will be helpful

Body:
The information given in the post helped me ( angular application build in electron print a div shows blank window ).

The answer is : in main.ts for electron, need to add
nativeWindowOpen: true  as below.

win = new BrowserWindow({
    x: 0,
    y: 0,
    width: size.width,
    height: size.height,
    webPreferences: {
      nodeIntegration: true,
      nativeWindowOpen: true, //**** add this**
      allowRunningInsecureContent: (serve) ? true : false,
    },
  });


问:
Find baked textures 3D model in Blender/Python
From a dataset of 3D models, I need to identify automatically which models have baked textures and which don't.
I'm using Blender-Python to manipulate the models, but I'm open to suggestions.

(There are too many models to open one by one)

答:
Well first, we need a way to identify whether an object is using a baked texture. Let's say all baked textures use an image with "baked" in its name, so let's look for image texture nodes.

The following will find all objects in the current blend file that uses an image texture with "baked" in the name.

```<code>import bpy

for obj in bpy.data.objects:
    # does object have a material?
    if len(obj.material_slots) < 1: continue
    for slot in obj.material_slots:
        # skip empty slots and mats that don't use nodes
        if not slot.material or not slot.material.use_nodes: continue
        for n in slot.material.node_tree.nodes:
            if n.type == 'TEX_IMAGE' and 'baked' in n.image.name:
                print(f'{obj.name} uses baked image {n.image.name}')
</code>```

As blender will clear out scripts as new blend files are opened, we need a script that will tell blender to open a file and run the previous script, then repeat for each file. To keep cross platform, we can use python for this as well.

```<code>from glob import glob
from subprocess import call

for blendFile in glob('*.blend'):
    arglist = [
    'blender',
    '--factory-startup',
    '-b',
    blendFile,
    '--python',
    'check_baked.py',
    ]
    print(f'Checking {blendFile}...')
    call(arglist)
</code>```

Body:
Well first, we need a way to identify whether an object is using a baked texture. Let's say all baked textures use an image with "baked" in its name, so let's look for image texture nodes.

The following will find all objects in the current blend file that uses an image texture with "baked" in the name.

import bpy

for obj in bpy.data.objects:
    # does object have a material?
    if len(obj.material_slots) < 1: continue
    for slot in obj.material_slots:
        # skip empty slots and mats that don't use nodes
        if not slot.material or not slot.material.use_nodes: continue
        for n in slot.material.node_tree.nodes:
            if n.type == 'TEX_IMAGE' and 'baked' in n.image.name:
                print(f'{obj.name} uses baked image {n.image.name}')

As blender will clear out scripts as new blend files are opened, we need a script that will tell blender to open a file and run the previous script, then repeat for each file. To keep cross platform, we can use python for this as well.

from glob import glob
from subprocess import call

for blendFile in glob('*.blend'):
    arglist = [
    'blender',
    '--factory-startup',
    '-b',
    blendFile,
    '--python',
    'check_baked.py',
    ]
    print(f'Checking {blendFile}...')
    call(arglist)


问:
How can I get a members list in a voice channel from my bot?
```<code>from django.shortcuts import render, redirect
import discord
import random
from discord.ext import commands

client = commands.Bot(command_prefix = '.')
channel = None

@client.event
async def on_ready():
    channel = client.get_channel(677999369642836037)

async def members_list(request):
    curMembers = []
    for member in channel.members:
        curMembers.append(member)

    return render(request, "discordTool/discordTool.html", {
        'members_list': curMembers,
    })

client.run('my token')
</code>```

This is my views.py of an app that supposes to show active members in a voice channel in my django site. However this doesn't work, can anyone help me or know a discord server about discord's API?

答:
This is because channel = client.get_channel(677999369642836037) sits inside the on_ready event, making it a local variable. It cannot be accessed outside the local coroutine.

You either need to make it a global variable, or move it to inside the members_list coroutine.

```<code>from django.shortcuts import render, redirect
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

async def members_list(request):
    channel = client.get_channel(677999369642836037)
    curMembers = []
    for member in channel.members:
        curMembers.append(member)

    return render(request, "discordTool/discordTool.html", {
        'members_list': curMembers,
    })

client.run('my token')
</code>```

Body:
from django.shortcuts import render, redirect
import discord
import random
from discord.ext import commands

client = commands.Bot(command_prefix = '.')
channel = None

@client.event
async def on_ready():
    channel = client.get_channel(677999369642836037)

async def members_list(request):
    curMembers = []
    for member in channel.members:
        curMembers.append(member)

    return render(request, "discordTool/discordTool.html", {
        'members_list': curMembers,
    })

client.run('my token')

This is my views.py of an app that supposes to show active members in a voice channel in my django site. However this doesn't work, can anyone help me or know a discord server about discord's API?

Body:
This is because channel = client.get_channel(677999369642836037) sits inside the on_ready event, making it a local variable. It cannot be accessed outside the local coroutine.

You either need to make it a global variable, or move it to inside the members_list coroutine.

from django.shortcuts import render, redirect
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

async def members_list(request):
    channel = client.get_channel(677999369642836037)
    curMembers = []
    for member in channel.members:
        curMembers.append(member)

    return render(request, "discordTool/discordTool.html", {
        'members_list': curMembers,
    })

client.run('my token')


问:
why cant I get this if statement to show?
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:</p>

```<code>#the main function
def main():
    print   #prints a blank line
    age = getAge ()
    weight = getWeight()
    birthMonth = getMonth()
    print
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if age <= 25:
        print 'Congratulations, the age is 25 or less.'

    if weight >= 128:
        print 'Congatulations, the weight is 128 or more.'

    if birthMonth == 'April':
        print 'Congratulations, the birth month is April.'

#calls main
main()
</code>```

答:
I have edited your code so that it will work correctly.</p>

```<code>def main():
    print   #prints a blank line
    age = getAge()
    weight = getWeight()
    birthMonth = getMonth()
    print()
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if int(age) <= 25:
        print('Congratulations, the age is 25 or less.')

    if int(weight) >= 128:
        print('Congatulations, the weight is 128 or more.')

    if birthMonth == 'April':
        print('Congratulations, the birth month is April.')

#calls main
main()
</code>```

Body:
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:

#the main function
def main():
    print   #prints a blank line
    age = getAge ()
    weight = getWeight()
    birthMonth = getMonth()
    print
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if age <= 25:
        print 'Congratulations, the age is 25 or less.'

    if weight >= 128:
        print 'Congatulations, the weight is 128 or more.'

    if birthMonth == 'April':
        print 'Congratulations, the birth month is April.'

#calls main
main()

Body:
I have edited your code so that it will work correctly.

def main():
    print   #prints a blank line
    age = getAge()
    weight = getWeight()
    birthMonth = getMonth()
    print()
    correctAnswers(age, weight, birthMonth)

#this function will input the age
def getAge():
    age = input('Enter your guess for age: ')
    return age

#thisfunction will input the weight
def getWeight():
    weight = input('Enter your guess for weight: ')
    return weight

#thisfunction will input the age
def getMonth():
    birthMonth = raw_input('Enter your guess for birth month: ')
    return birthMonth

#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
    if int(age) <= 25:
        print('Congratulations, the age is 25 or less.')

    if int(weight) >= 128:
        print('Congatulations, the weight is 128 or more.')

    if birthMonth == 'April':
        print('Congratulations, the birth month is April.')

#calls main
main()


问:
What are the pros and cons of the SVN plugins for Eclipse, Subclipse and Subversive?
SVN in Eclipse is spread into two camps. The SVN people have developed a plugin called Subclipse. The Eclipse people have a plugin called Subversive. Broadly speaking they both do the same things. What are the advantages and disadvantages of each?</p>

答:
FWIW, we are using an ancient version of SVN server (1.4 something), and I seem to remember that at one point there was an update to Subclipse that broke backward compatibility, and the gist was "nobody should be on such an old version of SVN anyway".

Subversive was the only one that seemed to be able to handle the older version. I can't remember the details, though, sorry.

OwnerDisplayName: rjmunro


问:
Replace New Lines in Node?
I'm trying to create a script to filter through a lot of lyric files. Here's the code I have:

Node.js

fs.readFile(filePath, 'utf-8', (err, data)=>{
    if (err) {
        console.log(err)
        return
    }
    data = data.replace(/\n[0-9]\n/, "Verse " + /\n[0-9]\n/)
    console.log(data)
    fs.writeFile(path.join(newDir, file), data, ()=>{
        console.log(file)
    })
})
```
<h2>Original Text File</h2>
```Title

1
Some lyrics

2
Some lyrics
```
<h2>What the new text file SHOULD look like</h2>
```Title

Verse 1
Some lyrics

Verse 2
Some lyrics
```

It can't seem to find the \n (newline), a verse number, \n (newline). Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter. Can anyone guide me on how could I filter through these?

答:
I suspect there is a \r prior to the \n. But you don't want to specify \n (or \r\n or \r?\n) anyway; use the multiline flag (m) and ^ and $ assertions. (You also need the g flag if you want to do more than just the first match.)

Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter.

The second, not third (it doesn't take a third). To use what you matched in the string, you can use $& (or pass in a function and use the first argument it receives). Details in the MDN docs (or, of course, the spec).

With m, g, and the assertions:

```<code>data = data.replace(/^[0-9]$/gm, "Verse $&");
</code>```

Live Example:

let data =
    "Title\r\n" +
    "\r\n" +
    "1\r\n" +
    "Some lyrics\r\n" +
    "\r\n" +
    "2\r\n" +
    "Some lyrics\r\n";

data = data.replace(/^[0-9]$/gm, "Verse $&");

console.log(data);
console.log(JSON.stringify(data));```

Title: Replace New Lines in Node?

Body:
I'm trying to create a script to filter through a lot of lyric files. Here's the code I have:

Node.js

fs.readFile(filePath, 'utf-8', (err, data)=>{
    if (err) {
        console.log(err)
        return
    }
    data = data.replace(/\n[0-9]\n/, "Verse " + /\n[0-9]\n/)
    console.log(data)
    fs.writeFile(path.join(newDir, file), data, ()=>{
        console.log(file)
    })
})

Original Text File

Title

1
Some lyrics

2
Some lyrics

What the new text file SHOULD look like

Title

Verse 1
Some lyrics

Verse 2
Some lyrics

It can't seem to find the \n (newline), a verse number, \n (newline). Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter. Can anyone guide me on how could I filter through these?

Body:
I suspect there is a \r prior to the \n. But you don't want to specify \n (or \r\n or \r?\n) anyway; use the multiline flag (m) and ^ and $ assertions. (You also need the g flag if you want to do more than just the first match.)

Also, obvious problem I'm not sure how to fix, the third parameter in .replace() probably isn't the same as the first parameter.

The second, not third (it doesn't take a third). To use what you matched in the string, you can use $& (or pass in a function and use the first argument it receives). Details in the MDN docs (or, of course, the spec).

With m, g, and the assertions:

data = data.replace(/^[0-9]$/gm, "Verse $&");

Live Example:

let data =
    "Title\r\n" +
    "\r\n" +
    "1\r\n" +
    "Some lyrics\r\n" +
    "\r\n" +
    "2\r\n" +
    "Some lyrics\r\n";

data = data.replace(/^[0-9]$/gm, "Verse $&");

console.log(data);
console.log(JSON.stringify(data));


问:
Exception occurred while initializing the installation: System.BadImageFormatException: Could not load file or assembly
I have Worker Services as Windows services which I am trying to install on a machine however it throws the below error when I try Installing it

```<code>Microsoft (R) .NET Framework Installation utility Version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe' or one of its dependencies. The module was expected to contain an assembly manifest..
</code>```

Below is the .csproj file content of the packages in use

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

```

<p>While looking at assembly binding log viewer I this error log.</p>

```** Assembly Binder Log Entry  (2/14/2020 @ 1:41:17 PM) ***

The operation failed.
Bind result: hr = 0x80131018. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Appbase = file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = InstallUtil.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/JNyingi/source/repos/SeSPWS/SeSPWS/bin/Release/netcoreapp3.0/SeSPWS.exe.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Entering run-from-source setup phase.
ERR: Error extracting manifest import from file (hr = 0x80131018).
ERR: Run-from-source setup phase failed with hr = 0x80131018.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

```

<p>I have installed the following runtime; .NET Core 3.0, ASP.NET Core 3.0 and Windows desktop 3.0. However, the service still fails to install even after upgrading to .NET Core 3.1 runtime.</p>

<p>Below is my build profile</p>

<p><img src="https://i.stack.imgur.com/XLSiI.png" alt="Build Setup"></p>

<p>I have built a similar worker service before which installed without any hustle; kindly I wish to resolve this error and deploy the service to the machine.</p>

<p><strong>EDIT</strong>
Below is My Program Class</p>

```public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateWebHostBuilder(args).Build().RunAsService();
            }
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1042);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });
    }
```

EDIT2

These are the NuGet packages in use for the service

答:
The error in majority of the cases is caused due to Incompatible bitness of your Application|Platform|Installutil|IIS

I've put together the various checks you can perform:

Settings of your main project Project > Properties > Uncheck Prefer 32 bit

Settings of your main project Project > Properties > /platform:AnyCpu or the BITness that you're targetting (x86) for 32bit

If you are referencing additional DLL(s) in your project, ensure there is no BITness mismatch

Validate your App.Config file and see if you have lines it it which specifies a different target runtime versus the one targetted by your app

Verify the bitness set by IIS > AppPool > Enable 32 bit applications

Unchecking "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions

Check the version of the InstallUtil that you are using to install the service

Check the StartUp of your project and see if its the intended one

Try to run InstallUtil is run as admin (As seen from another post)

Uncheck 64 bit version of IIS from VS Navigate to Visual Studio – Tools – Options – Projects and Solutions – Web Projects

Verify the bitness by viewing .CSProj file

You can narrow down further by identifying the assembly that caused this exception by using FusionLogging OR DependencyWalker tool, you will be able to tell which dll failed to loadat runtime

Further Reading:

This Medium post explains the process of creating a Windows Service in .NetCore

    EDIT: Break down of the Root Cause based on OP's post below

WebHostBuilder primarily allows us to configure and build a WebHost and is best suited for web apps.
But with .net core 2.1 a new option “generic” Host was introduced that enabled developers to create console app that can run background tasks, create services and handle messages.
See "Steve Gordons" article on Generic Host for Windows Services

When we create worker service template, we need a reference to Microsoft.Extensions.Hosting.WindowsServices from nuget
Now with this we can use IHostBuilder.UseWindowsService()

There are 2 ways of using this (see details next point): Background worker service(uses Microsoft.Net.Sdk.Worker), Web App(Microsoft.NET.Sdk.Web) service sample, the difference being Microsoft.Extensions.Hosting package is referenced explicitily in the former one
MSDN article that explains this

<Project Sdk="Microsoft.NET.Sdk.Web">
Now here you can use IWebHostBuilder
But be sure to use this for a web app-based service that uses the Razor Pages or MVC frameworks. A Good example

<Project Sdk="Microsoft.NET.Sdk.Worker">
This type suits the majority of the requirements for windows service creation where the service needs to executes background tasks

<RuntimeIdentifier> elements are used with Self Contained deployment and are used by .NET packages to represent platform-specific assets in NuGet packages

Body:
I have Worker Services as Windows services which I am trying to install on a machine however it throws the below error when I try Installing it

Microsoft (R) .NET Framework Installation utility Version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe' or one of its dependencies. The module was expected to contain an assembly manifest..

Below is the .csproj file content of the packages in use

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

While looking at assembly binding log viewer I this error log.

** Assembly Binder Log Entry  (2/14/2020 @ 1:41:17 PM) ***

The operation failed.
Bind result: hr = 0x80131018. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe
--- A detailed error log follows.

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Appbase = file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = InstallUtil.exe
Calling assembly : (Unknown).
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/JNyingi/source/repos/SeSPWS/SeSPWS/bin/Release/netcoreapp3.0/SeSPWS.exe.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Entering run-from-source setup phase.
ERR: Error extracting manifest import from file (hr = 0x80131018).
ERR: Run-from-source setup phase failed with hr = 0x80131018.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

I have installed the following runtime; .NET Core 3.0, ASP.NET Core 3.0 and Windows desktop 3.0. However, the service still fails to install even after upgrading to .NET Core 3.1 runtime.

Below is my build profile

I have built a similar worker service before which installed without any hustle; kindly I wish to resolve this error and deploy the service to the machine.

EDIT
Below is My Program Class

public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateWebHostBuilder(args).Build().RunAsService();
            }
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1042);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });
    }

EDIT2

These are the NuGet packages in use for the service


问:
Pushing data from socket.io into array
I have the following problem that I cant seem to work out. I'm trying to get an array of arrays from my socket.io emitter that is structured like follows:

```<code>[ [{...},{...},{...}] , [{...},{...}] , [{...}] ]
</code>```

Instead I get this:

I need all the arrays in one master array so that I can render bootstrap cards for each sub array.

Client side code:

```<code>const socket = io("http://localhost:5000");

    socket.on('data', (dta) => {
        handleData(dta.data);
    })

    function handleData(data) {
      const masterArray= [];
        masterArray.push(data);
        console.log(masterArray);
    }
</code>```

Server side code:

```<code>for(let i = 0 ; i < alarmpanels.length ; i++) {
const ElkClient = elkClient.ElkClient;
    let client = new ElkClient({
        connection: {
          name: alarmpanels[i].name,
          host: alarmpanels[i].host,
          port: alarmpanels[i].port,
          secure: alarmpanels[i].secure,
          zones: alarmpanels[i].zones
     }
  });

  connectClient(client);
}

  async function connectClient(client) {
    await client.connect();
    const zonesArray = client.options.connection.zones;
    const arr = [];
      try {
        const clhost = client.options.connection.host;
        const clport = client.options.connection.port;
        const clsecure = client.options.connection.secure;
        let data = await client.getArmingStatus();
        for (i = 0 ; i < zonesArray.length ; i ++) {
        const armUpState = await data.areas[i].armUpState;
        const clName = client.options.connection.name;
        const zoneName = zonesArray[i].name;
        const siteName = zonesArray[i].site;
        const clzone = zonesArray[i].zone;
        const totalPanels = zonesArray[i].length;

        const info = new PanelStatus(clhost, clport ,clsecure, clzone, siteName, clName, zoneName, armUpState, totalPanels);
        arr.push(info);
        }

      io.on('connection', (socket, req) => {
          socket.emit('data', {data: arr});
        })

      }
      catch (err) {
        console.log("Connection Lost!");
      }

    }
</code>```

答:
Your client code need slight changes

1) keep the masterArray declaration outside of handleData

2) When pushing to masterArray, use ... spread operator.

const masterArray = [];

/*

const socket = io("http://localhost:5000");

socket.on("data", dta => {
  handleData(dta.data);
});

*/

function handleData(data) {
  masterArray.push(...data);
}

handleData([{ a: 4 }, { b: 5 }]);
handleData([{ z: 4 }]);
handleData([{ p: 4 }, { q: 5 }, { r: 5 }]);

console.log(masterArray);```

Title: Pushing data from socket.io into array

Body:
I have the following problem that I cant seem to work out. I'm trying to get an array of arrays from my socket.io emitter that is structured like follows:

[ [{...},{...},{...}] , [{...},{...}] , [{...}] ]

Instead I get this:

I need all the arrays in one master array so that I can render bootstrap cards for each sub array.

Client side code:

const socket = io("http://localhost:5000");

    socket.on('data', (dta) => {
        handleData(dta.data);
    })

    function handleData(data) {
      const masterArray= [];
        masterArray.push(data);
        console.log(masterArray);
    }

Server side code:

for(let i = 0 ; i < alarmpanels.length ; i++) {
const ElkClient = elkClient.ElkClient;
    let client = new ElkClient({
        connection: {
          name: alarmpanels[i].name,
          host: alarmpanels[i].host,
          port: alarmpanels[i].port,
          secure: alarmpanels[i].secure,
          zones: alarmpanels[i].zones
     }
  });

  connectClient(client);
}

  async function connectClient(client) {
    await client.connect();
    const zonesArray = client.options.connection.zones;
    const arr = [];
      try {
        const clhost = client.options.connection.host;
        const clport = client.options.connection.port;
        const clsecure = client.options.connection.secure;
        let data = await client.getArmingStatus();
        for (i = 0 ; i < zonesArray.length ; i ++) {
        const armUpState = await data.areas[i].armUpState;
        const clName = client.options.connection.name;
        const zoneName = zonesArray[i].name;
        const siteName = zonesArray[i].site;
        const clzone = zonesArray[i].zone;
        const totalPanels = zonesArray[i].length;

        const info = new PanelStatus(clhost, clport ,clsecure, clzone, siteName, clName, zoneName, armUpState, totalPanels);
        arr.push(info);
        }

      io.on('connection', (socket, req) => {
          socket.emit('data', {data: arr});
        })

      }
      catch (err) {
        console.log("Connection Lost!");
      }

    }


问:
SpecFlow feature not found by Visual Studio Test Explorer
After installing SpecFlow via extensions into VS2013 Ultimate, and added SpecFlow and NUnit to the current Class Library project, creating a feature, and building successfully, the scenarios do not show up in Test Explorer as expected.  I've restarted Visual Studio, cleaned and rebuilt, nothing causes the scenarios to show up in Test Explorer.

Any tips?

```<code>Feature: SpecFlowFeature1

@mytag
Scenario: Scenario A
    Given X
    When Y
    Then Z

Scenario: Scenario B
    Given X
    When Y
    Then Z

Scenario: Scenario C
    Given X
    When Y
    Then Z
</code>```

答:
If you add this nuget package Specflow.Tools.MSBuild.Generation
into your project, .feature.cs files will be generated automatically
when you rebuild.

Body:
After installing SpecFlow via extensions into VS2013 Ultimate, and added SpecFlow and NUnit to the current Class Library project, creating a feature, and building successfully, the scenarios do not show up in Test Explorer as expected.  I've restarted Visual Studio, cleaned and rebuilt, nothing causes the scenarios to show up in Test Explorer.

Any tips?

Feature: SpecFlowFeature1

@mytag
Scenario: Scenario A
    Given X
    When Y
    Then Z

Scenario: Scenario B
    Given X
    When Y
    Then Z

Scenario: Scenario C
    Given X
    When Y
    Then Z


问:
How to save and download text file in Flutter web application
I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}
```

Can anyone help me to achieve this

答:
This method is based on manipulations with an HTML document.
Some additional packages should be imported:

import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart
```

<p>Code snippet:</p>

<pre class="lang-dart prettyprint-override"><code>final text = 'this is the text file';

// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
  ..href = url
  ..style.display = 'none'
  ..download = 'some_name.txt';
html.document.body.children.add(anchor);

// download
anchor.click();

// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);

</code>```

Here is DartPad demo.

Body:
I am new to Flutter and working in a flutter web application, My requirement is to create and download a text file. like below.

void getData() {
    List<int> bytes = utf8.encode('this is the text file');
    print(bytes); // Need to download this with txt file.
}

Can anyone help me to achieve this

Body:
This method is based on manipulations with an HTML document.
Some additional packages should be imported:

import 'dart:convert';
import 'dart:html' as html; // or package:universal_html/prefer_universal/html.dart

Code snippet:

final text = 'this is the text file';

// prepare
final bytes = utf8.encode(text);
final blob = html.Blob([bytes]);
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.document.createElement('a') as html.AnchorElement
  ..href = url
  ..style.display = 'none'
  ..download = 'some_name.txt';
html.document.body.children.add(anchor);

// download
anchor.click();

// cleanup
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);

Here is DartPad demo.


问:
Parsing XML files that do not have 'root' node in Python
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

```<code><Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>
</code>```

And this is my code on how to parse the XML files:

```<code>import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')
</code>```

The rest of the code is just writing to the output text file.

答:
I don't know if the Python parser supports DTDs, but if it does, then one approach is to define a simple wrapper document like this

```<code><!DOCTYPE root [
<!ENTITY e SYSTEM "realdata.xml">
]>
<root>&e;</root>
</code>```

and point the parser at this wrapper document instead of at realdata.xml

Body:
My client wants me to parse over 100,00 xml files and converting them into a text file.

I have successfully parse a couple of files and converting them into a text file. However I managed to do that by editing the xml and adding <root></root> in the xml file.

This would seem inefficient since I would have to edit nearly 100,00 xml files to achieve my desired result.

Is there anyway for my python code to recognize the first node and read it as the root node?

I have tried using the method showed in Python XML Parsing without root
,however I do not fully understand it and I do not know where to implement this.

The XML format is as follows:

<Thread>
   <ThreadID></ThreadID>
   <Title></Title>
   <InitPost>
        <UserID></UserID>
        <Date></Date>
        <icontent></icontent>
  </InitPost>
  <Post>
       <UserID></UserID>
       <Date></Date>
       <rcontent></rcontent>
  </Post>
</Thread>

And this is my code on how to parse the XML files:

import os
from xml.etree import ElementTree

saveFile = open('test3.txt','w')

for path, dirs, files in os.walk("data/sample"):
   for f in files:
    fileName = os.path.join(path, f)
    with open(fileName, "r", encoding="utf8") as myFile:
        dom = ElementTree.parse(myFile)

        thread = dom.findall('Thread')

        for t in thread:

            threadID = str(t.find('ThreadID').text)
            threadID = threadID.strip()

            title = str(t.find('Title').text)
            title = title.strip()

            userID = str(t.find('InitPost/UserID').text)
            userID = userID.strip()

            date = str(t.find('InitPost/Date').text)
            date = date.strip()

            initPost = str(t.find('InitPost/icontent').text)
            initPost = initPost.strip()

        post = dom.findall('Thread/Post')

The rest of the code is just writing to the output text file.

Body:
I don't know if the Python parser supports DTDs, but if it does, then one approach is to define a simple wrapper document like this

<!DOCTYPE root [
<!ENTITY e SYSTEM "realdata.xml">
]>
<root>&e;</root>

and point the parser at this wrapper document instead of at realdata.xml


问:
How to run ktor application?
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

```<code>plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}
</code>```

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?

答:
If it's not there, create a new one with the plus button.

You can select kotlin and then fill out the main class, etc.

Title: How to run ktor application?

Body:
I've created a Ktor application with Gradle and I followed the tutorial on https://ktor.io/quickstart/quickstart/gradle.html#initial.

At the end it says:

And then go to Run -> Edit Configurations select the blog.BlogAppKt
  configuration and change its Main class to:
  io.ktor.server.netty.EngineMain

Now when we run the new configuration, the application will start
  again.

I am searching for the option but could not find it:

The gradle file looks as follows:

plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "org.example"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "1.8"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}

Update

I'v tried following configuration:

But as you can, there is a error message.

What do I have to add to run the Ktor app?


问:
UpdateOrCreate on one to many relationship

UPDATED

i am trying to apply update_or_create method on parent table. Then on child table. But when the update_or_create method run on the child there is this error returns...

save() prohibited to prevent data loss due to unsaved related object
  'atom_presance'.

it's look like child doesn't know parent's update_or_create and can't get the foreign_key.

```<code>for i, fee in enumerate(fees):
   for j, item in enumerate(fee):
      projects = AtomPresance() #parent
      advertisements = Advertisements() #child

      project_name = {'project_name': item["title"]}

      kind = item["kind"]
      removed_price = {'removed_price': item[kind], "atom_presance":projects} #sending FOREIGN_KEY also

      obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)
      obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)
</code>```

what is the best way to use update_or_create on parent and child in this kind of situation.

答:
I got error when you are update_or_create second method in defaults values assign removed_price as dictionary put after the first creating
AtomPresance objects and assign key value in atom_presance=obj of removed_price dictionary

you have must pass the reference of parentmodel in childmodel creation replace below code with your code

```<code>for i, fee in enumerate(fees):
   for j, item in enumerate(fee):
      project_name = {'project_name': item["title"]}

      kind = item["kind"]

      obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)

      removed_price = {'removed_price': item[kind], "atom_presance":obj} #here change you need to assign the created obj that we create in above line

      obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)

</code>```

Body:
UPDATED

i am trying to apply update_or_create method on parent table. Then on child table. But when the update_or_create method run on the child there is this error returns...

save() prohibited to prevent data loss due to unsaved related object
  'atom_presance'.

it's look like child doesn't know parent's update_or_create and can't get the foreign_key.

for i, fee in enumerate(fees):
   for j, item in enumerate(fee):
      projects = AtomPresance() #parent
      advertisements = Advertisements() #child

      project_name = {'project_name': item["title"]}

      kind = item["kind"]
      removed_price = {'removed_price': item[kind], "atom_presance":projects} #sending FOREIGN_KEY also

      obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)
      obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)

what is the best way to use update_or_create on parent and child in this kind of situation.

Body:
I got error when you are update_or_create second method in defaults values assign removed_price as dictionary put after the first creating
AtomPresance objects and assign key value in atom_presance=obj of removed_price dictionary

you have must pass the reference of parentmodel in childmodel creation replace below code with your code

for i, fee in enumerate(fees):
   for j, item in enumerate(fee):
      project_name = {'project_name': item["title"]}

      kind = item["kind"]

      obj, created = AtomPresance.objects.update_or_create(project_name=item["title"], defaults=project_name)

      removed_price = {'removed_price': item[kind], "atom_presance":obj} #here change you need to assign the created obj that we create in above line

      obj, created = Advertisements.objects.update_or_create(saved_date=date, defaults=removed_price)


问:
stacked barplot returning individual bars
I am attempting to make a stacked bar plot and it is simply not working. I have attached my data and the script I have tried. My data is tab delimited and only has 4 rows of data. Color is suppose to be a method by which I can color my bar graph.

```<code>Person   Count   Color
Jim   35   Y
Jim   10   N
Jenny   12   Y
Jenny   25   N
</code>```

So what I am expecting is Jim's bars to stack on top of each other and have Jenny's next his stacked as well. But that is not what is occuring, the bars are present but they are besides each other despite belonging to the same person.

Code I have tried

```<code>barplot(count, col = color) ##this will get me the unstacked bars

###what I have seen as examples but I already have a table...
count = table (person, count)
count
barplot(count, col = color)
</code>```

答:
As @Edward correctly mentioned, you need a table, not data.frame. Just in case you need it (and for fun), you can use dplyr to cast it into a matrix and plot:

```<code>library(tidyr)
library(dplyr)

df %>% pivot_wider(values_from=Count,names_from=Person) %>% tibble::column_to_rownames("Color") %>%
{barplot(as.matrix(.),col=c("turquoise","orange"))}
</code>```

Body:
I am attempting to make a stacked bar plot and it is simply not working. I have attached my data and the script I have tried. My data is tab delimited and only has 4 rows of data. Color is suppose to be a method by which I can color my bar graph.

Person   Count   Color
Jim   35   Y
Jim   10   N
Jenny   12   Y
Jenny   25   N

So what I am expecting is Jim's bars to stack on top of each other and have Jenny's next his stacked as well. But that is not what is occuring, the bars are present but they are besides each other despite belonging to the same person.

Code I have tried

barplot(count, col = color) ##this will get me the unstacked bars

###what I have seen as examples but I already have a table...
count = table (person, count)
count
barplot(count, col = color)

Body:
As @Edward correctly mentioned, you need a table, not data.frame. Just in case you need it (and for fun), you can use dplyr to cast it into a matrix and plot:

library(tidyr)
library(dplyr)

df %>% pivot_wider(values_from=Count,names_from=Person) %>% tibble::column_to_rownames("Color") %>%
{barplot(as.matrix(.),col=c("turquoise","orange"))}


问:
Does bootstrap have builtin padding and margin classes?
Does Bootstrap have built-in padding and margin classes like pad-10, mar-left-10 or I have to add my own custom classes? For example, similar to the ones here at padding and margin tabs.

答:
These spacing notations are quite effective in custom changes. You can also use negative values there too. Official

Though we can use them whenever we want. Bootstrap Spacing


问:
Specflow test not discovered on test explorer c#
I have researched a lot before posting the question but I could not find a solution to fix my issue.

I am trying to use selenium to do automation testing, but the issue is that my test explorer is not picking up the specflow tests for some reason.

Here is what I am using:

c# .net core project

Specflow

Xunit

Selenium driver

Selenium Chrome Driver

NuGet Packages I have installed:

Selenium.Support

Selenium.WebDriver

Selenium.WebDriver.ChromeDriver

Specflow

Specflow.NetCore

Specflow.xUnit

SpecRun.Runner

xunit

xunit.core

xunit.runner.visualstudio

I also have the Specflow for Visual Studio 2017 installed.

I have installed and Uninstalled loads of NuGet packages to try and fix this issue. Anyone able to help me please?

答:
If you are encountering the problem, and have already installed Specflow.Tools.MSBuid.Generation NuGet package in your project, and you
intermittently lose your generated tests, then you should be aware that
there is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2

You can upgrade to a newer version of Specflow.Tools.MSBuild.Generation
or apply a workaround.

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

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

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

Body:
If you are encountering the problem, and have already installed Specflow.Tools.MSBuid.Generation NuGet package in your project, and you
intermittently lose your generated tests, then you should be aware that
there is a bug in Specflow.Tools.MSBuild.Generation Version=2.3.2

You can upgrade to a newer version of Specflow.Tools.MSBuild.Generation
or apply a workaround.

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

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

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


问:
Ending a Program Mid-Run
pythoncom.PumpMessages()

From what I understand this line basically tells the program to wait forever. For my purposes it seems to be working. However, I'd like to be able to end the program given the right stimulus. How would one go about ending the above line, or stopping the program from running any further.

答:
Here's an example of quitting the app using a timer thread:

```<code>import win32api
import win32con
import pythoncom
from threading import Timer

main_thread_id = win32api.GetCurrentThreadId()

def on_timer():
    win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);

t = Timer(5.0, on_timer) # Quit after 5 seconds
t.start()

pythoncom.PumpMessages()
</code>```

PostQuitMessage() will work only from the main thread, but then again the main thread is blocked, so it's not very useful by itself. You can only use it if you hook your own custom message handling into the message loop.

Title: Ending a Program Mid-Run

Body:
Here's an example of quitting the app using a timer thread:

import win32api
import win32con
import pythoncom
from threading import Timer

main_thread_id = win32api.GetCurrentThreadId()

def on_timer():
    win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);

t = Timer(5.0, on_timer) # Quit after 5 seconds
t.start()

pythoncom.PumpMessages()

PostQuitMessage() will work only from the main thread, but then again the main thread is blocked, so it's not very useful by itself. You can only use it if you hook your own custom message handling into the message loop.


问:
How to get rid of x and up/down arrow elements of a input date?

The only thing that I need showing up in the box there is the orange triangle, and I am not sure if I need CSS or something else to get rid of the two elements to the left of the triangle.

Is there a way to do so? I am just using the input type date.

Fiddle: http://jsfiddle.net/5M2PD/1/

答:
Chrome (v79):

```<code>input[type='date']::-webkit-clear-button,
input[type='date']::-webkit-inner-spin-button {
    display: none;
}
</code>```

Firefox (v73):

Firefox has only the clear button for date inputs. To remove it, the field should be made required.

```<code><input type=’date’ required=’required’ />
</code>```

Safari (v13):

Safari doesn’t support type=’date’.

Body:
Chrome (v79):

input[type='date']::-webkit-clear-button,
input[type='date']::-webkit-inner-spin-button {
    display: none;
}

Firefox (v73):

Firefox has only the clear button for date inputs. To remove it, the field should be made required.

<input type=’date’ required=’required’ />

Safari (v13):

Safari doesn’t support type=’date’.


问:
return type of generic, when to use <T>returnType<T> and when to just use returnType<T>?
In generic api, why sometimes a type parameter is written before the return type and sometimes it needs not?

Given the following two Steam API as example

```<code>Stream<T>   limit(long maxSize)
</code>```

and

```<code><R> Stream<R>   map(Function<? super T,? extends R> mapper)
</code>```

Why Stream.limit's return type can just be written as Stream<T> but not <T> Stream<T>?

When to use <T> returnType <T> and when to use returnType<T>?

答:
The first <R> in <R> Stream<R> is just another part of the method signature - the type parameters. You shouldn't view <R> Stream<R> as "one" thing, as you seem to have done in your question title.

The first <R> is just there to tell you what the type parameters of this method are, so map is a generic method. limit is not a generic method, because it does not have this part in its signature.

You might be confused about limit isn't a generic method, since it clearly returns something that has a generic parameter T in it. Well, T is actually the generic parameter of the enclosing class Stream<T>, so limit can't really return any other type than the Stream<T> on which it was called. If you call limit on a Stream, you can't expect it to give you a Stream. Therefore, limit is not generic.

Note that T is also used the parameter list of map.

when to use <T>returnType<T> and when to just use returnType<T>?

The big difference here is <T> returnType<T> makes the method generic. returnType<T> is not a generic method, and can only be used if T actually exists in the context.

Body:
In generic api, why sometimes a type parameter is written before the return type and sometimes it needs not?

Given the following two Steam API as example

Stream<T>   limit(long maxSize)

and

<R> Stream<R>   map(Function<? super T,? extends R> mapper)

Why Stream.limit's return type can just be written as Stream<T> but not <T> Stream<T>?

When to use <T> returnType <T> and when to use returnType<T>?

Body:
The first <R> in <R> Stream<R> is just another part of the method signature - the type parameters. You shouldn't view <R> Stream<R> as "one" thing, as you seem to have done in your question title.

The first <R> is just there to tell you what the type parameters of this method are, so map is a generic method. limit is not a generic method, because it does not have this part in its signature.

You might be confused about limit isn't a generic method, since it clearly returns something that has a generic parameter T in it. Well, T is actually the generic parameter of the enclosing class Stream<T>, so limit can't really return any other type than the Stream<T> on which it was called. If you call limit on a Stream<A>, you can't expect it to give you a Stream<B>. Therefore, limit is not generic.

Note that T is also used the parameter list of map.

when to use <T>returnType<T> and when to just use returnType<T>?

The big difference here is <T> returnType<T> makes the method generic. returnType<T> is not a generic method, and can only be used if T actually exists in the context.