问:
flask-migrate cannot drop table because other objects depend on it
Problem applying just created migration (Added db.Model) through Flask-Migrate (SQLAlchemy) for PostgresSQL DB.
The error itself:

```<code>sqlalchemy.exc.InternalError: (psycopg2.InternalError) cannot drop table parameter_subtype because other objects depend on it
</code>```

Full error stack trace is:

```<code>INFO  [alembic.autogenerate.compare] Detected removed foreign key (event_id) (id) on table stage_has_event
INFO  [alembic.autogenerate.compare] Detected removed column 'stage_has_event.event_id'
  Generating /app/migrations/versions/e224df1a4818_.py ... done
(venv) $ ./manage db upgrade
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade cadf22871ae0 -> e224df1a4818, empty message
Traceback (most recent call last):
  File "/app/venv/bin/flask", line 11, in <module>
    sys.exit(main())
  File "/app/venv/lib/python2.7/site-packages/flask_cli/cli.py", line 502, in main
    cli.main(args=args, prog_name=name)
  File "/app/venv/lib/python2.7/site-packages/flask_cli/cli.py", line 369, in main
    return AppGroup.main(self, *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/flask/cli.py", line 257, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/flask_migrate/cli.py", line 134, in upgrade
    _upgrade(directory, revision, sql, tag, x_arg)
  File "/app/venv/lib/python2.7/site-packages/flask_migrate/__init__.py", line 259, in upgrade
    command.upgrade(config, revision, sql=sql, tag=tag)
  File "/app/venv/lib/python2.7/site-packages/alembic/command.py", line 254, in upgrade
    script.run_env()
  File "/app/venv/lib/python2.7/site-packages/alembic/script/base.py", line 427, in run_env
    util.load_python_file(self.dir, 'env.py')
  File "/app/venv/lib/python2.7/site-packages/alembic/util/pyfiles.py", line 81, in load_python_file
    module = load_module_py(module_id, path)
  File "/app/venv/lib/python2.7/site-packages/alembic/util/compat.py", line 141, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "migrations/env.py", line 87, in <module>
    run_migrations_online()
  File "migrations/env.py", line 80, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/app/venv/lib/python2.7/site-packages/alembic/runtime/environment.py", line 836, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/app/venv/lib/python2.7/site-packages/alembic/runtime/migration.py", line 330, in run_migrations
    step.migration_fn(**kw)
  File "/app/migrations/versions/e224df1a4818_.py", line 21, in upgrade
    op.drop_table('parameter_subtype')
  File "<string>", line 8, in drop_table
  File "<string>", line 3, in drop_table
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/ops.py", line 1187, in drop_table
    operations.invoke(op)
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/base.py", line 319, in invoke
    return fn(self, operation)
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/toimpl.py", line 70, in drop_table
    operation.to_table(operations.migration_context)
  File "/app/venv/lib/python2.7/site-packages/alembic/ddl/impl.py", line 203, in drop_table
    self._exec(schema.DropTable(table))
  File "/app/venv/lib/python2.7/site-packages/alembic/ddl/impl.py", line 118, in _exec
    return conn.execute(construct, *multiparams, **params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 948, in execute
    return meth(self, multiparams, params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1009, in _execute_ddl
    compiled
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
    context)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
    exc_info
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/app`enter code here`/venv/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 507, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.InternalError: (psycopg2.InternalError) cannot drop table parameter_subtype because other objects depend on it
DETAIL:  constraint parameter_parameter_subtype_id_fkey on table parameter depends on table parameter_subtype
HINT:  Use DROP ... CASCADE to drop the dependent objects too.
 [SQL: '\nDROP TABLE parameter_subtype']
</code>```

This leads to table not created in PostgreSQL db and columns either.
Unsure what may have caused this problem and how to understand this Error message.

I did manually drop the tables and it helped. However how to be with migration.
Any Suggestions?

答:
I got the same error and what worked for me was to first drop the table in the database using the command:

```<code>$ DROP TABLE table_name;
</code>```

And then in the migration file in the upgrade() function delete or comment out the line where it says:

```<code>op.drop_table('table_name')
</code>```

Body:
Problem applying just created migration (Added db.Model) through Flask-Migrate (SQLAlchemy) for PostgresSQL DB.
The error itself:

sqlalchemy.exc.InternalError: (psycopg2.InternalError) cannot drop table parameter_subtype because other objects depend on it

Full error stack trace is:

INFO  [alembic.autogenerate.compare] Detected removed foreign key (event_id) (id) on table stage_has_event
INFO  [alembic.autogenerate.compare] Detected removed column 'stage_has_event.event_id'
  Generating /app/migrations/versions/e224df1a4818_.py ... done
(venv) $ ./manage db upgrade
INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.
INFO  [alembic.runtime.migration] Will assume transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade cadf22871ae0 -> e224df1a4818, empty message
Traceback (most recent call last):
  File "/app/venv/bin/flask", line 11, in <module>
    sys.exit(main())
  File "/app/venv/lib/python2.7/site-packages/flask_cli/cli.py", line 502, in main
    cli.main(args=args, prog_name=name)
  File "/app/venv/lib/python2.7/site-packages/flask_cli/cli.py", line 369, in main
    return AppGroup.main(self, *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 697, in main
    rv = self.invoke(ctx)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 1066, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 895, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/decorators.py", line 17, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/flask/cli.py", line 257, in decorator
    return __ctx.invoke(f, *args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/click/core.py", line 535, in invoke
    return callback(*args, **kwargs)
  File "/app/venv/lib/python2.7/site-packages/flask_migrate/cli.py", line 134, in upgrade
    _upgrade(directory, revision, sql, tag, x_arg)
  File "/app/venv/lib/python2.7/site-packages/flask_migrate/__init__.py", line 259, in upgrade
    command.upgrade(config, revision, sql=sql, tag=tag)
  File "/app/venv/lib/python2.7/site-packages/alembic/command.py", line 254, in upgrade
    script.run_env()
  File "/app/venv/lib/python2.7/site-packages/alembic/script/base.py", line 427, in run_env
    util.load_python_file(self.dir, 'env.py')
  File "/app/venv/lib/python2.7/site-packages/alembic/util/pyfiles.py", line 81, in load_python_file
    module = load_module_py(module_id, path)
  File "/app/venv/lib/python2.7/site-packages/alembic/util/compat.py", line 141, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "migrations/env.py", line 87, in <module>
    run_migrations_online()
  File "migrations/env.py", line 80, in run_migrations_online
    context.run_migrations()
  File "<string>", line 8, in run_migrations
  File "/app/venv/lib/python2.7/site-packages/alembic/runtime/environment.py", line 836, in run_migrations
    self.get_context().run_migrations(**kw)
  File "/app/venv/lib/python2.7/site-packages/alembic/runtime/migration.py", line 330, in run_migrations
    step.migration_fn(**kw)
  File "/app/migrations/versions/e224df1a4818_.py", line 21, in upgrade
    op.drop_table('parameter_subtype')
  File "<string>", line 8, in drop_table
  File "<string>", line 3, in drop_table
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/ops.py", line 1187, in drop_table
    operations.invoke(op)
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/base.py", line 319, in invoke
    return fn(self, operation)
  File "/app/venv/lib/python2.7/site-packages/alembic/operations/toimpl.py", line 70, in drop_table
    operation.to_table(operations.migration_context)
  File "/app/venv/lib/python2.7/site-packages/alembic/ddl/impl.py", line 203, in drop_table
    self._exec(schema.DropTable(table))
  File "/app/venv/lib/python2.7/site-packages/alembic/ddl/impl.py", line 118, in _exec
    return conn.execute(construct, *multiparams, **params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 948, in execute
    return meth(self, multiparams, params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py", line 68, in _execute_on_connection
    return connection._execute_ddl(self, multiparams, params)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1009, in _execute_ddl
    compiled
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1200, in _execute_context
    context)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1413, in _handle_dbapi_exception
    exc_info
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/app/venv/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
    context)
  File "/app`enter code here`/venv/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 507, in do_execute
    cursor.execute(statement, parameters)
sqlalchemy.exc.InternalError: (psycopg2.InternalError) cannot drop table parameter_subtype because other objects depend on it
DETAIL:  constraint parameter_parameter_subtype_id_fkey on table parameter depends on table parameter_subtype
HINT:  Use DROP ... CASCADE to drop the dependent objects too.
 [SQL: '\nDROP TABLE parameter_subtype']

This leads to table not created in PostgreSQL db and columns either.
Unsure what may have caused this problem and how to understand this Error message.

I did manually drop the tables and it helped. However how to be with migration.
Any Suggestions?

Body:
I got the same error and what worked for me was to first drop the table in the database using the command:

$ DROP TABLE table_name;

And then in the migration file in the upgrade() function delete or comment out the line where it says:

op.drop_table('table_name')


来源: stackexchange

问:
How to compile a Python package to a dll
Well, I have a Python package. I need to compile it as dll before distribute it in a way easily importable. How? You may suggest that *.pyc. But I read somewhere any *.pyc can be easily decompiled!

Update:
Follow these:

1) I wrote a python package

2) want to distribute it

3) do NOT want distribute the source

4) *.pyc is decompilable >> source can be extracted!

5) dll is standard

答:
If your only goal is to hide your source code, it is much simpler to just compile your code to an executable(use PyInstaller, for example), and use an module with readable source for communication.
NOTE: You might need more converter functions as shown in this example.
Example:
Module:

```<code>import subprocess
import codecs
def _encode_str(str):
    encoded=str.encode("utf-32","surrogatepass")
    return codecs.encode(encoded,"base64").replace(b"\n",b"")
def _decode_str(b64):
    return codecs.decode(b64,"base64").decode("utf-32","surrogatepass")
def strlen(s:str):#return length of str;int
    proc=subprocess.Popen(["path_to_your_exe.exe","strlen",_encode_str(str).decode("ascii")],stdout=subprocess.PIPE)
    return int(proc.stdout.read())
def random_char_from_string(str):
    proc=subprocess.Popen(["path_to_your_exe.exe","randchr",_encode_str(str).decode("ascii")],stdout=subprocess.PIPE)
    return _decode_str(proc.stdout.read())
</code>```

Executable:

```<code>import sys
import codecs
import random
def _encode_str(str):
    encoded=str.encode("utf-32","surrogatepass")
    return codecs.encode(encoded,"base64").replace(b"\n",b"")
def _decode_str(b64):
    return codecs.decode(b64,"base64").decode("utf-32","surrogatepass")
command=sys.argv[1]
if command=="strlen":
    s=_decode_str(sys.argv[2].encode("ascii"))
    print(len(str))
if command=="randchr":
    s_decode_str(sys.argv[2].encode("ascii"))
    print(_encode_str(random.choice(s)).decode("ascii"))
</code>```

You might also want to think about compiling different executables for different platforms, if your package isn't a windows-only package anyways.

ContentLicense: CC BY-SA 3.0

Body:
If your only goal is to hide your source code, it is much simpler to just compile your code to an executable(use PyInstaller, for example), and use an module with readable source for communication.
NOTE: You might need more converter functions as shown in this example.
Example:
Module:

import subprocess
import codecs
def _encode_str(str):
    encoded=str.encode("utf-32","surrogatepass")
    return codecs.encode(encoded,"base64").replace(b"\n",b"")
def _decode_str(b64):
    return codecs.decode(b64,"base64").decode("utf-32","surrogatepass")
def strlen(s:str):#return length of str;int
    proc=subprocess.Popen(["path_to_your_exe.exe","strlen",_encode_str(str).decode("ascii")],stdout=subprocess.PIPE)
    return int(proc.stdout.read())
def random_char_from_string(str):
    proc=subprocess.Popen(["path_to_your_exe.exe","randchr",_encode_str(str).decode("ascii")],stdout=subprocess.PIPE)
    return _decode_str(proc.stdout.read())

Executable:

import sys
import codecs
import random
def _encode_str(str):
    encoded=str.encode("utf-32","surrogatepass")
    return codecs.encode(encoded,"base64").replace(b"\n",b"")
def _decode_str(b64):
    return codecs.decode(b64,"base64").decode("utf-32","surrogatepass")
command=sys.argv[1]
if command=="strlen":
    s=_decode_str(sys.argv[2].encode("ascii"))
    print(len(str))
if command=="randchr":
    s_decode_str(sys.argv[2].encode("ascii"))
    print(_encode_str(random.choice(s)).decode("ascii"))

You might also want to think about compiling different executables for different platforms, if your package isn't a windows-only package anyways.

ContentLicense: CC BY-SA 4.0


问:
Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors
I have a Spring Boot WAR application perfectly working under Tomcat 8.0.39 on AWS. After issuing sudo service tomcat8 stop, upgrading to Tomcat 8.0.41 through sudo yum update, and rebooting the instance, the application does not start. In the catalina log file, I see a ton of exceptions of the type:

```<code>19-Feb-2017 10:27:15.326 WARNING [localhost-startStop-1] org.apache.tomcat.util.
scan.StandardJarScanner.scan Failed to scan [file:/usr/share/java/tomcat8/javax.
annotation-api.jar] from classloader hierarchy
 java.io.FileNotFoundException: /usr/share/java/tomcat8/javax.annotation-api.jar
 (No such file or directory)
</code>```

Here are the files Tomcat complains about:

```<code>javax.annotation-api.jar
jsr181-api.jar
jaxb-api.jar
javax.xml.soap-api.jar
FastInfoset.jar
mimepull.jar
saaj-impl.jar
stax2-api.jar
woodstox-core-asl.jar
jaxb-core-2.2.10-b140802.1033.jar
jaxb-api-2.2.12-b140109.1041.jar
istack-commons-runtime-2.19.jar
txw2-2.2.10-b140802.1033.jar
hk2-core.jar
class-model.jar
config.jar
auto-depends.jar
javax.inject.jar
hk2-api.jar
osgi-resource-locator.jar
tiger-types.jar
bean-validator.jar
jtype.jar
</code>```

Any suggestions on how to fix this?

Update #1:

Some of the above files belong to jaxws-ri. It turned out that I had some (10), but not all (23), of the jars from JAX-WS RI 2.2.10 lib directory copied into Tomcat's lib directory. After copying the missing 13 jars, the list of files Tomcat complains about in the catalina log file has shrunk to:

```<code>jaxb-core-2.2.10-b140802.1033.jar
jaxb-api-2.2.12-b140109.1041.jar
istack-commons-runtime-2.19.jar
txw2-2.2.10-b140802.1033.jar
hk2-core.jar
class-model.jar
config.jar
auto-depends.jar
javax.inject.jar
hk2-api.jar
osgi-resource-locator.jar
tiger-types.jar
bean-validator.jar
jtype.jar
</code>```

(Exceptions for the above files are repeated several times in the log file. Looks like the scanner is invoked repeatedly at startup, perhaps scanning different class paths.)

This tells me that with the transition from 8.0.39 to 8.0.41, Tomcat suddenly became very picky about the presence of all referenced jars, even though the application works perfectly fine without many of them. In addition, Tomcat appears to be very particular about specific builds of some jars (e.g. see the jaxb-core... and jaxb-api... jars above).

Now, to fix this I could try to find all these missing jars and copy them to Tomcat's lib directory. However, I see no way of assuring the proper source for some of them due to generic names, such as config.jar, or missing version numbers.

So, is there a way to prevent Tomcat's scan.StandardJarScanner.scan from being so picky about all these jars?

Update #2:

It turns out that in Tomcat 8.0.38, a setting was added to control jar scanning, the value of which defaults to true. To turn scanning off, add the following line in context.xml:

```<code><Context>
  ...
  <JarScanner scanManifest="false"/>
</Context>
</code>```

For details, see
Provide an option to disable processing of Class-Path entry in a jar's manifest file.

答:
you can add the below line

I had the same issue

server.tomcat.additional-tld-skip-patterns=*.jar

In application.properties file

Body:
I have a Spring Boot WAR application perfectly working under Tomcat 8.0.39 on AWS. After issuing sudo service tomcat8 stop, upgrading to Tomcat 8.0.41 through sudo yum update, and rebooting the instance, the application does not start. In the catalina log file, I see a ton of exceptions of the type:

19-Feb-2017 10:27:15.326 WARNING [localhost-startStop-1] org.apache.tomcat.util.
scan.StandardJarScanner.scan Failed to scan [file:/usr/share/java/tomcat8/javax.
annotation-api.jar] from classloader hierarchy
 java.io.FileNotFoundException: /usr/share/java/tomcat8/javax.annotation-api.jar
 (No such file or directory)

Here are the files Tomcat complains about:

javax.annotation-api.jar
jsr181-api.jar
jaxb-api.jar
javax.xml.soap-api.jar
FastInfoset.jar
mimepull.jar
saaj-impl.jar
stax2-api.jar
woodstox-core-asl.jar
jaxb-core-2.2.10-b140802.1033.jar
jaxb-api-2.2.12-b140109.1041.jar
istack-commons-runtime-2.19.jar
txw2-2.2.10-b140802.1033.jar
hk2-core.jar
class-model.jar
config.jar
auto-depends.jar
javax.inject.jar
hk2-api.jar
osgi-resource-locator.jar
tiger-types.jar
bean-validator.jar
jtype.jar

Any suggestions on how to fix this?

Update #1:

Some of the above files belong to jaxws-ri. It turned out that I had some (10), but not all (23), of the jars from JAX-WS RI 2.2.10 lib directory copied into Tomcat's lib directory. After copying the missing 13 jars, the list of files Tomcat complains about in the catalina log file has shrunk to:

jaxb-core-2.2.10-b140802.1033.jar
jaxb-api-2.2.12-b140109.1041.jar
istack-commons-runtime-2.19.jar
txw2-2.2.10-b140802.1033.jar
hk2-core.jar
class-model.jar
config.jar
auto-depends.jar
javax.inject.jar
hk2-api.jar
osgi-resource-locator.jar
tiger-types.jar
bean-validator.jar
jtype.jar

(Exceptions for the above files are repeated several times in the log file. Looks like the scanner is invoked repeatedly at startup, perhaps scanning different class paths.)

This tells me that with the transition from 8.0.39 to 8.0.41, Tomcat suddenly became very picky about the presence of all referenced jars, even though the application works perfectly fine without many of them. In addition, Tomcat appears to be very particular about specific builds of some jars (e.g. see the jaxb-core... and jaxb-api... jars above).

Now, to fix this I could try to find all these missing jars and copy them to Tomcat's lib directory. However, I see no way of assuring the proper source for some of them due to generic names, such as config.jar, or missing version numbers.

So, is there a way to prevent Tomcat's scan.StandardJarScanner.scan from being so picky about all these jars?

Update #2:

It turns out that in Tomcat 8.0.38, a setting was added to control jar scanning, the value of which defaults to true. To turn scanning off, add the following line in context.xml:

<Context>
  ...
  <JarScanner scanManifest="false"/>
</Context>

For details, see
Provide an option to disable processing of Class-Path entry in a jar's manifest file.


问:
using two consecutive values from a list in each iteration
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.  </p>

```<code>import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :
</code>```

答:
Change the top of your Bezier function to look like

```<code>def Bezier(x_n, p0, p3) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    p1 = p0
    p2 = p3
</code>```

getting rid of that loop and the plist completely.

Then, in your time function (from my answer to your previous question getting a boundary of an item from another list), change it to look like:

```<code>def time() :
    tlist = [0.0, 0.12, 0.16, 0.2, 0.31, 0.34, 0.38, 0.46, 0.51] # list of start time for the phonemes
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    total_frames = math.floor(tlist[-1] / 0.04)
    t_u = 0.0
    i = 0
    while i < len(tlist) - 1:
        # if the number is in the range
        # do the calculations and move to the next number
        if t_u > tlist[i] and t_u < tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is between',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            poly = poly_coeff(tlist[i], tlist[i + 1], t_u)
            Newton(poly, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number is at the lower boundary of the range no need of calculation as u = 0
        elif t_u == tlist[i] :
            print "\n The t_u value:", t_u, 'is on the boundary of',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            print "u : 0"
            Bezier(0, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number is at the upper boundary of the range no need of calculation as u = 1
        elif t_u == tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is on the boundary of',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            print " u : 1"
            Bezier(1, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number isn't in the range, move to the next range
        else :
            i += 1
</code>```

The only changes are putting the plist there and passing the plist values to Newton and Bezier.

The only changes to you Newton function are to change the first line to

```<code>def Newton(poly, p0, p3):
</code>```

and the last line to

```<code>    Bezier(x_n, p0, p3)
</code>```

Body:
I have posted a part of my code below. Newton() function calls Bezier() function. The Bezier() function has a list from where I get p0 and p3. What I am trying to do is, in 1st iteration the program should take the first and second items from the plist as p0 and p3. Then in 2nd iteration, p0 and p3 are the second and third items and so on. With each iteration, the p0 and p3 values should change. It's like the new p0 is the old p3. I could not put this in the code properly. Thank you.

import math

w = 1.0

def Newton(poly):
    """ Returns a root of the polynomial"""
    x = 0.5  # initial guess value
    counter = 0
    epsilon = 0.000000000001
    poly_diff = poly_differentiate(poly)

    while True:
        x_n = x - (float(poly_substitute(poly, x)) / float(poly_substitute(poly_diff, x)))
        counter += 1
        if abs(x_n - x) < epsilon :
            break
        x = x_n
        print "\tIteration " , counter , " : ", x_n

    print "u: ", x_n
    Bezier(x_n)

def Bezier(x_n) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    for i in range(len(plist) - 1) :
        p0 = plist[i]
        p3 = plist[i + 1]
        p1 = p0
        p2 = p3
        print p0, p3
        p_u = math.pow(1 - u, 3) * p0 + 3 * u * math.pow(1 - u, 2) * p1 \
            + 3 * (1 - u) * math.pow(u, 2) * p2 + math.pow(u, 3) * p3
        p_u = p_u * w
        d = math.pow(1 - u, 3) * w + 3 * u * w * math.pow(1 - u, 2) + 3 * (1 - u) * w * math.pow(u, 2) + math.pow(u, 3) * w
        p_u = p_u / d

    print "p(u): ", p_u
    return plist

if __name__ == "__main__" :

Body:
Change the top of your Bezier function to look like

def Bezier(x_n, p0, p3) :
    """ Calculating sampling points using rational bezier curve equation"""
    u = x_n
    p1 = p0
    p2 = p3

getting rid of that loop and the plist completely.

Then, in your time function (from my answer to your previous question getting a boundary of an item from another list), change it to look like:

def time() :
    tlist = [0.0, 0.12, 0.16, 0.2, 0.31, 0.34, 0.38, 0.46, 0.51] # list of start time for the phonemes
    plist = [0.5, 0.1, 0.4, 0.35, 0.8, 0.6, 1.0, 0.2, 0.7, 0.9] # list of parameter values of the phonemes

    total_frames = math.floor(tlist[-1] / 0.04)
    t_u = 0.0
    i = 0
    while i < len(tlist) - 1:
        # if the number is in the range
        # do the calculations and move to the next number
        if t_u > tlist[i] and t_u < tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is between',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            poly = poly_coeff(tlist[i], tlist[i + 1], t_u)
            Newton(poly, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number is at the lower boundary of the range no need of calculation as u = 0
        elif t_u == tlist[i] :
            print "\n The t_u value:", t_u, 'is on the boundary of',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            print "u : 0"
            Bezier(0, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number is at the upper boundary of the range no need of calculation as u = 1
        elif t_u == tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is on the boundary of',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            print " u : 1"
            Bezier(1, plist[i], plist[i+1])
            t_u = t_u + 0.04 # regular time interval

        # if the number isn't in the range, move to the next range
        else :
            i += 1

The only changes are putting the plist there and passing the plist values to Newton and Bezier.

The only changes to you Newton function are to change the first line to

def Newton(poly, p0, p3):

and the last line to

    Bezier(x_n, p0, p3)


问:
How to create global variable as dso_local in llvm ir builder for c++?
I am trying to create a global variable that looks like the following using the c++ llvm ir builder:

```<code>@test = dso_local global i8* null, align 8
</code>```

The problem is when I create a global variable using the following code:

auto global_variable = TheModule->getOrInsertGlobal("gvar", llvm::Type::getInt8PtrTy(TheContext))
```

there are no options that allow me to set the global variable to my desired syntax. I would like to know how I would go about creating that global variable using the llvm ir builder for c++.

答:
You can simply use the GlobalValue::setDSOLocal function to mark a global variable or a function as dso_local.

For example:

```<code>Function *randFunc = (Function*)M.getOrInsertFunction("rand", FunctionType::getInt32Ty(*CONTEXT)).getCallee();
randFunc->setDSOLocal(true);
CallInst *rand = CallInst::Create(randFunc->getFunctionType(), randFunc, "", I);
</code>```

Body:
I am trying to create a global variable that looks like the following using the c++ llvm ir builder:

@test = dso_local global i8* null, align 8

The problem is when I create a global variable using the following code:

auto global_variable = TheModule->getOrInsertGlobal("gvar", llvm::Type::getInt8PtrTy(TheContext))

there are no options that allow me to set the global variable to my desired syntax. I would like to know how I would go about creating that global variable using the llvm ir builder for c++.

Body:
You can simply use the GlobalValue::setDSOLocal function to mark a global variable or a function as dso_local.

For example:

Function *randFunc = (Function*)M.getOrInsertFunction("rand", FunctionType::getInt32Ty(*CONTEXT)).getCallee();
randFunc->setDSOLocal(true);
CallInst *rand = CallInst::Create(randFunc->getFunctionType(), randFunc, "", I);


问:
How to toggle between booleans (in a list or tuple)?

i = True
j = False
t = (i,j)
for i in t:
    if i:
        i = not i

print (t)
(True, False)
```

For example, I want to change all values in a tuple to False, no matter the element was True or False before. How can I realise that?

答:
```<code>i = True
j = False
t = (i,j)
result = ()
for i in range(len(t)):
    result = result + (False,)

print(result)
</code>```

Body:
i = True
j = False
t = (i,j)
for i in t:
    if i:
        i = not i

print (t)
(True, False)

For example, I want to change all values in a tuple to False, no matter the element was True or False before. How can I realise that?


问:
When do custom table view cells dealloc?
I was under the impression that table view cells never got dealloced until the app crash because you are able to resuse them. But when I was profiling my table view, I realized that something was calling dealloc on my custom cell. What exactly dealloc's custom cells and can I stop it?</p>

答: Table views create and shed cells as needed.  This is to allow for very long lists to be scrolled through without storing them all in memory.  A virtually infinite scrollable list is possible.  A convenient way to retain your custom cells for the table view's lifespan is to add them to a mutable array upon creation.  Before creating, look in the array to see if it already exists.</p>


问:
How can I align an Icon to top of Text?

This is how I want this to look like

Notice that the text is always a number.

How can I align the top of the Heart to the red line (top of text)?

If I can remove the font padding (over the red line and below the number) this also could work for me fine but I do not know how to do this.

This is my code

Row {
            Text(
                pulse.toString(),
                modifier = Modifier
                    .background(Color.Gray),
                fontSize = 60.sp,
                color = vitalModifier.color)
            Spacer(modifier = Modifier.width(10.dp))
            Icon(
                modifier = Modifier
                    .background(Color.Green)
                    .alignBy(LastBaseline),
                painter = painterResource(R.drawable.ic_heart),
                contentDescription = null,
                tint = vitalModifier.color)
        }
```

答:
You can use BadgedBox to achieve this

```<code>BadgedBox(badge = { Badge { Text("8") } }) {
                    Icon(
                        Icons.Filled.Favorite,
                        contentDescription = "Favorite"
                    )
                }

</code>```

https://dev.to/farhanroy/jetpack-compose-badge-18ho

Title: How can I align an Icon to top of Text?

Body:
You can use BadgedBox to achieve this

BadgedBox(badge = { Badge { Text("8") } }) {
                    Icon(
                        Icons.Filled.Favorite,
                        contentDescription = "Favorite"
                    )
                }

https://dev.to/farhanroy/jetpack-compose-badge-18ho


问:
Invalid Bot Token, discord.js
I'm new to discord.js and I have no clue why I'm getting this error:

Uncaught Error [TOKEN_INVALID]: An invalid token was provided.

my bot.js file

```<code>    const { Client, Intents } = require('discord.js');
    const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

    client.on('ready', () => {
        console.log(`Successfully Logged in as ${client.user.tag}!`);
    });

    client.login(process.env.TOKEN);
</code>```

.env file

```<code>TOKEN='my Bot token here'
</code>```

I'm 100% sure that my bot token is correct/valid, I have also tried revoking it and copy-pasting the new token several times, but I still get the same error... I have searched up nearly everywhere on the net and I still haven't found a solution to my problem.

package.json file

```<code>{
  "dependencies": {
    "discord.js": "^13.6.0",
    "dotenv": "^16.0.0"
  }
}
</code>```

答:
Did you initialize the env to be used in your file?

You will have to use dotenv package.

Put require('dotenv').config() at the top of your file and you would be good to go

Title: Invalid Bot Token, discord.js

Body:
I'm new to discord.js and I have no clue why I'm getting this error:

Uncaught Error [TOKEN_INVALID]: An invalid token was provided.

my bot.js file

    const { Client, Intents } = require('discord.js');
    const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

    client.on('ready', () => {
        console.log(`Successfully Logged in as ${client.user.tag}!`);
    });

    client.login(process.env.TOKEN);

.env file

TOKEN='my Bot token here'

I'm 100% sure that my bot token is correct/valid, I have also tried revoking it and copy-pasting the new token several times, but I still get the same error... I have searched up nearly everywhere on the net and I still haven't found a solution to my problem.

package.json file

{
  "dependencies": {
    "discord.js": "^13.6.0",
    "dotenv": "^16.0.0"
  }
}


问:
Trouble with python iteration of knn scores
Im new to python and sklearn and im still trying to figure out What exactly does lambda do and how would I go about getting the scores from my test data set, if anyone has any helpful tips that would be great, thank you!

Question: Now we will write a function that will initialize, fit and return score on test data for given values of k and Plot result
Use values from 1 to 25(inclusive) and get score and plot as a bar graph
Hint : you can use map or you can use simple loops

```<code>import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

def returnScore(k, xtrain, xtest, ytrain, ytest):
  knn = KNeighborsClassifier(n_neighbors=k)
  knn.fit(xtrain, ytrain)
  return knn.score(xtest, ytest)

result = [*map(lambda i:returnScore(i,?,?,?,?), range(1,25))]
print(result)
plt.plot(result)
</code>```

答:
The scores are what knn.score() gives you. Basically is what you get in the result array. lambda functions in Python are anonymous functions. So you could equivalently write

```<code>def getscores(k):
    ...
    return returnScore(k,?,?,?,?)

result = [*map(getscores, range(1,25))]
</code>```

but, in this case, it is easier to read when you use lambda functions. See How are lambdas useful?

Body:
Im new to python and sklearn and im still trying to figure out What exactly does lambda do and how would I go about getting the scores from my test data set, if anyone has any helpful tips that would be great, thank you!

Question: Now we will write a function that will initialize, fit and return score on test data for given values of k and Plot result
Use values from 1 to 25(inclusive) and get score and plot as a bar graph
Hint : you can use map or you can use simple loops

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix

def returnScore(k, xtrain, xtest, ytrain, ytest):
  knn = KNeighborsClassifier(n_neighbors=k)
  knn.fit(xtrain, ytrain)
  return knn.score(xtest, ytest)

result = [*map(lambda i:returnScore(i,?,?,?,?), range(1,25))]
print(result)
plt.plot(result)

Body:
The scores are what knn.score() gives you. Basically is what you get in the result array. lambda functions in Python are anonymous functions. So you could equivalently write

def getscores(k):
    ...
    return returnScore(k,?,?,?,?)

result = [*map(getscores, range(1,25))]

but, in this case, it is easier to read when you use lambda functions. See How are lambdas useful?


问:
Scale and center div to fit on all screens
I want to scale and center this div element to look good on all screens. I tried height:x% but it doesn't work. Only scaling it with px works. Any ideas why?

body {
    text-align: center;
}

div {
    display: block;
    justify-content: center;
    margin: auto;
    border-radius: 25px;
    height: 100px;
    width: 50%;
    background-color: aqua;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>

        <link rel="stylesheet" href="styles.css">
    </head>
    <body>

        <div>
            <h1>Sample</h1>
        </div>

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

答:
You can use the global reset * { margin: 0; margin: 0; } to reset the margin and padding of all element and set width and height of the body respectively 100vw and 100vh this will allow the body to expand and take all the space visible inside of your browser.

after that you can also set the width and height of the div to 100% for each to take all spaces ans set the display property to flex to use the Flexbox layout and set align-items:center; and justify-content: center; this will put all element which are in the div in the center of the screen

* {
    margin: 0;
    padding: 0;
}

body {
    height: 100vh;
    width: 100vw;
}

div {
    width: 100%;
    height: 100%;
    display: flex;
    align-items:center;
    justify-content: center;
    background-color: aqua;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <h1>Sample</h1>
</div></code>```

Body:
I want to scale and center this div element to look good on all screens. I tried height:x% but it doesn't work. Only scaling it with px works. Any ideas why?

body {
    text-align: center;
}

div {
    display: block;
    justify-content: center;
    margin: auto;
    border-radius: 25px;
    height: 100px;
    width: 50%;
    background-color: aqua;
}

        <link rel="stylesheet" href="styles.css">

Sample

Body:
You can use the global reset * { margin: 0; margin: 0; } to reset the margin and padding of all element and set width and height of the body respectively 100vw and 100vh this will allow the body to expand and take all the space visible inside of your browser.

after that you can also set the width and height of the div to 100% for each to take all spaces ans set the display property to flex to use the Flexbox layout and set align-items:center; and justify-content: center; this will put all element which are in the div in the center of the screen

* {
    margin: 0;
    padding: 0;
}

body {
    height: 100vh;
    width: 100vw;
}

div {
    width: 100%;
    height: 100%;
    display: flex;
    align-items:center;
    justify-content: center;
    background-color: aqua;
}

<div>
    <h1>Sample</h1>
</div>


问:
ReferenceError: require is not defined in ES module scope
I added the webpack 5 config like this in the typescript project:

```<code>const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry : {
    'index' : './index.ts',
  } ,
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
        '@': path.resolve(__dirname, '../../../src'),
    },
  },
  output : {
    path : path.resolve(__dirname, '../../bundle') ,
    filename : '[name].js'
  },
  module : {
    rules : [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/]
        },
        include: [
          path.resolve(__dirname, '../../../node_modules/js-wheel'),
          path.resolve(__dirname, '../../../src')
        ],
        exclude: /node_modules|\.d\.ts$/
      }
    ]
  }
};
</code>```

but when I use this command to build the project:

```<code>"build": "rm -rf dist && webpack --mode development --config src/config/webpack.config.js",
</code>```

shows error:

```<code>[webpack-cli] ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/xxx/source/dwarf/frontend/js/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
</code>```

how to change the webpack config to support ES6? I am searching from google but did not found any clue. is it possible to transform the webpack config incompatible with ES6?

答:
The error shows that you are using ES module in your project, but the require are CommonJS import way, so try to using the ES module import way like this:

```<code>import webpack from 'webpack';
</code>```

and export like this:

```<code>export default {
  entry : {
    'index' : './index.ts',
  }
}
</code>```

Body:
I added the webpack 5 config like this in the typescript project:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry : {
    'index' : './index.ts',
  } ,
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    alias: {
        vue: 'vue/dist/vue.esm-bundler.js',
        '@': path.resolve(__dirname, '../../../src'),
    },
  },
  output : {
    path : path.resolve(__dirname, '../../bundle') ,
    filename : '[name].js'
  },
  module : {
    rules : [
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/]
        },
        include: [
          path.resolve(__dirname, '../../../node_modules/js-wheel'),
          path.resolve(__dirname, '../../../src')
        ],
        exclude: /node_modules|\.d\.ts$/
      }
    ]
  }
};

but when I use this command to build the project:

"build": "rm -rf dist && webpack --mode development --config src/config/webpack.config.js",

shows error:

[webpack-cli] ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/xxx/source/dwarf/frontend/js/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

how to change the webpack config to support ES6? I am searching from google but did not found any clue. is it possible to transform the webpack config incompatible with ES6?

Body:
The error shows that you are using ES module in your project, but the require are CommonJS import way, so try to using the ES module import way like this:

import webpack from 'webpack';

and export like this:

export default {
  entry : {
    'index' : './index.ts',
  }
}


问:
CAB Framework WorkItem event switching between user controls
I have a problem using CAB Framework. I created some GUI User control interfaces and put them on my screen, that works fine. However, I would like to save my data between the different user controls. I made some DataContracts using WCF and I put the data I need in the DataContract and put those in properties so they're accessible from the WorkItem. Now I used the following function in the WorkItem to process the data:

```<code>protected override void OnWorkItemSmartPartChanged(object sender, EventArgs e)
    {
        MessageBox.Show(_testWorkItemControlAdres.AdresContract.Gemeente);
    }
</code>```

When I change between user controls, I want to see if it can succesfully access the data. However, when I switch between the wizard steps (the user controls) it never triggers the event. Do I need to add this event somewhere else or not?

答:
Did you actually link the event to the WorkItem?

Workspace.SmartPartActivated += new EventHandler(OnWorkItemSmartPartChanged);

Cheers

Body:
I have a problem using CAB Framework. I created some GUI User control interfaces and put them on my screen, that works fine. However, I would like to save my data between the different user controls. I made some DataContracts using WCF and I put the data I need in the DataContract and put those in properties so they're accessible from the WorkItem. Now I used the following function in the WorkItem to process the data:

protected override void OnWorkItemSmartPartChanged(object sender, EventArgs e)
    {
        MessageBox.Show(_testWorkItemControlAdres.AdresContract.Gemeente);
    }

When I change between user controls, I want to see if it can succesfully access the data. However, when I switch between the wizard steps (the user controls) it never triggers the event. Do I need to add this event somewhere else or not?


问:
Monkeypatch an executable in Python pytest
In Python 3.10, I have a function like:

from shutil import which
def my_func():
    if which('myexecutable.sh'):
       # do stuff
    else:
       # do other stuff
```

I would like to write a unit test with Pytest that runs the first part code even though the executable is not present. What is the best way to do this?

I know that I can use monkeypatch.setenv() to set an environment variable, but that's not going to make the which() check pass. There's also the added challenge of making sure this is compatible on Windows and Linux.

答:
You could try like this:

# in script file
from shutil import which

def myfunc():
    if which("myexecutable.sh"):
        return "OK"
    else:
        ...
```
<pre class="lang-py prettyprint-override"><code># in test file
import pytest
from script import myfunc

@pytest.fixture
def which(mocker):
    return mocker.patch("script.which", autospec=True)

def test_myfunc(which):
    assert myfunc() == "OK"
</code>```

Running pytest outputs: 1 passed

Body:
In Python 3.10, I have a function like:

from shutil import which
def my_func():
    if which('myexecutable.sh'):
       # do stuff
    else:
       # do other stuff

I would like to write a unit test with Pytest that runs the first part code even though the executable is not present. What is the best way to do this?

I know that I can use monkeypatch.setenv() to set an environment variable, but that's not going to make the which() check pass. There's also the added challenge of making sure this is compatible on Windows and Linux.

Body:
You could try like this:

# in script file
from shutil import which

def myfunc():
    if which("myexecutable.sh"):
        return "OK"
    else:
        ...

# in test file
import pytest
from script import myfunc

@pytest.fixture
def which(mocker):
    return mocker.patch("script.which", autospec=True)

def test_myfunc(which):
    assert myfunc() == "OK"

Running pytest outputs: 1 passed


问:
Textarea that can do syntax highlighting on the fly?
I am storing a number of HTML blocks inside a CMS for reasons of easier maintenance. They are represented by <textarea>s.

Does anybody know a JavaScript Widget of some sort that can do syntax highlighting for HTML within a textarea or similar, while still staying a plain text editor (no WYSIWYG or advanced functions)?

答:
This is doable by adding an overlay code block infront of textarea, and use that to apply syntax highlighting as mentioned by couple of others.

However there are some edge cases to take care of.
This article goes in detail about them:
https://css-tricks.com/creating-an-editable-textarea-that-supports-syntax-highlighted-code

Thankfully, author has created it as a custom element
https://github.com/WebCoder49/code-input

Usage example
https://codepen.io/WebCoder49/pen/jOypJOx


问:
How to convert an array of string integers to an array of integers? Ruby
I have an array:

```<code>all_ages = ["11", "9", "10", "8", "9"]
</code>```

and I want to convert it to an array of integers to hopefully make it easier to add them all together.
Any help greatly appreciated, looking for level one solutions.

Body:
I have an array:

all_ages = ["11", "9", "10", "8", "9"]

and I want to convert it to an array of integers to hopefully make it easier to add them all together.
Any help greatly appreciated, looking for level one solutions.

Body:
all_ages = ["11", "9", "10", "8", "9"]

Code

p all_ages.map(&:to_i).sum

Or

p all_ages.map { |x| x.to_i }.sum

Output

47


问:
typescript extend new property without modifying existing type
I have this code

```<code>type VehicleDetails = {made: string}

function doSomethingWithVehicleDetails (details: VehicleDetails) { //what to add here for newProperty?
  console.log(details);
}

doSomethingWithVehicleDetails({ made: '123', newProperty: true })
</code>```

https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/FDAuE8AcFMAIDVoAsCWBjANtAItUBDFDAZ1gF5YBvAW3wBNoAuWY0AJxQDsBzAXxABmAV05pQKAPadYdCQGUJ1PKh4B1FKCSJUmHHkIlYACgYEixZtvRZcZkgEoqsAPTOA7knyhYoCbHp0sEjQbHACEmywnNBuAApsEjBsEAD8wLCwaFLEElgAdBgS3Cb65vYA3MD8wLIKSppc3OqaVrq2BsRGlLC0DMwA5ACMAEwAzP0ANFEx8YkhEMzsQnC89kA

without modifying type VehicleDetails = {made: string}, how can I add newProperty in doSomethingWithVehicleDetails argument to fix the error?

答:
You could do something like this:

type VehicleDetails = {made: string};

function doSomethingWithVehicleDetails (details: VehicleDetails & { newProperty: boolean }) {
  console.log(details);
}

doSomethingWithVehicleDetails({ made: '123', newProperty: true });
```

Body:
I have this code

type VehicleDetails = {made: string}

function doSomethingWithVehicleDetails (details: VehicleDetails) { //what to add here for newProperty?
  console.log(details);
}

doSomethingWithVehicleDetails({ made: '123', newProperty: true })

https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/FDAuE8AcFMAIDVoAsCWBjANtAItUBDFDAZ1gF5YBvAW3wBNoAuWY0AJxQDsBzAXxABmAV05pQKAPadYdCQGUJ1PKh4B1FKCSJUmHHkIlYACgYEixZtvRZcZkgEoqsAPTOA7knyhYoCbHp0sEjQbHACEmywnNBuAApsEjBsEAD8wLCwaFLEElgAdBgS3Cb65vYA3MD8wLIKSppc3OqaVrq2BsRGlLC0DMwA5ACMAEwAzP0ANFEx8YkhEMzsQnC89kA

without modifying type VehicleDetails = {made: string}, how can I add newProperty in doSomethingWithVehicleDetails argument to fix the error?


问:
File uploading rails 3
I have a rails 3 app that has a comment system that allows a user to make comments. What I now wish to do is extend this further by enabling the user to attach/upload files to the comment system. Fairly easy question I am about to ask. What is the best tool/plugin or gem to use so that I can achieve this? I've done some thorough research and found that alot of these plugins such as carrierwave, paperclip and a few others are used to upload photos and I am not trying to do this.

Requirements

User should be able to upload/attach files

Can upload word, powerpoint or execel docuements

答:
Paperclip

CarrierWave

As for me CarrierWave more modern and nice solution. Have a try.

Title: File uploading rails 3


问:
How to create file directory from reading spreadsheet in apps script
I have managed to record a folder's file/folder directory into a Google Sheet. From this Google Sheet I would like to copy this folder structure by reading each row.

Google Sheet Link: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

```<code>function copyFolderTree() {
  const sourceFolderId = '1uTGq2MRHzbev23sQzzFCi3Pl-v-ntMql';
  const sourceFolder = DriveApp.getFolderById(sourceFolderId).getName();
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const data = ws.getDataRange().getValues();
  range.shift()
  const destinationRootFolder = DriveApp.createFolder(`${sourceFolder}`)

  data.forEach(function(row){
    Logger.log(row)
    let depth = row[4]
    if (row[4] === depth && row[2] === 'Folder') {
      Logger.log(`Name of folder is currently ${row[4]}`)
      Logger.log(`Depth is currently ${row[4]}`)
      Logger.log(`Type is currently ${row[2]}`)
      destinationRootFolder.createFolder(row[0])
      row.push('hello')
      Logger.log(row)
      range.setValues(values);
    }
    })
}

I realise this is the incorrect thinking. Do I need to place the newly created folder into it's copied parent folder using the folder's name?

Thank you,

  [1]: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing
</code>```

答:
From From this Google Sheet I would like to copy this folder structure by reading each row. and First I would like to create the folder structure. My next step would be to work on transferring the files across., when you want to copy a folder (in your sample Spreadsheet, it's "Amy Bits".) including all subfolders and files using Google Apps Script, how about the following sample script? I have created a Google Apps Script library for achieving this situation. So in this answer, I would like to propose the script using the Google Apps Script library.

Usage:

1. Install library.

You can see the method for installing the library at here.

2. Enable Drive API.

In this library, Drive API is used. So please enable Drive API at Advanced Google services.

3. Sample script:

When your sample Spreadsheet is used, the sample script is as follows.

function myFunction() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  const sourceFolderId = sheet.getRange("B2").getValue().split("/")[5]; // Please set the source folder ID.
  const destinationFolderId = DriveApp.createFolder("sample").getId(); // Please set the destination folder ID.
  const object = { sourceFolderId, destinationFolderId, overwrite: true };
  const res = CopyFolder.copyAllFilesFolders(object);
  console.log(res);
}
```
<ul>
<li><p>If you can directly put the source folder ID and the destination folder ID, you can also the following sample script.</p>
```  function myFunction() {
    const object = {
      sourceFolderId: "###", // Please set the source folder ID.
      destinationFolderId: "###", // Please set the destination folder ID.
      overwrite: true,
    };
    const res = CopyFolder.copyAllFilesFolders(object);
    console.log(res);
  }
```

Note:

If the script process time is over 6 minutes, you can see one more sample script. Ref

Reference:

CopyFolder of Google Apps Script library

Body:
I have managed to record a folder's file/folder directory into a Google Sheet. From this Google Sheet I would like to copy this folder structure by reading each row.

Google Sheet Link: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

function copyFolderTree() {
  const sourceFolderId = '1uTGq2MRHzbev23sQzzFCi3Pl-v-ntMql';
  const sourceFolder = DriveApp.getFolderById(sourceFolderId).getName();
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName('Sheet1');
  const data = ws.getDataRange().getValues();
  range.shift()
  const destinationRootFolder = DriveApp.createFolder(`${sourceFolder}`)

  data.forEach(function(row){
    Logger.log(row)
    let depth = row[4]
    if (row[4] === depth && row[2] === 'Folder') {
      Logger.log(`Name of folder is currently ${row[4]}`)
      Logger.log(`Depth is currently ${row[4]}`)
      Logger.log(`Type is currently ${row[2]}`)
      destinationRootFolder.createFolder(row[0])
      row.push('hello')
      Logger.log(row)
      range.setValues(values);
    }
    })
}

I realise this is the incorrect thinking. Do I need to place the newly created folder into it's copied parent folder using the folder's name?

Thank you,

  [1]: https://docs.google.com/spreadsheets/d/1qgDd8PEmHSYz5IsN9banYBjbmAyoLLVe3WMnOvmHdlE/edit?usp=sharing

Body:
From From this Google Sheet I would like to copy this folder structure by reading each row. and First I would like to create the folder structure. My next step would be to work on transferring the files across., when you want to copy a folder (in your sample Spreadsheet, it's "Amy Bits".) including all subfolders and files using Google Apps Script, how about the following sample script? I have created a Google Apps Script library for achieving this situation. So in this answer, I would like to propose the script using the Google Apps Script library.

Usage:

1. Install library.

You can see the method for installing the library at here.

2. Enable Drive API.

In this library, Drive API is used. So please enable Drive API at Advanced Google services.

3. Sample script:

When your sample Spreadsheet is used, the sample script is as follows.

function myFunction() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  const sourceFolderId = sheet.getRange("B2").getValue().split("/")[5]; // Please set the source folder ID.
  const destinationFolderId = DriveApp.createFolder("sample").getId(); // Please set the destination folder ID.
  const object = { sourceFolderId, destinationFolderId, overwrite: true };
  const res = CopyFolder.copyAllFilesFolders(object);
  console.log(res);
}

If you can directly put the source folder ID and the destination folder ID, you can also the following sample script.

  function myFunction() {
    const object = {
      sourceFolderId: "###", // Please set the source folder ID.
      destinationFolderId: "###", // Please set the destination folder ID.
      overwrite: true,
    };
    const res = CopyFolder.copyAllFilesFolders(object);
    console.log(res);
  }

Note:

If the script process time is over 6 minutes, you can see one more sample script. Ref

Reference:

CopyFolder of Google Apps Script library


问:
Where could I update Laravel Migration files Foreign key scripts
working with Laravel project and need update titles table new columns like employee_id and create new migration command php artisan make:migration add_employee_id_to_titles_table --table=titles and create new migration file like add_employee_id_to_titles_tables.php now I need add following foreign key relationship with new columns and the titles table

```<code> Schema::table('titles', function ($table){
             $table->foreign('employee_id')->references('id')->on('titles')->onDelete('cascade');
        });
</code>```

my problem is in witch migration files titles or new add_employee_id_to_titles_tables should I add this scripts?

答:
When you run php artisan migrate it checks your database and migrations table and if there is new migration that didn't save it will run.
So you have to write the scripts in a file that has not been executed

Body:
working with Laravel project and need update titles table new columns like employee_id and create new migration command php artisan make:migration add_employee_id_to_titles_table --table=titles and create new migration file like add_employee_id_to_titles_tables.php now I need add following foreign key relationship with new columns and the titles table

 Schema::table('titles', function ($table){
             $table->foreign('employee_id')->references('id')->on('titles')->onDelete('cascade');
        });

my problem is in witch migration files titles or new add_employee_id_to_titles_tables should I add this scripts?


问:
Java closing connections and findbugs
In our code we usually use the following pattern:

```<code>Connection conn;
try{
    conn = getConnection();
    //Do databasey stuff
}catch(Exceptions that get thrown){
}finally{
    try{
        conn.close();
    }catch(SQLException ex){
        logger.error("Failed to cleanup database connection",ex);
    }
}
</code>```

However findbugs doesn't like this. Since conn.close() can throw an exception then the connection isn't guaranteed to be closed.
Is findbugs being too pedantic or is there a better way to close database connections.

Edit:
Added removed try catch around close.

答:
What you really want to be doing is to combine "The Elite Gentleman"'s answer with the @edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" ) annotation. FindBugs seems to only be happy if you the complete closing in method in the following manner (which is btw the preferred sequence for doing so):

```<code>...
}finally{
    try{
       resultSet.close();
    }catch( SqlException e ){
       //log error
    }finally{
       try{
          statement.close();
       }catch( SqlException e ){
          //log error
       }finally{
          try{
              connection.close();
          }catch( SqlException e ){
              //log error
          }
       }
    }
}
</code>```

Which is very verbose and you probably don't want to do if for no other reason than the love of your carpal tunnel, thus you should use the DBUtils.closeQuietly() method (or create your own, your call). However, FindBugs doesn't recognise this (i.e. using the library or your own method) as properly closing the resources and issues you a warning. In this case it is clearly a false positive. Therefore must make sure its the only warning you are getting and then disable that specific warning for that method.

```<code>@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )
public void doStuff( final Connection connection ){
    try{
        //Do databasey stuff
    }catch( SqlException e ){
        //throw a glorious exception....
    }finally{
        DbUtils.closeQuietly( resultSet  );
        DbUtils.closeQuietly( statement  );
        DbUtils.closeQuietly( connection );
}
</code>```

This way you clean up your resources with the few lines of code and avoid a FindBugs warning.

ContentLicense: CC BY-SA 2.5

Title: Java closing connections and findbugs

Body:
In our code we usually use the following pattern:

Connection conn;
try{
    conn = getConnection();
    //Do databasey stuff
}catch(Exceptions that get thrown){
}finally{
    try{
        conn.close();
    }catch(SQLException ex){
        logger.error("Failed to cleanup database connection",ex);
    }
}

However findbugs doesn't like this. Since conn.close() can throw an exception then the connection isn't guaranteed to be closed.
Is findbugs being too pedantic or is there a better way to close database connections.

Edit:
Added removed try catch around close.

Body:
What you really want to be doing is to combine "The Elite Gentleman"'s answer with the @edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" ) annotation. FindBugs seems to only be happy if you the complete closing in method in the following manner (which is btw the preferred sequence for doing so):

...
}finally{
    try{
       resultSet.close();
    }catch( SqlException e ){
       //log error
    }finally{
       try{
          statement.close();
       }catch( SqlException e ){
          //log error
       }finally{
          try{
              connection.close();
          }catch( SqlException e ){
              //log error
          }
       }
    }
}

Which is very verbose and you probably don't want to do if for no other reason than the love of your carpal tunnel, thus you should use the DBUtils.closeQuietly() method (or create your own, your call). However, FindBugs doesn't recognise this (i.e. using the library or your own method) as properly closing the resources and issues you a warning. In this case it is clearly a false positive. Therefore must make sure its the only warning you are getting and then disable that specific warning for that method.

@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )
public void doStuff( final Connection connection ){
    try{
        //Do databasey stuff
    }catch( SqlException e ){
        //throw a glorious exception....
    }finally{
        DbUtils.closeQuietly( resultSet  );
        DbUtils.closeQuietly( statement  );
        DbUtils.closeQuietly( connection );
}

This way you clean up your resources with the few lines of code and avoid a FindBugs warning.


问:
How to get textView in subview for AVPlayerViewController to scroll?
I am using AVPlayerViewController to play mp3 audio files.  I can get the player to appear programmatically with no problems. I have also added subviews in order to set an overlay for an imageView and textView. This works fine but I cannot get the textView to scroll. I was able to test the same basic code using just a regular UIViewController and the textView scrolls fine. So, I'm wondering if there's an issue with scrolling using AVPlayerViewController or if I've missed something. Please note: This is NOT a duplicate of my other post about AVPlayerViewController. In the other post, I'm asking if it's possible to use Storyboard somehow to customize in this way. Any help/suggestions regarding scrolling here would be greatly appreciated.  Code is as follows:

```<code>let url = URL(string:mystream)
    let player = AVPlayer(url: url!)

    let controller = AVPlayerViewController()

    controller.player = player
    controller.view.frame = self.view.frame

    controller.contentOverlayView!.backgroundColor = UIColor(red: 150/255, green: 51/255, blue: 251/255, alpha: 1)

    //.. view
    var myView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))

    //.. imageView
    var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 325, height: 325))
    imageView.image = myImage
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    //.. textView
    var myTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 350, height: 600))
    //myTextView.text = currentList
    myTextView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. "
    myTextView.font = UIFont(name: "Chalkboard SE", size: 18)
    myTextView.textColor = UIColor.yellow
    myTextView.backgroundColor = UIColor.gray

    //..
    myTextView.contentMode = .scaleAspectFit

    myTextView.isScrollEnabled = true
    myTextView.isUserInteractionEnabled = true
    myTextView.isEditable = true
    myTextView.isSelectable = true
    myTextView.bounces = true
    myTextView.showsVerticalScrollIndicator = true
    myTextView.showsHorizontalScrollIndicator = true
    myTextView.contentSize = CGSize(width: 700, height: 700)

    myTextView.translatesAutoresizingMaskIntoConstraints = false

    myView.addSubview(imageView)
    myView.addSubview(myTextView)

    controller.contentOverlayView?.addSubview(myView)

    //.. @@@@@@@@@
    imageView.topAnchor.constraint(equalTo: myView.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 325).isActive = true

    myTextView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 15).isActive = true
    myTextView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    myTextView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    myTextView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    //.. @@@@@@@@@

    present(controller, animated: true) {
            player.play()
    }
</code>```

Here is a picture of what the presented player should look like... I need the textView to scroll...

UPDATE: So, after seeing Shawn's answer and thinking about this, I would like to try to also implement a tabBar type design like say Spotify where the user can navigate to various tabs, still have the "player" playing music, and have a "mini player" at the bottom of the screen. See my next screenshot. Best way to do this? AVPlayerViewController? AVPlayer?

答:
There are a lot of gesture recognizers already present on an AVPlayerViewController to pan, pinch etc to either interact with the media and / or dismiss the AVPlayerViewController once presented.

Because of this, I believe your UITextView does not receive it's interaction events and so nothing happens when the user tries to scroll.

Infact, Apple documents that the contentOverlayView of the AVPlayerViewController should be used for non interactive views.

contentOverlayView

A view that displays between the video content and
the playback controls.

Discussion

Use the content overlay view to add noninteractive custom
views, such as a logo or watermark, between the video content and the
controls.

What I suggest is the following like I suggested in your other question:

Create a custom UIViewController

Add the AVPlayerViewController as a child view to this custom view controller

Add the UIImageView and the UITextView to this custom UIViewController and not to the AVPlayerViewController

Here is how I would do that is as follows:

```<code>import UIKit
import AVKit

class CustomPlayerVC: UIViewController
{
    var image: UIImage?
    var streamURL: URL?
    var metaText = ""

    private let imageView = UIImageView()
    private let myTextView = UITextView()
    private let playerViewController = AVPlayerViewController()

    // Bool to check if your player view has been configured
    // so that you configure only once
    private var isPlayerConfigured = false

    // Custom init
    init(withStreamURL streamURL: URL?,
         image: UIImage?,
         metaText: String)
    {
        self.streamURL = streamURL
        self.image = image
        self.metaText = metaText

        super.init(nibName: nil, bundle: nil)
    }

    // Storyboard support if you want to add this view controller
    // in your storyboard
    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
    }

    override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews()

        // Check if the player is already configured
        if !isPlayerConfigured
        {
            isPlayerConfigured = true
            configurePlayer()
            configureImageView()
            configureTextView()
        }
    }

    private func configurePlayer()
    {
        if let streamURL = streamURL
        {
            let player = AVPlayer(url: streamURL)

            playerViewController.player = player

            // Add the AVPlayerController as a child of the current
            // view controller
            self.addChild(playerViewController)

            // Configure the player view
            let playerView = playerViewController.view
            playerView?.backgroundColor = .clear
            playerView?.frame = self.view.bounds

            // Add the AVPlayerViewController's view as a subview
            // of the current view
            self.view.addSubview(playerView!)
            playerViewController.didMove(toParent: self)

            // Start playing the content
            playerViewController.player?.play()

            // Add this to hide the default quick time player logo
            let contentBGView = UIView(frame: view.bounds)
            contentBGView.backgroundColor
                = UIColor(red: 150/255, green: 51/255, blue: 251/255, alpha: 1)
            playerViewController.contentOverlayView!.addSubview(contentBGView)
        }
    }

    // Configure your image view with auto-layout
    private func configureImageView()
    {
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.image = image
        imageView.contentMode = .scaleAspectFill
        view.addSubview(imageView)

        imageView.topAnchor
            .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50)
            .isActive = true

        imageView.centerXAnchor
            .constraint(equalTo: view.centerXAnchor, constant: 0)
            .isActive = true

        imageView.widthAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        imageView.heightAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        imageView.layer.cornerRadius = 20
        imageView.clipsToBounds = true
    }

    // Configure your text view with auto-layout
    private func configureTextView()
    {
        myTextView.translatesAutoresizingMaskIntoConstraints = false

        myTextView.text = metaText
        myTextView.font = UIFont.systemFont(ofSize: 18)
        myTextView.textColor = UIColor.yellow
        myTextView.backgroundColor = UIColor.gray
        view.addSubview(myTextView)

        // Your auto layout constraints
        myTextView.topAnchor
            .constraint(equalTo: imageView.bottomAnchor, constant: 15)
            .isActive = true

        myTextView.centerXAnchor
            .constraint(equalTo: view.centerXAnchor, constant: 0)
            .isActive = true

        myTextView.widthAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        myTextView.heightAnchor
            .constraint(equalToConstant: 200)
            .isActive = true
    }
}
</code>```

And then when you want to transition to your player, this is what you do:

```<code>private func playAudio()
{
    let text = "your long text goes here"

    let streamURL = URL(string: "http://stream.radiojar.com/nhq0vcqwuueuv")

    // Initialize the custom player view controller
    let customPlayerVC
        = CustomPlayerVC(withStreamURL: streamURL,
                         image: UIImage(named: "art"),
                         metaText: text)

    // This is important to avoid seeing the full screen player button
    customPlayerVC.modalPresentationStyle = .fullScreen

    present(customPlayerVC, animated: true) {
        // do what you want
    }
}
</code>```

The end result is a player which plays your audio stream, displays the image and gives you a text view which can be scrolled.

Here is a glimpse of the user interaction:

Body:
I am using AVPlayerViewController to play mp3 audio files.  I can get the player to appear programmatically with no problems. I have also added subviews in order to set an overlay for an imageView and textView. This works fine but I cannot get the textView to scroll. I was able to test the same basic code using just a regular UIViewController and the textView scrolls fine. So, I'm wondering if there's an issue with scrolling using AVPlayerViewController or if I've missed something. Please note: This is NOT a duplicate of my other post about AVPlayerViewController. In the other post, I'm asking if it's possible to use Storyboard somehow to customize in this way. Any help/suggestions regarding scrolling here would be greatly appreciated.  Code is as follows:

let url = URL(string:mystream)
    let player = AVPlayer(url: url!)

    let controller = AVPlayerViewController()

    controller.player = player
    controller.view.frame = self.view.frame

    controller.contentOverlayView!.backgroundColor = UIColor(red: 150/255, green: 51/255, blue: 251/255, alpha: 1)

    //.. view
    var myView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height))

    //.. imageView
    var imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 325, height: 325))
    imageView.image = myImage
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    //.. textView
    var myTextView = UITextView(frame: CGRect(x: 0, y: 0, width: 350, height: 600))
    //myTextView.text = currentList
    myTextView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. "
    myTextView.font = UIFont(name: "Chalkboard SE", size: 18)
    myTextView.textColor = UIColor.yellow
    myTextView.backgroundColor = UIColor.gray

    //..
    myTextView.contentMode = .scaleAspectFit

    myTextView.isScrollEnabled = true
    myTextView.isUserInteractionEnabled = true
    myTextView.isEditable = true
    myTextView.isSelectable = true
    myTextView.bounces = true
    myTextView.showsVerticalScrollIndicator = true
    myTextView.showsHorizontalScrollIndicator = true
    myTextView.contentSize = CGSize(width: 700, height: 700)

    myTextView.translatesAutoresizingMaskIntoConstraints = false

    myView.addSubview(imageView)
    myView.addSubview(myTextView)

    controller.contentOverlayView?.addSubview(myView)

    //.. @@@@@@@@@
    imageView.topAnchor.constraint(equalTo: myView.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
    imageView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    imageView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    imageView.heightAnchor.constraint(equalToConstant: 325).isActive = true

    myTextView.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 15).isActive = true
    myTextView.centerXAnchor.constraint(equalTo: myView.centerXAnchor, constant: 0).isActive = true
    myTextView.widthAnchor.constraint(equalToConstant: 325).isActive = true
    myTextView.heightAnchor.constraint(equalToConstant: 200).isActive = true

    //.. @@@@@@@@@

    present(controller, animated: true) {
            player.play()
    }

Here is a picture of what the presented player should look like... I need the textView to scroll...

UPDATE: So, after seeing Shawn's answer and thinking about this, I would like to try to also implement a tabBar type design like say Spotify where the user can navigate to various tabs, still have the "player" playing music, and have a "mini player" at the bottom of the screen. See my next screenshot. Best way to do this? AVPlayerViewController? AVPlayer?

Body:
There are a lot of gesture recognizers already present on an AVPlayerViewController to pan, pinch etc to either interact with the media and / or dismiss the AVPlayerViewController once presented.

Because of this, I believe your UITextView does not receive it's interaction events and so nothing happens when the user tries to scroll.

Infact, Apple documents that the contentOverlayView of the AVPlayerViewController should be used for non interactive views.

contentOverlayView

A view that displays between the video content and
the playback controls.

Discussion

Use the content overlay view to add noninteractive custom
views, such as a logo or watermark, between the video content and the
controls.

What I suggest is the following like I suggested in your other question:

Create a custom UIViewController

Add the AVPlayerViewController as a child view to this custom view controller

Add the UIImageView and the UITextView to this custom UIViewController and not to the AVPlayerViewController

Here is how I would do that is as follows:

import UIKit
import AVKit

class CustomPlayerVC: UIViewController
{
    var image: UIImage?
    var streamURL: URL?
    var metaText = ""

    private let imageView = UIImageView()
    private let myTextView = UITextView()
    private let playerViewController = AVPlayerViewController()

    // Bool to check if your player view has been configured
    // so that you configure only once
    private var isPlayerConfigured = false

    // Custom init
    init(withStreamURL streamURL: URL?,
         image: UIImage?,
         metaText: String)
    {
        self.streamURL = streamURL
        self.image = image
        self.metaText = metaText

        super.init(nibName: nil, bundle: nil)
    }

    // Storyboard support if you want to add this view controller
    // in your storyboard
    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
    }

    override func viewDidLayoutSubviews()
    {
        super.viewDidLayoutSubviews()

        // Check if the player is already configured
        if !isPlayerConfigured
        {
            isPlayerConfigured = true
            configurePlayer()
            configureImageView()
            configureTextView()
        }
    }

    private func configurePlayer()
    {
        if let streamURL = streamURL
        {
            let player = AVPlayer(url: streamURL)

            playerViewController.player = player

            // Add the AVPlayerController as a child of the current
            // view controller
            self.addChild(playerViewController)

            // Configure the player view
            let playerView = playerViewController.view
            playerView?.backgroundColor = .clear
            playerView?.frame = self.view.bounds

            // Add the AVPlayerViewController's view as a subview
            // of the current view
            self.view.addSubview(playerView!)
            playerViewController.didMove(toParent: self)

            // Start playing the content
            playerViewController.player?.play()

            // Add this to hide the default quick time player logo
            let contentBGView = UIView(frame: view.bounds)
            contentBGView.backgroundColor
                = UIColor(red: 150/255, green: 51/255, blue: 251/255, alpha: 1)
            playerViewController.contentOverlayView!.addSubview(contentBGView)
        }
    }

    // Configure your image view with auto-layout
    private func configureImageView()
    {
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.image = image
        imageView.contentMode = .scaleAspectFill
        view.addSubview(imageView)

        imageView.topAnchor
            .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50)
            .isActive = true

        imageView.centerXAnchor
            .constraint(equalTo: view.centerXAnchor, constant: 0)
            .isActive = true

        imageView.widthAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        imageView.heightAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        imageView.layer.cornerRadius = 20
        imageView.clipsToBounds = true
    }

    // Configure your text view with auto-layout
    private func configureTextView()
    {
        myTextView.translatesAutoresizingMaskIntoConstraints = false

        myTextView.text = metaText
        myTextView.font = UIFont.systemFont(ofSize: 18)
        myTextView.textColor = UIColor.yellow
        myTextView.backgroundColor = UIColor.gray
        view.addSubview(myTextView)

        // Your auto layout constraints
        myTextView.topAnchor
            .constraint(equalTo: imageView.bottomAnchor, constant: 15)
            .isActive = true

        myTextView.centerXAnchor
            .constraint(equalTo: view.centerXAnchor, constant: 0)
            .isActive = true

        myTextView.widthAnchor
            .constraint(equalToConstant: 325)
            .isActive = true

        myTextView.heightAnchor
            .constraint(equalToConstant: 200)
            .isActive = true
    }
}

And then when you want to transition to your player, this is what you do:

private func playAudio()
{
    let text = "your long text goes here"

    let streamURL = URL(string: "http://stream.radiojar.com/nhq0vcqwuueuv")

    // Initialize the custom player view controller
    let customPlayerVC
        = CustomPlayerVC(withStreamURL: streamURL,
                         image: UIImage(named: "art"),
                         metaText: text)

    // This is important to avoid seeing the full screen player button
    customPlayerVC.modalPresentationStyle = .fullScreen

    present(customPlayerVC, animated: true) {
        // do what you want
    }
}

The end result is a player which plays your audio stream, displays the image and gives you a text view which can be scrolled.

Here is a glimpse of the user interaction:


问:
location_geocoder Bad state: No element
if i want to make use from geocoder it given me this error message: Bad state: No element.

what i now is that i have giving geocoder a correctly written city name and also that i have given geocoder a api key from a payed google maps platform account.

flutter run:

```<code>Launching lib/main.dart on iPhone 13 in debug mode...
Running pod install...                                             14.3s
Running Xcode build...
 └─Compiling, linking and signing...                        13.8s
Xcode build done.                                           633.2s
Syncing files to device iPhone 13...                               186ms

Flutter run key commands.
r Hot reload.
R Hot restart.
h List all available interactive commands.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).

 Running with sound null safety

An Observatory debugger and profiler on iPhone 13 is available at: http://127.0.0.1:50040/6fcE371o6S0=/
The Flutter DevTools debugger and profiler on iPhone 13 is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:50040/6fcE371o6S0=/
flutter: null
flutter: stadt_view: bansko
flutter: Bad state: No element
flutter: null

</code>```

i now that ther don't stand anything from location_geocoder but if i comment the geocoder part out: i don't have the bug anymore.

flutter doctor:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.0, on macOS 12.1 21C52 darwin-x64, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] IntelliJ IDEA Community Edition (version 2020.3.3)
[✓] VS Code (version 1.64.0)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

! Doctor found issues in 1 category.
</code>```

Please help me

答: just use http package instead location_geocoder that worked for me</p>

Title: location_geocoder Bad state: No element

Body:
if i want to make use from geocoder it given me this error message: Bad state: No element.

what i now is that i have giving geocoder a correctly written city name and also that i have given geocoder a api key from a payed google maps platform account.

flutter run:

Launching lib/main.dart on iPhone 13 in debug mode...
Running pod install...                                             14.3s
Running Xcode build...
 └─Compiling, linking and signing...                        13.8s
Xcode build done.                                           633.2s
Syncing files to device iPhone 13...                               186ms

Flutter run key commands.
r Hot reload.
R Hot restart.
h List all available interactive commands.
d Detach (terminate "flutter run" but leave application running).
c Clear the screen
q Quit (terminate the application on the device).

 Running with sound null safety

An Observatory debugger and profiler on iPhone 13 is available at: http://127.0.0.1:50040/6fcE371o6S0=/
The Flutter DevTools debugger and profiler on iPhone 13 is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:50040/6fcE371o6S0=/
flutter: null
flutter: stadt_view: bansko
flutter: Bad state: No element
flutter: null

i now that ther don't stand anything from location_geocoder but if i comment the geocoder part out: i don't have the bug anymore.

flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.0, on macOS 12.1 21C52 darwin-x64, locale en-US)
[!] Android toolchain - develop for Android devices (Android SDK version 32.1.0-rc1)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.1)
[✓] IntelliJ IDEA Community Edition (version 2020.3.3)
[✓] VS Code (version 1.64.0)
[✓] Connected device (2 available)
[✓] HTTP Host Availability

! Doctor found issues in 1 category.

Please help me


问:
Does not the Systom.IO.Compression.ZipArchive support multi threading?
```<code>            Stream stream = await storageFile.OpenStreamForReadAsync();

            ZipArchive zipArchive = new ZipArchive(stream);

            List<Task> tasks = new List<Task>();
            for (int i = 5; i < 10; i++)
            {
                int j = i;
                tasks.Add(Task.Run(() =>
                {
                    var entry = zipArchive.Entries[j];
                    //It Shows error message:"the operation changed the status of the object"
                }));
            }

</code>```

I've deleted other any operation on the ZipArvhive instance,however such simple code still show error.
The MSDN docs didn't talked about whether it support multi-threading.

答:
The default expectation to the question of thread safety, on any instance member of any type, is "no" - thread safety of instance state is a very niche requirement that is usually explicitly documented (static state is usually expected to have thread safe protections).

The code and behaviour in your question shows that this expectation is validated, and that the answer in this case remains the default: "no"

Body:
            Stream stream = await storageFile.OpenStreamForReadAsync();

            ZipArchive zipArchive = new ZipArchive(stream);

            List<Task> tasks = new List<Task>();
            for (int i = 5; i < 10; i++)
            {
                int j = i;
                tasks.Add(Task.Run(() =>
                {
                    var entry = zipArchive.Entries[j];
                    //It Shows error message:"the operation changed the status of the object"
                }));
            }

I've deleted other any operation on the ZipArvhive instance,however such simple code still show error.
The MSDN docs didn't talked about whether it support multi-threading.


问:
Can I define a const static instance of a class in the class header file
Is it possible to declare and define a const static instance of a class in the class header file.

I want to do something like this (from this similar question):

```<code>class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");
</code>```

This would work if the definition of PlaceID::OUTSIDE was in a source file, but if it's in a header file that is include in multiple location it causes an link error because PlaceID::OUTSIDE is then defined multiple times.

I'd like to define it in the header file for two reasons. First, this will be part of a library and I'd like the library to be header file only.

Second and this is the most important one I want the compiler to be allowed to "inline" the uses of this instance. The class in question (not the one used as an example here) is a wrapper around a primitive type with all methods inlined in order to offer the same performance as the primitive type would. If I place the definition of this instance in a source file, the compiler will not know it's value at compilation time and won't be able to apply some optimisations.

Thanks.

答:
that is include in multiple location

You can stop your header from being included multiple times(and causing your problem(DISCLAIMER: I have not tested it.)) by this(which is commonly used by a lot of libraries)

a.hpp

#ifndef LIBRARY_A
#define LIBRARY_A
//define other things
#endif
```

replace LIBRARY_A for an ID of your choice(note it can't conflict with other libraries so avoid names like SOUND_SYSTEM, but rather SOUND_LIBRARY_FOO with FOO replaced by your project name/your name)

Body:
Is it possible to declare and define a const static instance of a class in the class header file.

I want to do something like this (from this similar question):

class PlaceID {

public:

    inline PlaceID(const std::string placeName):mPlaceName(placeName) {}

    const static PlaceID OUTSIDE;

private:
    std::string mPlaceName;
};

const PlaceID PlaceID::OUTSIDE = PlaceID("");

This would work if the definition of PlaceID::OUTSIDE was in a source file, but if it's in a header file that is include in multiple location it causes an link error because PlaceID::OUTSIDE is then defined multiple times.

I'd like to define it in the header file for two reasons. First, this will be part of a library and I'd like the library to be header file only.

Second and this is the most important one I want the compiler to be allowed to "inline" the uses of this instance. The class in question (not the one used as an example here) is a wrapper around a primitive type with all methods inlined in order to offer the same performance as the primitive type would. If I place the definition of this instance in a source file, the compiler will not know it's value at compilation time and won't be able to apply some optimisations.

Thanks.

Body:
that is include in multiple location

You can stop your header from being included multiple times(and causing your problem(DISCLAIMER: I have not tested it.)) by this(which is commonly used by a lot of libraries)

a.hpp

#ifndef LIBRARY_A
#define LIBRARY_A
//define other things
#endif

replace LIBRARY_A for an ID of your choice(note it can't conflict with other libraries so avoid names like SOUND_SYSTEM, but rather SOUND_LIBRARY_FOO with FOO replaced by your project name/your name)