问:
Good introduction to the Berkeley db C api installed on OS X?
I'm looking for a good introduction to the Berkeley db api that is installed on OS X. I have looked at this Oracle document: http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/BerkeleyDB-Core-C-GSG.pdf

Which seems to be a newer version. I am not able to compile this and get the following error:

```<code>test.c:23: error: ‘DB_CREATE’ undeclared (first use in this function)
test.c:23: error: (Each undeclared identifier is reported only once
test.c:23: error: for each function it appears in.)
test.c:26: error: ‘DB’ has no member named ‘open’
test.c:42: error: too many arguments to function ‘dbp->close’
</code>```

AFAIK, the version installed on OS X is the old BSD licensed 1.85.

答: I did a quick search on Apple's support site. It looks like there are probably more recent releases of Berkeley DB installed on Mac OS X. I found that Berkeley DB 4.2 is installed on Mac OS X Server v10.5 and used in the Open Directory Server. </p>

Body:
I'm looking for a good introduction to the Berkeley db api that is installed on OS X. I have looked at this Oracle document: http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/BerkeleyDB-Core-C-GSG.pdf

Which seems to be a newer version. I am not able to compile this and get the following error:

test.c:23: error: ‘DB_CREATE’ undeclared (first use in this function)
test.c:23: error: (Each undeclared identifier is reported only once
test.c:23: error: for each function it appears in.)
test.c:26: error: ‘DB’ has no member named ‘open’
test.c:42: error: too many arguments to function ‘dbp->close’

AFAIK, the version installed on OS X is the old BSD licensed 1.85.


来源: stackexchange

问:
How to get original image from Filters
I have an image with filters, now I want to go back to the original image on click of a button.

not sure if I need to make a constance for it

```<code>@IBAction func Blur(_ sender: Any) {
    let inputImg = UIimage.image!

    let inputCIImage = CIImage(image: inputImg)

    let blurFilter = CIFilter(name: "CIGaussianBlur")!
    blurFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
    blurFilter.setValue(8, forKey: kCIInputRadiusKey)
    let context = CIContext(options: nil)

    if let output = blurFilter.outputImage{
        if let ciImg = context.createCGImage(output, from: output.extent){
            UIimage.image = UIImage(cgImage: ciImg)
        }
    }
}
</code>```

答:
Wouldn't it be easier to just store the original image in your ViewController, and apply a filer depending on a state?

I would assume that what you call UIImage is a UIImageView tell me if I am wrong.

```<code>let inputImg = // Your original image
let isBlured = false

@IBAction func didClickButton(_ sender: Any) {

    if isBlured {
        myUIImageView.image = inputImg // original image
        isBlured = false
    } else {

        let inputCIImage = CIImage(image: inputImg)
        let blurFilter = CIFilter(name: "CIGaussianBlur")!
        blurFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
        blurFilter.setValue(8, forKey: kCIInputRadiusKey)
        let context = CIContext(options: nil)

        if let output = blurFilter.outputImage{
            if let ciImg = context.createCGImage(output, from: output.extent){
                myUIImageView.image = UIImage(cgImage: ciImg)
                isBlured = true
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get original image from Filters

Body:
I have an image with filters, now I want to go back to the original image on click of a button.

not sure if I need to make a constance for it

@IBAction func Blur(_ sender: Any) {
    let inputImg = UIimage.image!

    let inputCIImage = CIImage(image: inputImg)

    let blurFilter = CIFilter(name: "CIGaussianBlur")!
    blurFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
    blurFilter.setValue(8, forKey: kCIInputRadiusKey)
    let context = CIContext(options: nil)

    if let output = blurFilter.outputImage{
        if let ciImg = context.createCGImage(output, from: output.extent){
            UIimage.image = UIImage(cgImage: ciImg)
        }
    }
}

Body:
Wouldn't it be easier to just store the original image in your ViewController, and apply a filer depending on a state?

I would assume that what you call UIImage is a UIImageView tell me if I am wrong.

let inputImg = // Your original image
let isBlured = false

@IBAction func didClickButton(_ sender: Any) {

    if isBlured {
        myUIImageView.image = inputImg // original image
        isBlured = false
    } else {

        let inputCIImage = CIImage(image: inputImg)
        let blurFilter = CIFilter(name: "CIGaussianBlur")!
        blurFilter.setValue(inputCIImage, forKey: kCIInputImageKey)
        blurFilter.setValue(8, forKey: kCIInputRadiusKey)
        let context = CIContext(options: nil)

        if let output = blurFilter.outputImage{
            if let ciImg = context.createCGImage(output, from: output.extent){
                myUIImageView.image = UIImage(cgImage: ciImg)
                isBlured = true
            }
        }
    }
}


问:
Is there a way to add characters based on a variable?
I'm making a text-based game about Hangman and so far I have 10 words with different amounts of characters in each word. The lowest character count is three, so I'm planning to put in three underscores at the start for me to be able to add underscores after the string.

I have a variable set up, called wordPlayingLength which counts up an integer based on the amount of characters in the word that has been selected through a random statement. My question is if there's a way to add underscores that matches up with the word's length in characters?

```<code>if (randomNumber == 10):
    wordPlaying = str("Didgeridoo") ## states the word being played
    wordPlayingLength = int(len(wordPlaying)) ## calculates the character length of the word being played
    print(str(wordPlayingLength) + " letters!")

    underscoreCount = (wordPlayingLength)
    print("_ _ _ " + ) ## this is where I got stuck, no idea here
</code>```

答:
Firstly,
You don't need wordPlaying = str("Didgeridoo") just wordPlaying = "Didgeridoo"

and wordPlayingLength = int(len(wordPlaying)) just wordPlayingLength = len(wordPlaying)

Secondly,
to repeate string, you can use ' _ ' * wordPlayingLength

Body:
I'm making a text-based game about Hangman and so far I have 10 words with different amounts of characters in each word. The lowest character count is three, so I'm planning to put in three underscores at the start for me to be able to add underscores after the string.

I have a variable set up, called wordPlayingLength which counts up an integer based on the amount of characters in the word that has been selected through a random statement. My question is if there's a way to add underscores that matches up with the word's length in characters?

if (randomNumber == 10):
    wordPlaying = str("Didgeridoo") ## states the word being played
    wordPlayingLength = int(len(wordPlaying)) ## calculates the character length of the word being played
    print(str(wordPlayingLength) + " letters!")

    underscoreCount = (wordPlayingLength)
    print("_ _ _ " + ) ## this is where I got stuck, no idea here


问:
Grab all rows in a table and grab one row where condition
I have an integer column that's set to 1 for nearly all rows in my table, 2 for about 10 rows, and 3 for 6 rows. I want a to select all rows from my table where that column is not equal to 3, but grab the most recently updated row where it is equal to 3. I also have an updated_at column that is a date column.

Here is the sql I've come up with so far.

```<code>SELECT *
  FROM mytable
  LEFT JOIN (SELECT *
               FROM mytable
              WHERE spec_id=3
              ORDER BY updated_at DESC LIMIT 1) mytable2
         ON mytable.id=mytable2.id
</code>```

However, this statement grabs all 6 of my rows where spec_id is set to 3.

Please help.

答:
Just use union all

```<code>(SELECT * FROM mytable WHERE spec_id=3 ORDER BY updated_at DESC LIMIT 1)
UNION ALL
 SELECT * FROM mytable WHERE spec_id!=3
</code>```

Body:
I have an integer column that's set to 1 for nearly all rows in my table, 2 for about 10 rows, and 3 for 6 rows. I want a to select all rows from my table where that column is not equal to 3, but grab the most recently updated row where it is equal to 3. I also have an updated_at column that is a date column.

Here is the sql I've come up with so far.

SELECT *
  FROM mytable
  LEFT JOIN (SELECT *
               FROM mytable
              WHERE spec_id=3
              ORDER BY updated_at DESC LIMIT 1) mytable2
         ON mytable.id=mytable2.id

However, this statement grabs all 6 of my rows where spec_id is set to 3.

Please help.

Body:
Just use union all

(SELECT * FROM mytable WHERE spec_id=3 ORDER BY updated_at DESC LIMIT 1)
UNION ALL
 SELECT * FROM mytable WHERE spec_id!=3


问:
Unable to run airflow scheduler
I have recently installed airflow on an AWS server by using this guide for ubuntu 16.04. After a painful and successful install started the webserver. I tried a sample dag as follows

```<code>from airflow.operators.python_operator import PythonOperator
from airflow.operators.dummy_operator import DummyOperator
from datetime import timedelta
from airflow import DAG
import airflow

# DEFAULT ARGS
default_args = {
'owner': 'airflow',
'start_date': airflow.utils.dates.days_ago(2),
'depends_on_past': False}

dag = DAG('init_run', default_args=default_args, description='DAG SAMPLE',
schedule_interval='@daily')

def print_something():
        print("HELLO AIRFLOW!")

with dag:
        task_1 = PythonOperator(task_id='do_it', python_callable=print_something)
        task_2 = DummyOperator(task_id='dummy')

        task_1 << task_2
</code>```

But when i open the UI the tasks in the dag are still in "No Status" no matter how many times i trigger manually or refresh the page.

Later i found out that airflow scheduler is not running and shows the following error:

```<code>{celery_executor.py:228} ERROR - Error sending Celery task:No module named 'MySQLdb'
Celery Task ID: ('init_run', 'dummy', datetime.datetime(2019, 5, 30, 18, 0, 24, 902499, tzinfo=<TimezoneInfo [UTC, GMT, +00:00:00, STD]>), 1)
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/executors/celery_executor.py", line 118, in send_task_to_executor
    result = task.apply_async(args=[command], queue=queue)
  File "/usr/local/lib/python3.7/site-packages/celery/app/task.py", line 535, in apply_async
    **options
  File "/usr/local/lib/python3.7/site-packages/celery/app/base.py", line 728, in send_task
    amqp.send_task_message(P, name, message, **options)
  File "/usr/local/lib/python3.7/site-packages/celery/app/amqp.py", line 552, in send_task_message
    **properties
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 181, in publish
    exchange_name, declare,
  File "/usr/local/lib/python3.7/site-packages/kombu/connection.py", line 510, in _ensured
    return fun(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 194, in _publish
    [maybe_declare(entity) for entity in declare]
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 194, in <listcomp>
    [maybe_declare(entity) for entity in declare]
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 102, in maybe_declare
    return maybe_declare(entity, self.channel, retry, **retry_policy)
  File "/usr/local/lib/python3.7/site-packages/kombu/common.py", line 121, in maybe_declare
    return _maybe_declare(entity, channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/common.py", line 145, in _maybe_declare
    entity.declare(channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 608, in declare
    self._create_queue(nowait=nowait, channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 617, in _create_queue
    self.queue_declare(nowait=nowait, passive=False, channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 652, in queue_declare
    nowait=nowait,
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/virtual/base.py", line 531, in queue_declare
    self._new_queue(queue, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 82, in _new_queue
    self._get_or_create(queue)
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 70, in _get_or_create
    obj = self.session.query(self.queue_cls) \
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 65, in session
    _, Session = self._open()
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 56, in _open
    engine = self._engine_from_config()
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 51, in _engine_from_config
    return create_engine(conninfo.hostname, **transport_options)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 443, in create_engine
    return strategy.create(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 104, in dbapi
    return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'
</code>```

Here is the setting in the config file (airflow.cfg):

```<code>sql_alchemy_conn = postgresql+psycopg2://airflow@localhost:5432/airflow
broker_url = sqla+mysql://airflow:airflow@localhost:3306/airflow
result_backend =  db+postgresql://airflow:airflow@localhost/airflow
</code>```

I been struggling with this issue for two days now, Please help

答:
In your airflow.cfg, there should also be a config option for celery_result_backend. Are you able to let us know what this value is set to? If it is not present in your config, set it to the same value as the result_backend

i.e:

```<code>celery_result_backend =  db+postgresql://airflow:airflow@localhost/airflow
</code>```

And then restart the airflow stack to ensure the configuration changes apply.

(I wanted to leave this as a comment but don't have enough rep to do so)

Title: Unable to run airflow scheduler

Body:
I have recently installed airflow on an AWS server by using this guide for ubuntu 16.04. After a painful and successful install started the webserver. I tried a sample dag as follows

from airflow.operators.python_operator import PythonOperator
from airflow.operators.dummy_operator import DummyOperator
from datetime import timedelta
from airflow import DAG
import airflow

# DEFAULT ARGS
default_args = {
'owner': 'airflow',
'start_date': airflow.utils.dates.days_ago(2),
'depends_on_past': False}

dag = DAG('init_run', default_args=default_args, description='DAG SAMPLE',
schedule_interval='@daily')

def print_something():
        print("HELLO AIRFLOW!")

with dag:
        task_1 = PythonOperator(task_id='do_it', python_callable=print_something)
        task_2 = DummyOperator(task_id='dummy')

        task_1 << task_2

But when i open the UI the tasks in the dag are still in "No Status" no matter how many times i trigger manually or refresh the page.

Later i found out that airflow scheduler is not running and shows the following error:

{celery_executor.py:228} ERROR - Error sending Celery task:No module named 'MySQLdb'
Celery Task ID: ('init_run', 'dummy', datetime.datetime(2019, 5, 30, 18, 0, 24, 902499, tzinfo=<TimezoneInfo [UTC, GMT, +00:00:00, STD]>), 1)
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/airflow/executors/celery_executor.py", line 118, in send_task_to_executor
    result = task.apply_async(args=[command], queue=queue)
  File "/usr/local/lib/python3.7/site-packages/celery/app/task.py", line 535, in apply_async
    **options
  File "/usr/local/lib/python3.7/site-packages/celery/app/base.py", line 728, in send_task
    amqp.send_task_message(P, name, message, **options)
  File "/usr/local/lib/python3.7/site-packages/celery/app/amqp.py", line 552, in send_task_message
    **properties
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 181, in publish
    exchange_name, declare,
  File "/usr/local/lib/python3.7/site-packages/kombu/connection.py", line 510, in _ensured
    return fun(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 194, in _publish
    [maybe_declare(entity) for entity in declare]
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 194, in <listcomp>
    [maybe_declare(entity) for entity in declare]
  File "/usr/local/lib/python3.7/site-packages/kombu/messaging.py", line 102, in maybe_declare
    return maybe_declare(entity, self.channel, retry, **retry_policy)
  File "/usr/local/lib/python3.7/site-packages/kombu/common.py", line 121, in maybe_declare
    return _maybe_declare(entity, channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/common.py", line 145, in _maybe_declare
    entity.declare(channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 608, in declare
    self._create_queue(nowait=nowait, channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 617, in _create_queue
    self.queue_declare(nowait=nowait, passive=False, channel=channel)
  File "/usr/local/lib/python3.7/site-packages/kombu/entity.py", line 652, in queue_declare
    nowait=nowait,
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/virtual/base.py", line 531, in queue_declare
    self._new_queue(queue, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 82, in _new_queue
    self._get_or_create(queue)
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 70, in _get_or_create
    obj = self.session.query(self.queue_cls) \
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 65, in session
    _, Session = self._open()
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 56, in _open
    engine = self._engine_from_config()
  File "/usr/local/lib/python3.7/site-packages/kombu/transport/sqlalchemy/__init__.py", line 51, in _engine_from_config
    return create_engine(conninfo.hostname, **transport_options)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py", line 443, in create_engine
    return strategy.create(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "/usr/local/lib/python3.7/site-packages/sqlalchemy/dialects/mysql/mysqldb.py", line 104, in dbapi
    return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'

Here is the setting in the config file (airflow.cfg):

sql_alchemy_conn = postgresql+psycopg2://airflow@localhost:5432/airflow
broker_url = sqla+mysql://airflow:airflow@localhost:3306/airflow
result_backend =  db+postgresql://airflow:airflow@localhost/airflow

I been struggling with this issue for two days now, Please help

Body:
In your airflow.cfg, there should also be a config option for celery_result_backend. Are you able to let us know what this value is set to? If it is not present in your config, set it to the same value as the result_backend

i.e:

celery_result_backend =  db+postgresql://airflow:airflow@localhost/airflow

And then restart the airflow stack to ensure the configuration changes apply.

(I wanted to leave this as a comment but don't have enough rep to do so)


问:
Python math operation on column
Data from json is in df and am trying to ouput to a csv.
I am trying to multiply dataframe column with a fixed value and having issues how data is displayed

I have used the following but the data is still not how i want to display

df_entry['Hours'] = df_entry['Hours'].multiply(2)
df_entry['Hours'] = df_entry['Hours'] * 2

```

<p>Input</p>

```ID, name,hrs
100,AB,37.5
```

<p>Expected</p>

```ID, name,hrs
100,AB,75.0
```

<p>What I am getting</p>

```ID, name,hrs
100,AB,37.537.5
```

答:
That happens because the dtype of the column is str. You need to convert it to float before multiplication.</p>

```<code>df_entry['Hours'] = df_entry['Hours'].astype(float) * 2
</code>```

Title: Python math operation on column

Body:
Data from json is in df and am trying to ouput to a csv.
I am trying to multiply dataframe column with a fixed value and having issues how data is displayed

I have used the following but the data is still not how i want to display

df_entry['Hours'] = df_entry['Hours'].multiply(2)
df_entry['Hours'] = df_entry['Hours'] * 2

Input

ID, name,hrs
100,AB,37.5

Expected

ID, name,hrs
100,AB,75.0

What I am getting

ID, name,hrs
100,AB,37.537.5

Body:
That happens because the dtype of the column is str. You need to convert it to float before multiplication.

df_entry['Hours'] = df_entry['Hours'].astype(float) * 2


问:
Java 6 JAXB/JAXP/SAAJ reference implemetation conflict with Xerces
Can there be conflict between the JAXB/JAXP/SAAJ reference implementation in Java 6 and Xerces 2.x referenced by a WAR in a standard Java EE container like Tomcat and if so how given the classes have the same name, but are in different namespaces?</p>

答: I had a problem with JAXP/SAAJ and Tomcat. I think I had to put the SAAJ jar in the Tomcat endorsed directory to override the existing one, due to a conflict with another class which had the same package and class name</p>

ContentLicense: CC BY-SA 3.0


问:
How does C++ placement delete work internally (C++ runtime)? How to overcome its limitation?
C++ is asymmetric of placement new and placement delete. We are allowed to overload placement new in almost arbitrary ways. However, the placement delete functions are only called from placement new expressions. In particular, they are called if the constructor of the object throws an exception. There's no way to invoke placement delete for application code at all.

I have following confusions and questions to be clarified:

1) Why can't C++ compiler simply reject a placement new method signature if there's no placement delete counterpart defined? Doing that could help kill the possibilities of memory leak in that context.

2) If I have multiple memory pools (managed by application code) and I want different placement new to allocate memory from different pools, there's simply no way to support that due to the the fact that there's no way to know which memory pool the pointer came from in operator delete? (operator delete only has void* info). Is there any way I can accomplish this in C++?

```<code>struct Node {
    void* operator new(size_t size, Strategy s) {
        // Depend on different strategy, allocate memory
        // from different Memory pool
    }

    void operator delete(void* memory, Strategy s) {
        // Return the memory to different Memory pool
        // depends on the Strategy
        // However this delete will only be invoked by
        // c++ runtime if Node constructor throws.
    }

    void operator delete(void* memory, size_t s) {
        // This delete doesn't have any clue about the
        // the strategy. Hence, it can't decide which
        // Memory pool to return to.
    }
}
</code>```

3) In the context of placement new, C++ runtime will invoke placement delete with same argument. How does C++ runtime accomplish this?

答:
This answer assumes the question refers to user-defined placement allocation functions:

```<code>void* operator new  ( std::size_t count, user-defined-args... );
void* operator new[]( std::size_t count, user-defined-args... );
</code>```

and user-defined placement deallocation functions:

```<code>void operator delete  ( void* ptr, args... );
void operator delete[]( void* ptr, args... );
</code>```

The behaviour of these functions is:

operator new:  If defined, called by the custom single-object placement new expression with the matching signature. If a class-specific version is defined, it is called in preference to this. If neither is provided by the user, the placement new expression is ill-formed.

operator new[]: Ditto but for array form.

operator delete: If defined, called by the custom single-object placement new expression with the matching signature if the object's constructor throws an exception. If a class-specific version is defined, it is called in preference to this. If neither is provided by the user, no deallocation function is called.

operator delete[]: Ditto but for array form.

To answer your questions:

Don't pay for what you don't use.  There might be a setup where no deallocation function is required.

You'll have to include a mechanism whereby the value of the void * pointer being deleted can be used to determine which memory pool it is in.  This must be possible because your different pools can't return the same value simultaneously. A naive method might be to have each pool manage a non-overlapping address range and test the pointer against each pool's address range.  Or perhaps you could store metadata in memory before the pointed-to location, e.g. the new version would allocate N+16 bytes, store metadata in the first 16, and return to the user a pointer to the 16th byte of the block).  Or you could keep a data structure associating each active pointer with metadata.

Evaluation of the new-expression for allocating an object of class type will go something like:

Call operator new, passing the arguments

Assuming that succeeds, call class constructor (if it's a class type being allocated).

If the class constructor throws, and matching operator delete exists, call that function, passing the arguments.

Now evaluation of the new-expression is finished, and control returns to either the code that contained the new-expression, or into the exception handling mechanism.

Body:
C++ is asymmetric of placement new and placement delete. We are allowed to overload placement new in almost arbitrary ways. However, the placement delete functions are only called from placement new expressions. In particular, they are called if the constructor of the object throws an exception. There's no way to invoke placement delete for application code at all.

I have following confusions and questions to be clarified:

1) Why can't C++ compiler simply reject a placement new method signature if there's no placement delete counterpart defined? Doing that could help kill the possibilities of memory leak in that context.

2) If I have multiple memory pools (managed by application code) and I want different placement new to allocate memory from different pools, there's simply no way to support that due to the the fact that there's no way to know which memory pool the pointer came from in operator delete? (operator delete only has void* info). Is there any way I can accomplish this in C++?

struct Node {
    void* operator new(size_t size, Strategy s) {
        // Depend on different strategy, allocate memory
        // from different Memory pool
    }

    void operator delete(void* memory, Strategy s) {
        // Return the memory to different Memory pool
        // depends on the Strategy
        // However this delete will only be invoked by
        // c++ runtime if Node constructor throws.
    }

    void operator delete(void* memory, size_t s) {
        // This delete doesn't have any clue about the
        // the strategy. Hence, it can't decide which
        // Memory pool to return to.
    }
}

3) In the context of placement new, C++ runtime will invoke placement delete with same argument. How does C++ runtime accomplish this?

Body:
This answer assumes the question refers to user-defined placement allocation functions:

void* operator new  ( std::size_t count, user-defined-args... );
void* operator new[]( std::size_t count, user-defined-args... );

and user-defined placement deallocation functions:

void operator delete  ( void* ptr, args... );
void operator delete[]( void* ptr, args... );

The behaviour of these functions is:

operator new:  If defined, called by the custom single-object placement new expression with the matching signature. If a class-specific version is defined, it is called in preference to this. If neither is provided by the user, the placement new expression is ill-formed.

operator new[]: Ditto but for array form.

operator delete: If defined, called by the custom single-object placement new expression with the matching signature if the object's constructor throws an exception. If a class-specific version is defined, it is called in preference to this. If neither is provided by the user, no deallocation function is called.

operator delete[]: Ditto but for array form.

To answer your questions:

Don't pay for what you don't use.  There might be a setup where no deallocation function is required.

You'll have to include a mechanism whereby the value of the void * pointer being deleted can be used to determine which memory pool it is in.  This must be possible because your different pools can't return the same value simultaneously. A naive method might be to have each pool manage a non-overlapping address range and test the pointer against each pool's address range.  Or perhaps you could store metadata in memory before the pointed-to location, e.g. the new version would allocate N+16 bytes, store metadata in the first 16, and return to the user a pointer to the 16th byte of the block).  Or you could keep a data structure associating each active pointer with metadata.

Evaluation of the new-expression for allocating an object of class type will go something like:

Call operator new, passing the arguments

Assuming that succeeds, call class constructor (if it's a class type being allocated).

If the class constructor throws, and matching operator delete exists, call that function, passing the arguments.

Now evaluation of the new-expression is finished, and control returns to either the code that contained the new-expression, or into the exception handling mechanism.


问:
AWS S3 copy assets between two buckets
With the command line interface I can copy files between two buckets.

```<code>$ aws s3 sync s3://mybucket-src s3://mybucket-target --exclude *.tmp
</code>```

This will copy from one source bucket to another target bucket. But I want to copy file types (images, documents, videos) to their respective folders in target bucket.

Images go into source_files/images

Documents go into source_files/pdf

Videos go into source_files/videos

Also as soon as if new files hit source bucket, they should be copied to their respective folders in target bucket.

答:
if you are using windows powershell:

```<code>  aws s3 ls  s3://bucket-source | ForEach-Object -Process {[System.IO.Path]::GetExtension($_).Split(".")[1]} | ForEach-Object -Process {aws s3 sync s3://bucket-source s3://bucket-destination/$_/ --exclude "*" --include  "*.$_" }
</code>```

Explanation:

Get the list of files in source bucket

aws s3 ls  s3://bucket-source

find their extensions

ForEach-Object -Process {[System.IO.Path]::GetExtension($_).Split(".")[1]}

copy to the destination bucket. It creates folders for each extension and copy that type of files to it:

ForEach-Object -Process {aws s3 sync s3://bucket-source s3://bucket-destination/$/ --exclude "*" --include  "*.$"

Title: AWS S3 copy assets between two buckets

Body:
With the command line interface I can copy files between two buckets.

$ aws s3 sync s3://mybucket-src s3://mybucket-target --exclude *.tmp

This will copy from one source bucket to another target bucket. But I want to copy file types (images, documents, videos) to their respective folders in target bucket.

Images go into source_files/images

Documents go into source_files/pdf

Videos go into source_files/videos

Also as soon as if new files hit source bucket, they should be copied to their respective folders in target bucket.

Body:
if you are using windows powershell:

  aws s3 ls  s3://bucket-source | ForEach-Object -Process {[System.IO.Path]::GetExtension($_).Split(".")[1]} | ForEach-Object -Process {aws s3 sync s3://bucket-source s3://bucket-destination/$_/ --exclude "*" --include  "*.$_" }

Explanation:

Get the list of files in source bucket

aws s3 ls  s3://bucket-source

find their extensions

ForEach-Object -Process {[System.IO.Path]::GetExtension($_).Split(".")[1]}

copy to the destination bucket. It creates folders for each extension and copy that type of files to it:

ForEach-Object -Process {aws s3 sync s3://bucket-source s3://bucket-destination/$/ --exclude "*" --include  "*.$"


问:
Using Regex to split hashtag and search items
I have a regex expression to list the hashtags in a search entered into my app that looks like this:

```<code>text.match(/#[a-z]+/gi);
</code>```

and a regex expression to list all the words in a search

```<code>text.match(/\S+\s*/g);
</code>```

What I want to be able to do is to split hashtags and words into two separate lists so I want to be able to update the second regex expression so that it ignores hashtags. How would I achieve this?

For example, if the input is:

"Hello this is #my #question for today"

The expected output should be 2 arrays:

```<code>[Hello, this, is, for, today],
[my, question]
</code>```

I would also like to make the hashtag regex return the words without the hashtags if possible otherwise I could just string split the words in the array later if not possible

答:
You can do this with both negative and positive lookbehinds. Obviously, the negative lookbehinds will match works without your 'hash tags', and the positive will match on the ones with them.

Negative LookBehind to match your normal search terms

```<code>/\b(?<!#)[^#\s]+/g
</code>```

\b ensures you are looking at the beginning of a word

(?<!) is a negative lookbehind. Prevents the match of #

Regex101 Example

Positive LookBehind to match your "hashed" words

```<code>/(?<=#)\w+/g
</code>```

(?<=) is a positive lookbehind, allows a match if # is found behind \w+

Regex101 Example

Additional information regarding Lookarounds

Body:
I have a regex expression to list the hashtags in a search entered into my app that looks like this:

text.match(/#[a-z]+/gi);

and a regex expression to list all the words in a search

text.match(/\S+\s*/g);

What I want to be able to do is to split hashtags and words into two separate lists so I want to be able to update the second regex expression so that it ignores hashtags. How would I achieve this?

For example, if the input is:

"Hello this is #my #question for today"

The expected output should be 2 arrays:

[Hello, this, is, for, today],
[my, question]

I would also like to make the hashtag regex return the words without the hashtags if possible otherwise I could just string split the words in the array later if not possible

Body:
You can do this with both negative and positive lookbehinds. Obviously, the negative lookbehinds will match works without your 'hash tags', and the positive will match on the ones with them.

Negative LookBehind to match your normal search terms

/\b(?<!#)[^#\s]+/g

\b ensures you are looking at the beginning of a word

(?<!) is a negative lookbehind. Prevents the match of #

Regex101 Example

Positive LookBehind to match your "hashed" words

/(?<=#)\w+/g

(?<=) is a positive lookbehind, allows a match if # is found behind \w+

Regex101 Example

Additional information regarding Lookarounds


问:
Reading an API which is returning StreamingResponseBody as response
I have an API which is returning huge data ( > 7 MB) in JSON format. An IOS device is accessing this API and storing data in to local device storage. Since response size is huge, user is experiencing long delay.

I created another API with same data but this time I have used StreamingResponseBody to write output directly to the response object as stream. Now response size reduced to 2 MB. But how client device (IOS/Angular) can read the response? Because when I hit the API from postman the output is not readable.

Here is the controller code -

```<code>@GetMapping( value = "/materials/stream")
    public ResponseEntity<StreamingResponseBody> getMaterialsStreamed() {

        StreamingResponseBody responseBody = outputStream -> {
            try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {
                oos.writeObject(service.getMaterials()); // service.getMaterials() is returning Iterable<Material>
            }
        };

        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generic_file_name.json")
                .contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody);
    }
</code>```

答: you are returning a stream of bytes, postman will just print it as bytes(which is unreadable). you need to save the stream first and then read it as a normal file(i.e downloading a file and open it using IOS/Angular).</p>

Body:
I have an API which is returning huge data ( > 7 MB) in JSON format. An IOS device is accessing this API and storing data in to local device storage. Since response size is huge, user is experiencing long delay.

I created another API with same data but this time I have used StreamingResponseBody to write output directly to the response object as stream. Now response size reduced to 2 MB. But how client device (IOS/Angular) can read the response? Because when I hit the API from postman the output is not readable.

Here is the controller code -

@GetMapping( value = "/materials/stream")
    public ResponseEntity<StreamingResponseBody> getMaterialsStreamed() {

        StreamingResponseBody responseBody = outputStream -> {
            try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {
                oos.writeObject(service.getMaterials()); // service.getMaterials() is returning Iterable<Material>
            }
        };

        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generic_file_name.json")
                .contentType(MediaType.APPLICATION_OCTET_STREAM).body(responseBody);
    }


问:
Is it possible to inject a process and get the given handles then use them to inject another process?
I'm trying to figure out a way to inject an already running process, to filter the given handles to that process, then using the chosen handle to inject another process with the same access privileges.

I'm not sure if this can be done by injecting a dynamic library, that can get the work done.

I wonder if that's possible without affecting the handle granted access,
from a user-mode level. I've been looking for an idea so that i can understand how this works but i can't find something useful.

答:
The answer is yes check this: https://easyhook.github.io/
There are good examples in the pages you can follow tutorials this one might interest you: http://easyhook.github.io/tutorials/nativeremotehook.html</p>


问:
How to create an array given a line of input with integers where the first integer is the length?
I am trying to create a function that returns the address of an array which is created by taking a single line of input from the user where the first integer is the length. For example if the input from the user was "5 19 8 26 12 9" the corresponding array would be [19, 8, 26, 12, 9] (Which is of length 5).

The way I went about doing this was rather than taking input from the user while after the function ran I took it as arguments (argc,argv) Ex. "./a.out 5 19 8 26 12 9". I was wondering if there were any other possible solutions that exist perhaps using scanf or cin...

答:
This is the general question of how to designate the extent of a sequence of data items which has dynamic length.

Interestingly, there aren't actually many programming patterns to go about this (though there are many ways to implement them). The problem effectively boils down to a simple question: how do I know when to stop taking values?

When you receive values that are already stored (e.g. argc/argv or passing in an array or some other container), you already have the values and you know how many there are. This is the trivial case. Parsing data from a file or from the terminal is where things start to get interesting.

Here's a list of frequently-used "stopping mechanisms" (with all others to my knowledge being specific applications of prefix and/or suffix).

Prefixed Sequence

This is the method you described. In its most general sense it involves prefixing the input with something that tells you how much data is there. This could be human-level as the number of elements following it, or machine-level as e.g. the number of bytes to receive from a network connection.

Here's an example that uses the number of elements in an input sequence as a prefix.

```<code>std::vector<int> vec;
int count, temp;

std::cin >> count;
for (int i = 0; i < count; ++i)
{
    std::cin >> temp;
    vec.push_back(temp);
}
</code>```

Note that using this method you immediately know the total number of elements in the sequence, which you can use to simplify the code and reduce the number of dynamic allocations:

```<code>std::vector<int> vec;
int count;

std::cin >> count;
vec.resize(count); // performs only one allocation
for (int i = 0; i < count; ++i) std::cin >> vec[i];
</code>```

Example user input (console or file):

```<code>4 3 5
4 88 -90
2
</code>```

Resulting values (vec):

```<code>3, 5, 4, 88
</code>```

Suffixed Sequence

Similar to the prefix sequence, you can also suffix the sequence with some value that denotes where to stop. This is typically referred to as a terminator (e.g. C-style strings are terminated by a a zero byte i.e. '\0').

This example shows how to read a sequence of non-negative integers. We use the first negative value as the stopping condition:

```<code>std::vector<int> vec;
int temp;

while (std::cin >> temp && temp >= 0) vec.push_back(temp);
</code>```

Example user input (console or file):

```<code>4 3 5
4 88 -90
2
</code>```

Resulting values (vec):

```<code>4, 3, 5, 4, 88
</code>```

Reaching EOF

EOF (end of file) can be used as a stopping mechanism if you're reading from a file. It's essentially a system-specific combination of prefix and/or suffix. For instance, the specific filesystem structure being used will typically store the length of the file in bytes. This is essentially the prefix method (although the prefix value doesn't actually appear in the data sequence in this case).

This method is popular because it's very common to have a file that contains only a sequence of same-type elements. It can be used with cin, but only if cin has been redirected from a file (as otherwise you'd never - traditionally - reach the end since it'll just interactively wait for more input as a console session).

```<code>std::vector<int> vec;
std::ifstream file("nums.txt");
int temp;

while (file >> temp) vec.push_back(temp);
</code>```

In fact this use is so common that the STL added std::istream_iterator for making this easy to write in a safe, library-ish way. In this case it's not really better, but depending on what you're doing iterators can be more convenient - e.g. you could feed them into std::accumulate() to get the sum. Here's an example of using std::istream_iterator to do the same thing:

```<code>std::vector<int> vec;
std::ifstream file("nums.txt");

std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(),
    std::back_inserter(vec));
</code>```

Example user input (file):

```<code>4 3 5
4 88 -90
2
</code>```

Resulting values (vec):

```<code>4, 3, 5, 4, 88, -90, 2
</code>```

End of Line

Using the end of line (i.e. '\n') as a stopping condition is technically a suffixed sequence method, but it's different enough and common enough that I feel it should be addressed directly, especially in regards to what you're trying to accomplish.

You could use the unformatted input functions line std::cin.get() to manually search for the characters you want to keep or ignore, but this is tedious and error-prone. The method I'll be demonstrating is slower than the manual method, but if performance is not a concern they are vastly superior (especially for more complex types with overloaded stream extraction operators).

We'll read an entire line of text from cin (which is terminated by new line character '\n'), and then parse out its values after the fact.

```<code>std::vector<int> vec;
std::string line;
int temp;

std::getline(std::cin, line);
std::istringstream ss(line);
while (ss >> temp) vec.push_back(temp);
</code>```

And if you want to use standard utilities (or if you need iterators):

```<code>std::vector<int> vec;
std::string line;

std::getline(std::cin, line);
std::istringstream ss(line);
std::copy(std::istream_itereator<int>(ss), std::istream_iterator<int>(),
    std::back_inserter(vec));
</code>```

Example user input (console or file):

```<code>4 3 5
4 88 -90
2
</code>```

Resulting values (vec):

```<code>4, 3, 5
</code>```

Body:
This is the general question of how to designate the extent of a sequence of data items which has dynamic length.

Interestingly, there aren't actually many programming patterns to go about this (though there are many ways to implement them). The problem effectively boils down to a simple question: how do I know when to stop taking values?

When you receive values that are already stored (e.g. argc/argv or passing in an array or some other container), you already have the values and you know how many there are. This is the trivial case. Parsing data from a file or from the terminal is where things start to get interesting.

Here's a list of frequently-used "stopping mechanisms" (with all others to my knowledge being specific applications of prefix and/or suffix).

Prefixed Sequence

This is the method you described. In its most general sense it involves prefixing the input with something that tells you how much data is there. This could be human-level as the number of elements following it, or machine-level as e.g. the number of bytes to receive from a network connection.

Here's an example that uses the number of elements in an input sequence as a prefix.

std::vector<int> vec;
int count, temp;

std::cin >> count;
for (int i = 0; i < count; ++i)
{
    std::cin >> temp;
    vec.push_back(temp);
}

Note that using this method you immediately know the total number of elements in the sequence, which you can use to simplify the code and reduce the number of dynamic allocations:

std::vector<int> vec;
int count;

std::cin >> count;
vec.resize(count); // performs only one allocation
for (int i = 0; i < count; ++i) std::cin >> vec[i];

Example user input (console or file):

4 3 5
4 88 -90
2

Resulting values (vec):

3, 5, 4, 88

Suffixed Sequence

Similar to the prefix sequence, you can also suffix the sequence with some value that denotes where to stop. This is typically referred to as a terminator (e.g. C-style strings are terminated by a a zero byte i.e. '\0').

This example shows how to read a sequence of non-negative integers. We use the first negative value as the stopping condition:

std::vector<int> vec;
int temp;

while (std::cin >> temp && temp >= 0) vec.push_back(temp);

Example user input (console or file):

4 3 5
4 88 -90
2

Resulting values (vec):

4, 3, 5, 4, 88

Reaching EOF

EOF (end of file) can be used as a stopping mechanism if you're reading from a file. It's essentially a system-specific combination of prefix and/or suffix. For instance, the specific filesystem structure being used will typically store the length of the file in bytes. This is essentially the prefix method (although the prefix value doesn't actually appear in the data sequence in this case).

This method is popular because it's very common to have a file that contains only a sequence of same-type elements. It can be used with cin, but only if cin has been redirected from a file (as otherwise you'd never - traditionally - reach the end since it'll just interactively wait for more input as a console session).

std::vector<int> vec;
std::ifstream file("nums.txt");
int temp;

while (file >> temp) vec.push_back(temp);

In fact this use is so common that the STL added std::istream_iterator for making this easy to write in a safe, library-ish way. In this case it's not really better, but depending on what you're doing iterators can be more convenient - e.g. you could feed them into std::accumulate() to get the sum. Here's an example of using std::istream_iterator to do the same thing:

std::vector<int> vec;
std::ifstream file("nums.txt");

std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(),
    std::back_inserter(vec));

Example user input (file):

4 3 5
4 88 -90
2

Resulting values (vec):

4, 3, 5, 4, 88, -90, 2

End of Line

Using the end of line (i.e. '\n') as a stopping condition is technically a suffixed sequence method, but it's different enough and common enough that I feel it should be addressed directly, especially in regards to what you're trying to accomplish.

You could use the unformatted input functions line std::cin.get() to manually search for the characters you want to keep or ignore, but this is tedious and error-prone. The method I'll be demonstrating is slower than the manual method, but if performance is not a concern they are vastly superior (especially for more complex types with overloaded stream extraction operators).

We'll read an entire line of text from cin (which is terminated by new line character '\n'), and then parse out its values after the fact.

std::vector<int> vec;
std::string line;
int temp;

std::getline(std::cin, line);
std::istringstream ss(line);
while (ss >> temp) vec.push_back(temp);

And if you want to use standard utilities (or if you need iterators):

std::vector<int> vec;
std::string line;

std::getline(std::cin, line);
std::istringstream ss(line);
std::copy(std::istream_itereator<int>(ss), std::istream_iterator<int>(),
    std::back_inserter(vec));

Example user input (console or file):

4 3 5
4 88 -90
2

Resulting values (vec):

4, 3, 5


问:
Typescript keyof one interface extending other interface
I have one Basic interface:

```<code>interface Basic {
  [key: string]: {
    data: string;
  };
}
</code>```

Another interface extending it:

```<code>interface Another extends Basic {
  'onekey': OneKeyData;
  'secondkey': SeconKeyData;
}
</code>```

My issue with is when use generic T extends keyof Another it allows any string keys because of Basic interface. OneKeyData and SecondKeyData they all contain data property as in Basic. I would remove extends Basic if it wasn't used in other place like this:

```<code>interface Options<TKey extends keyof Another> {
  field: Another[TKey]['data'];
}
</code>```

What is the best solution in this case? Is it possible to get keyof only Another interface?

答:
As mentioned in the comments, it is possible to get keyof ignoring the index signature using a trick with conditional type inference.

```<code>type KnownKeys<T> = {
    [K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never;

type KnownKeysOfAnother = KnownKeys<Another> // "oneKey" | "secondKey";
</code>```

Is that what you're looking for?

Body:
I have one Basic interface:

interface Basic {
  [key: string]: {
    data: string;
  };
}

Another interface extending it:

interface Another extends Basic {
  'onekey': OneKeyData;
  'secondkey': SeconKeyData;
}

My issue with is when use generic T extends keyof Another it allows any string keys because of Basic interface. OneKeyData and SecondKeyData they all contain data property as in Basic. I would remove extends Basic if it wasn't used in other place like this:

interface Options<TKey extends keyof Another> {
  field: Another[TKey]['data'];
}

What is the best solution in this case? Is it possible to get keyof only Another interface?

Body:
As mentioned in the comments, it is possible to get keyof ignoring the index signature using a trick with conditional type inference.

type KnownKeys<T> = {
    [K in keyof T]: string extends K ? never : number extends K ? never : K
} extends { [_ in keyof T]: infer U } ? U : never;

type KnownKeysOfAnother = KnownKeys<Another> // "oneKey" | "secondKey";

Is that what you're looking for?


问:
TypeError: _ReanimatedModule.default.animateNextTransition is not a function in React-native-navigation

Current Behavior

When you click on the text, you get an error with the title.

Expected Behavior

I hoped that the screen would move smoothly without being cut off or showing a white screen.

How to reproduce

App.js

import React from "react";
import createAnimatedSwitchNavigator from "react-navigation-animated-switch";
import { Transition } from "react-native-reanimated";
import {
  createDrawerNavigator,
  createAppContainer,
  createStackNavigator
} from "react-navigation";
import A from "./A";
import B from "./B";

const MySwitch = createAnimatedSwitchNavigator(
  {
    Home: A,
    Other: B
  },
  {
    initialRouteName: "Home",
    headerMode: "none"
  },
  {
    // The previous screen will slide to the bottom while the next screen will fade in
    transition: (
      <Transition.Together>
        <Transition.Out
          type="slide-bottom"
          durationMs={400}
          interpolation="easeIn"
        />
        <Transition.In type="fade" durationMs={500} />
      </Transition.Together>
    )
  }
);
const HomeScreenRouter = createAppContainer(MySwitch);

export default HomeScreenRouter;
```

<p>A.js</p>

<pre class="lang-js prettyprint-override"><code>import React from "react";
import { StyleSheet, Text, View, TouchableHighlight } from "react-native";

export default class A extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress={() => this.props.navigation.navigate("Other")}>
          Open up App.js to start working on your app!
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});
</code>```

B.js

import React from "react";
import { StyleSheet, Text, View } from "react-native";

export default class B extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>B screen</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});
```

Your Environment

| react-navigation |  "^3.11.0"

| react-native     | "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz"

| node             |  v10.16.0

| react-native-reanimated | "^1.0.1"

| react-navigation-animated-switch | "^0.2.0"

| npm or yarn      | 6.9.0

Please help me a lot

Thank you for your help.

答:
it's not currently available in sdk 32. sdk 33 is coming  soon.

this is documented in the readme

Body:
Current Behavior

When you click on the text, you get an error with the title.

Expected Behavior

I hoped that the screen would move smoothly without being cut off or showing a white screen.

How to reproduce

App.js

import React from "react";
import createAnimatedSwitchNavigator from "react-navigation-animated-switch";
import { Transition } from "react-native-reanimated";
import {
  createDrawerNavigator,
  createAppContainer,
  createStackNavigator
} from "react-navigation";
import A from "./A";
import B from "./B";

const MySwitch = createAnimatedSwitchNavigator(
  {
    Home: A,
    Other: B
  },
  {
    initialRouteName: "Home",
    headerMode: "none"
  },
  {
    // The previous screen will slide to the bottom while the next screen will fade in
    transition: (
      <Transition.Together>
        <Transition.Out
          type="slide-bottom"
          durationMs={400}
          interpolation="easeIn"
        />
        <Transition.In type="fade" durationMs={500} />
      </Transition.Together>
    )
  }
);
const HomeScreenRouter = createAppContainer(MySwitch);

export default HomeScreenRouter;

A.js

import React from "react";
import { StyleSheet, Text, View, TouchableHighlight } from "react-native";

export default class A extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Text onPress={() => this.props.navigation.navigate("Other")}>
          Open up App.js to start working on your app!
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

B.js

import React from "react";
import { StyleSheet, Text, View } from "react-native";

export default class B extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>B screen</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

Your Environment

| react-navigation |  "^3.11.0"

| react-native     | "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz"

| node             |  v10.16.0

| react-native-reanimated | "^1.0.1"

| react-navigation-animated-switch | "^0.2.0"

| npm or yarn      | 6.9.0

Please help me a lot

Thank you for your help.


问:
How to create references to objects created in a loop?
I'm sure this question has been asked but I cannot find it (on SO or Google) for my life.

How can I most effectively create a reference to multiple objects that I create in a loop?
In this specific case, I am using Swing to add JButtons to a GridLayout.

```<code>int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    add(new JButton("" + i));}
</code>```

If later I want to change the text on the buttons, how would I do so? Say, if I wanted to change button number 8:

```<code>buttonEight.setText("DO NOT CLICK!!!);
</code>```

How would I create a reference to the button with the 8 on it from buttonEight?

The only thing I can think of is creating a bunch of instance variables before the loop. Except... Well. Actually , that wouldn't work (I don't think)

Something that would do this:

```<code>JButton button8;
    for (int i = 0; i < numOfButtons; i++){

    button + i = new JButton(""+ i);
    //like, if i = 8 then button + i gets me button8 to reference it or something?
    //obviously that doesn't work
    }

button8.setText("DO NOT CLICK!!!);
</code>```

and also I'd be in trouble creating the right number of instance variables if numOfButtons is variable.

How should I do this?

答:
Or, if you wanted to set the text of only the eighth button, you could use a conditional to single out that button:

```<code>for (int i=0;i<numOfButtons;i++) {
    if (i==7) {
        add(new JButton("DO NOT CLICK!");
    } else {
        add(new JButton(""+i);
    }
}
</code>```

which will save memory space in your program than if you use an ArrayList.

Body:
I'm sure this question has been asked but I cannot find it (on SO or Google) for my life.

How can I most effectively create a reference to multiple objects that I create in a loop?
In this specific case, I am using Swing to add JButtons to a GridLayout.

int numOfButtons = 10;
for (int i = 0; i < numOfButtons; i++){
    add(new JButton("" + i));}

If later I want to change the text on the buttons, how would I do so? Say, if I wanted to change button number 8:

buttonEight.setText("DO NOT CLICK!!!);

How would I create a reference to the button with the 8 on it from buttonEight?

The only thing I can think of is creating a bunch of instance variables before the loop. Except... Well. Actually , that wouldn't work (I don't think)

Something that would do this:

JButton button8;
    for (int i = 0; i < numOfButtons; i++){

    button + i = new JButton(""+ i);
    //like, if i = 8 then button + i gets me button8 to reference it or something?
    //obviously that doesn't work
    }

button8.setText("DO NOT CLICK!!!);

and also I'd be in trouble creating the right number of instance variables if numOfButtons is variable.

How should I do this?

Body:
Or, if you wanted to set the text of only the eighth button, you could use a conditional to single out that button:

for (int i=0;i<numOfButtons;i++) {
    if (i==7) {
        add(new JButton("DO NOT CLICK!");
    } else {
        add(new JButton(""+i);
    }
}

which will save memory space in your program than if you use an ArrayList.


问:
How do you set the username (APP_USER) as the email from single-sign on in APEX?
I'm setting up an APEX app using single-sign on following this tutorial and the app now allows sign-in to occur. However the value of APP_USER does not equal the email address that is logged in through Microsoft - it defaults to APEX_PUBLIC_USER. I want to use the username to provide role-based application access control.

I've looked around for solutions and found post authentication code that looks like it should help and I have tried to adapt.

Using

```<code>procedure post_authenticate
is
begin
    w14_auth_pkh.post_authenticate(
        p_username => :APP_USER);
end post_authenticate
</code>```

or

apex_custom_auth.set_user (p_user => :APP_USER);

I get the following error messages when applying changes from within the authenticate scheme section:

ORA-06550: line 8, column 1: PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following: ; The symbol ";" was substituted for "BEGIN" to continue.

or

ORA-06550: line 2, column 17: PLS-00103: Encountered the symbol "." when expecting one of the following: constant exception   table columns long double ref char time timestamp interval date binary national character nchar The symbol "" was substituted for "." to continue.

答:
You first code sample uses a package of Dimitri's, and is missing a semi-colon at the end.

Your relevant code would be
APEX_CUSTOM_AUTH.SET_USER();

Alternatively, you could change the Username attribute to something that has been made available via the user info endpoint URL.

Body:
I'm setting up an APEX app using single-sign on following this tutorial and the app now allows sign-in to occur. However the value of APP_USER does not equal the email address that is logged in through Microsoft - it defaults to APEX_PUBLIC_USER. I want to use the username to provide role-based application access control.

I've looked around for solutions and found post authentication code that looks like it should help and I have tried to adapt.

Using

procedure post_authenticate
is
begin
    w14_auth_pkh.post_authenticate(
        p_username => :APP_USER);
end post_authenticate

or

apex_custom_auth.set_user (p_user => :APP_USER);

I get the following error messages when applying changes from within the authenticate scheme section:

ORA-06550: line 8, column 1: PLS-00103: Encountered the symbol "BEGIN" when expecting one of the following: ; The symbol ";" was substituted for "BEGIN" to continue.

or

ORA-06550: line 2, column 17: PLS-00103: Encountered the symbol "." when expecting one of the following: constant exception   table columns long double ref char time timestamp interval date binary national character nchar The symbol "" was substituted for "." to continue.


问:
Implement 3 way handshake for TCP in Java
I want to implement TCP protocol using Java. I've read Sun documentation and examples but all of them simply open a socket, client waits for server to accept the connection and then sends data.

I wonder how I can implement the three way handshake and data validation using Java? How do server and client exchange sequence number? Does Java provide any class/methods (or at least interface) to implement three way handshake?

Can someone please give me some ideas, or link to some examples?

Thanks in advance,

答: Yes it is possible. You can access the IP layer in Java using a library like JPCap. The rest of the TCP implementation can be built by you. This is of course a non-trivial task.</p>

ContentLicense: CC BY-SA 2.5


问:
Auto property initialization with anonymous function
I'm trying to get rid of some code with anonymous functions and classes.

I stuck on this:

```<code>public List<Object> Years { get; set; } = GetYears();

private static List<Object> GetYears()
{
    List<Object> retList = new List<Object>();

    retList.Add(new { Value = (byte)255, Name = "Any" });
    retList.Add(new { Value = (byte)254, Name = "None" });

    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}
</code>```

Is it possible to get rid of static GetYears() method?

I mean something like this:

```<code>public List<Object> Years { get; set; } = () =>
{
    List<Object> retList = new List<Object>();
    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}
</code>```

The problem is that the field initializer cannot reference non-static method.

Is it possible to get around this?

Edit: I added these 2 lines of code:

```<code>retList.Add(new { Value = (byte)255, Name = "None" });
retList.Add(new { Value = (byte)254, Name = "Any" });
</code>```

答:
Technically speaking, you can do something like this

```<code>public class LambdaInitalization {
    public List<Object> Years = ((Func<List<Object>>)(() =>
    {
        List<Object> retList = new List<Object>();
        for (byte i = 0; i < 50; i++)
        {
            retList.Add(new { Value = i, Name = (2000 + i).ToString() });
        }
        return retList;
    }))();
}
</code>```

Which creates an anonymous function that returns a List<Object>, then runs it (unfortunately it cannot be implied, it must be an explicit cast).

The much better solution is to just use the constructor, to do pretty much exactly what the constructor exists for.

```<code>public class CtorInitalization {
    public List<Object> Years { get; set; }

    public CtorInitalization() {
        Years = new List<Object>();
        for (byte i = 0; i < 50; i++)
        {
            Years.Add(new { Value = i, Name = (2000 + i).ToString() });
        }
    }
}
</code>```

Funnily enough, the lamda initialization will compile into the constructor anyway, so there is no valid use functionally speaking for defining it outside of the constructor.

See both of these in action here: https://dotnetfiddle.net/1f62Hj

Body:
I'm trying to get rid of some code with anonymous functions and classes.

I stuck on this:

public List<Object> Years { get; set; } = GetYears();

private static List<Object> GetYears()
{
    List<Object> retList = new List<Object>();

    retList.Add(new { Value = (byte)255, Name = "Any" });
    retList.Add(new { Value = (byte)254, Name = "None" });

    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}

Is it possible to get rid of static GetYears() method?

I mean something like this:

public List<Object> Years { get; set; } = () =>
{
    List<Object> retList = new List<Object>();
    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}

The problem is that the field initializer cannot reference non-static method.

Is it possible to get around this?

Edit: I added these 2 lines of code:

retList.Add(new { Value = (byte)255, Name = "None" });
retList.Add(new { Value = (byte)254, Name = "Any" });

Body:
Technically speaking, you can do something like this

public class LambdaInitalization {
    public List<Object> Years = ((Func<List<Object>>)(() =>
    {
        List<Object> retList = new List<Object>();
        for (byte i = 0; i < 50; i++)
        {
            retList.Add(new { Value = i, Name = (2000 + i).ToString() });
        }
        return retList;
    }))();
}

Which creates an anonymous function that returns a List<Object>, then runs it (unfortunately it cannot be implied, it must be an explicit cast).

The much better solution is to just use the constructor, to do pretty much exactly what the constructor exists for.

public class CtorInitalization {
    public List<Object> Years { get; set; }

    public CtorInitalization() {
        Years = new List<Object>();
        for (byte i = 0; i < 50; i++)
        {
            Years.Add(new { Value = i, Name = (2000 + i).ToString() });
        }
    }
}

Funnily enough, the lamda initialization will compile into the constructor anyway, so there is no valid use functionally speaking for defining it outside of the constructor.

See both of these in action here: https://dotnetfiddle.net/1f62Hj


问:
AppleScripts: display notification is too fast to display properly
I don't recall if this changed recently (I'm on 10.13), but when I call display notification in a fast loop, the notification changes to "N new notifications". Totally unhelpful for most of my scripts.

I've tried sporadically calling the notification with

```<code>if notificationCount / someDenom = (notificationCount / someDenom) as integer then display notification "etc."
</code>```

which works if how long a loop will take is a known quantity. But half the time, I'm calling the scripts sometimes on a local drive, other times over a network, and the results are unpredictable. Either I don't get frequent enough notifications, or it collapses into the too many display sometimes.

Thinking it's entirely possible that this is baked into macOS and there's nothing I can do except the above, but thought someone might have a bright idea.

[Edited to add: just had one myself, a subroutine which notes the datestamp and elapsed time since the last call, then only calls the notification if N seconds have passed. I'll give that a try.]

[Edited again: well, that technically works, but it adds 0.68 seconds to every notification, which is a pretty high cost in a tight loop.]

答:
Not sure if this is what you are looking for but it works for scripts:

```<code>delay 1
display notification "uno momento..."
delay 1
display notification "it works!"
</code>```

Meaning, figure out a way to add a delay between notifications if they're not appearing / play with the delay time until it works for your purposes. I found using 1 sec is OK since users will read at that speed, and it allows the OS time to catch up and ensures all notifications are listed in order AND all of them show up / are displayed to user.

I found I also have to include a delay prior to the first notification, if sending notifications in a group...again ensuring first notify displays properly.

Body:
I don't recall if this changed recently (I'm on 10.13), but when I call display notification in a fast loop, the notification changes to "N new notifications". Totally unhelpful for most of my scripts.

I've tried sporadically calling the notification with

if notificationCount / someDenom = (notificationCount / someDenom) as integer then display notification "etc."

which works if how long a loop will take is a known quantity. But half the time, I'm calling the scripts sometimes on a local drive, other times over a network, and the results are unpredictable. Either I don't get frequent enough notifications, or it collapses into the too many display sometimes.

Thinking it's entirely possible that this is baked into macOS and there's nothing I can do except the above, but thought someone might have a bright idea.

[Edited to add: just had one myself, a subroutine which notes the datestamp and elapsed time since the last call, then only calls the notification if N seconds have passed. I'll give that a try.]

[Edited again: well, that technically works, but it adds 0.68 seconds to every notification, which is a pretty high cost in a tight loop.]

Body:
Not sure if this is what you are looking for but it works for scripts:

delay 1
display notification "uno momento..."
delay 1
display notification "it works!"

Meaning, figure out a way to add a delay between notifications if they're not appearing / play with the delay time until it works for your purposes. I found using 1 sec is OK since users will read at that speed, and it allows the OS time to catch up and ensures all notifications are listed in order AND all of them show up / are displayed to user.

I found I also have to include a delay prior to the first notification, if sending notifications in a group...again ensuring first notify displays properly.


问:
Whats the difference between a module and a library in Python?
I have background in Java and I am new to Python. I want to make sure I understand correctly Python terminology before I go ahead.

My understanding of a module is: a script which can be imported by many scripts, to make reading easier. Just like in java you have a class, and that class can be imported by many other classes.

My understanding of a library is: A library contains many modules which are separated by its use.

My question is: Are libraries like packages, where you have a package e.g. called food, then:

chocolate.py

sweets.py

biscuts.py

are contained in the food package?

Or do libraries use packages, so if we had another package drink:

milk.py

juice.py

contained in the package. The library contains two packages?

Also, an application programming interface (API) usually contains a set of libraries is this at the top of the hierarchy:

API

Library

Package

Module

Script

So an API will consist off all from 2-5?

答:
I will try to answer this without using terms the earliest of beginners would use,and explain why or how they used differently, along with the most "official" and/or most understood or uniform use of the terms.

It can be confusing, and I confused myself thinking to hard, so don't think to much about it. Anyways context matters, greatly.

Library- Most often will refer to the general library or another collection created with a similar format and use. The General Library is the sum of 'standard', popular and widely used Modules, witch can be thought of as single file tools, for now or short cuts making things possible or faster. The general library is an option most people enable when installing Python. Because it has this name "Python General Library" it is used often with similar structure, and ideas. Witch is simply to have a bunch of Modules, maybe even packages grouped together, usually in a list. The list is usually to download them. Generally it is just related files, with similar interests. That is the easiest way to describe it.

Module- A Module refers to a file. The file has script 'in it' and the name of the file is the name of the module, Python files end with .py. All the file contains is code that ran together makes something happen, by using functions, strings ect.
Main modules you probably see most often are popular because they are special modules that can get info from other files/modules.
It is confusing because the name of the file and module are equal and just drop the .py. Really it's just code you can use as a shortcut written by somebody to make something easier or possible.

Package- This is a termis used to generally sometimes, although context makes a difference. The most common use from my experience is multiple modules (or files) that are grouped together. Why they are grouped together can be for a few reasons, that is when context matters.
These are ways I have noticed the term package(s) used. They are a group of Downloaded, created and/or stored modules. Which can all be true, or only 1, but really it is just a file that references other files, that need to be in the correct structure or format, and that entire sum is the package itself, installed or may have been included in the python general library. A package can contain modules(.py files) because they depend on each other and sometimes may not work correctly, or at all. There is always a common goal of every part (module/file) of a package, and the total sum of all of the parts is the package itself.

Most often in Python Packages are Modules, because the package name is the name of the module that is used to connect all the pieces. So you can input a package because it is a module, also allows it to call upon other modules, that are not packages because they only perform a certain function, or task don't involve other files. Packages have a goal, and each module works together to achieve that final goal.

Most confusion come from a simple file file name or prefix to a file, used as the module name then again the package name.

Remember Modules and Packages can be installed. Library is usually a generic term for listing, or formatting a group of modules and packages. Much like Pythons general library. A hierarchy would not work, APIs do not belong really, and if you did they could be anywhere and every ware involving Script, Module, and Packages, the worl library being such a general word, easily applied to many things, also makes API able to sit above or below that. Some Modules can be based off of other code, and that is the only time I think it would relate to a pure Python related discussion.


问:
Locking issue with LimitedConcurrencyLevelTaskScheduler and aync/await
I'm struggling to understand what's happening in this simple program.

In the example below I have a task factory that uses the  LimitedConcurrencyLevelTaskScheduler from ParallelExtensionsExtras with maxDegreeOfParallelism set to 2.

I then start 2 tasks that each call an async method (e.g. an async Http request), then gets the awaiter and the result of the completed task.

The problem seem to be that Task.Delay(2000) never completes. If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly. Does async/await somehow use the parent task's task scheduler, or how is it connected?

```<code>using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private void DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            HttpClientGetAsync().GetAwaiter().GetResult();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}
</code>```

Thanks in advance for any help

答:
await by default captures the current context and uses that to resume the async method. This context is SynchronizationContext.Current, unless it is null, in which case it is TaskScheduler.Current.

In this case, await is capturing the LimitedConcurrencyLevelTaskScheduler used to execute DoWork. So, after starting the Task.Delay both times, both of those threads are blocked (due to the GetAwaiter().GetResult()). When the Task.Delay completes, the await schedules the remainder of the HttpClientGetAsync method to its context. However, the context will not run it since it already has 2 threads.

So you end up with threads blocked in the context until their async methods complete, but the async methods cannot complete until there is a free thread in the context; thus a deadlock. Very similar to the standard "don't block on async code" style of deadlock, just with n threads instead of one.

Clarifications:

The problem seem to be that Task.Delay(2000) never completes.

Task.Delay is completing, but the await cannot continue executing the async method.

If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

There are plenty of threads available. But the LimitedConcurrencyTaskScheduler only allows 2 threads at a time to run in its context.

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly.

Yes; it's the await that is capturing the context. Task.Delay does not capture a context internally, so it can complete without needing to enter the LimitedConcurrencyTaskScheduler.

Solution:

Task schedulers in general do not work very well with asynchronous code. This is because task schedulers were designed for Parallel Tasks rather than asynchronous tasks. So they only apply when code is running (or blocked). In this case, LimitedConcurrencyLevelTaskScheduler only "counts" code that's running; if you have a method that's doing an await, it won't "count" against that concurrency limit.

So, your code has ended up in a situation where it has the sync-over-async antipattern, probably because someone was trying to avoid the problem of await not working as expected with limited concurrency task schedulers. This sync-over-async antipattern has then caused the deadlock problem.

Now, you could add in more hacks by using ConfigureAwait(false) everywhere and continue blocking on asynchronous code, or you could fix it better.

A more proper fix would be to do asynchronous throttling. Toss out the LimitedConcurrencyLevelTaskScheduler completely; concurrency-limiting task schedulers only work with synchronous code, and your code is asynchronous. You can do asynchronous throttling using SemaphoreSlim, as such:

```<code>class TaskSchedulerTest
{
  private readonly SemaphoreSlim _mutex = new SemaphoreSlim(2);

  public async Task RunAsync()
  {
    var tasks = Enumerable.Range(1, 2).Select(id => DoWorkAsync(id));
    await Task.WhenAll(tasks);
  }

  private async Task DoWorkAsync(int id)
  {
    await _mutex.WaitAsync();
    try
    {
      Console.WriteLine($"Starting Work {id}");
      await HttpClientGetAsync();
      Console.WriteLine($"Finished Work {id}");
    }
    finally
    {
      _mutex.Release();
    }
  }

  async Task HttpClientGetAsync()
  {
    await Task.Delay(2000);
  }
}
</code>```

Body:
I'm struggling to understand what's happening in this simple program.

In the example below I have a task factory that uses the  LimitedConcurrencyLevelTaskScheduler from ParallelExtensionsExtras with maxDegreeOfParallelism set to 2.

I then start 2 tasks that each call an async method (e.g. an async Http request), then gets the awaiter and the result of the completed task.

The problem seem to be that Task.Delay(2000) never completes. If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly. Does async/await somehow use the parent task's task scheduler, or how is it connected?

using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Schedulers;

namespace LimitedConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TaskSchedulerTest();
            test.Run();
        }
    }

    class TaskSchedulerTest
    {
        public void Run()
        {
            var scheduler = new LimitedConcurrencyLevelTaskScheduler(2);
            var taskFactory = new TaskFactory(scheduler);

            var tasks = Enumerable.Range(1, 2).Select(id => taskFactory.StartNew(() => DoWork(id)));
            Task.WaitAll(tasks.ToArray());
        }

        private void DoWork(int id)
        {
            Console.WriteLine($"Starting Work {id}");
            HttpClientGetAsync().GetAwaiter().GetResult();
            Console.WriteLine($"Finished Work {id}");
        }

        async Task HttpClientGetAsync()
        {
            await Task.Delay(2000);
        }
    }
}

Thanks in advance for any help

Body:
await by default captures the current context and uses that to resume the async method. This context is SynchronizationContext.Current, unless it is null, in which case it is TaskScheduler.Current.

In this case, await is capturing the LimitedConcurrencyLevelTaskScheduler used to execute DoWork. So, after starting the Task.Delay both times, both of those threads are blocked (due to the GetAwaiter().GetResult()). When the Task.Delay completes, the await schedules the remainder of the HttpClientGetAsync method to its context. However, the context will not run it since it already has 2 threads.

So you end up with threads blocked in the context until their async methods complete, but the async methods cannot complete until there is a free thread in the context; thus a deadlock. Very similar to the standard "don't block on async code" style of deadlock, just with n threads instead of one.

Clarifications:

The problem seem to be that Task.Delay(2000) never completes.

Task.Delay is completing, but the await cannot continue executing the async method.

If I set maxDegreeOfParallelism to 3 (or greater) it completes. But with maxDegreeOfParallelism = 2 (or less) my guess is that there is no thread available to complete the task. Why is that?

There are plenty of threads available. But the LimitedConcurrencyTaskScheduler only allows 2 threads at a time to run in its context.

It seems to be related to async/await since if I remove it and simply do Task.Delay(2000).GetAwaiter().GetResult() in DoWork it works perfectly.

Yes; it's the await that is capturing the context. Task.Delay does not capture a context internally, so it can complete without needing to enter the LimitedConcurrencyTaskScheduler.

Solution:

Task schedulers in general do not work very well with asynchronous code. This is because task schedulers were designed for Parallel Tasks rather than asynchronous tasks. So they only apply when code is running (or blocked). In this case, LimitedConcurrencyLevelTaskScheduler only "counts" code that's running; if you have a method that's doing an await, it won't "count" against that concurrency limit.

So, your code has ended up in a situation where it has the sync-over-async antipattern, probably because someone was trying to avoid the problem of await not working as expected with limited concurrency task schedulers. This sync-over-async antipattern has then caused the deadlock problem.

Now, you could add in more hacks by using ConfigureAwait(false) everywhere and continue blocking on asynchronous code, or you could fix it better.

A more proper fix would be to do asynchronous throttling. Toss out the LimitedConcurrencyLevelTaskScheduler completely; concurrency-limiting task schedulers only work with synchronous code, and your code is asynchronous. You can do asynchronous throttling using SemaphoreSlim, as such:

class TaskSchedulerTest
{
  private readonly SemaphoreSlim _mutex = new SemaphoreSlim(2);

  public async Task RunAsync()
  {
    var tasks = Enumerable.Range(1, 2).Select(id => DoWorkAsync(id));
    await Task.WhenAll(tasks);
  }

  private async Task DoWorkAsync(int id)
  {
    await _mutex.WaitAsync();
    try
    {
      Console.WriteLine($"Starting Work {id}");
      await HttpClientGetAsync();
      Console.WriteLine($"Finished Work {id}");
    }
    finally
    {
      _mutex.Release();
    }
  }

  async Task HttpClientGetAsync()
  {
    await Task.Delay(2000);
  }
}


问:
Make child container fixed relatively to parent div(with non-fixed height)
By default, when user opens my page he can see only "imagecontainer" div with images and "imagebutton" has status "selected".

When user clicks on "Videos" button, I make "Videos" button selected,
hide "imagecontainer" and show "videocontainer".

The problem is, that my “maincontainer” height is not fixed. When user switches from videos to images, back and force, and since images and videos are sometimes different in sizes, my “button-row” shifts also up and down. Making experience inconsistent.

I am not allowed to change "maincontainer" width , change it's properties or position or add something to this layout. I can only change "videocontainer" or “button-row”.

I tried to make my "button-row" with absolute position and give to it "bottom:0" to stick it to the bottom of parent container. However it didn't worked.

Is there any workarounds? Can I do it through jquery? Somehow capture initial height of maincontainer. And then, if user clicks Videos button, force maincontainer to have the same height that I captured on initial page load (when Image button is selected)

```<code><div id=“maincontainer”>
    <div>Some data</div>
    <div id = "imagecontainer"> My image is here</div>
    <div id = "videocontainer"> My video is here</div>
    <div id = “button-row”>
        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>
    </div>
</div>
</code>```

Css for main container:

```<code>#maincontainer{
    position: relative;
    width: 350px;
}
</code>```

答:
Would this work (untested)</p>

```<code>$(document).ready(function() {
    if($("#imagecontainer").height() > $("#videocontainer").height()) {
        $("#videocontainer").height($("#imagecontainer").height());
    } else {
        $("#imagecontainer").height($("#videocontainer").height());
    }
});
</code>```

Body:
By default, when user opens my page he can see only "imagecontainer" div with images and "imagebutton" has status "selected".

When user clicks on "Videos" button, I make "Videos" button selected,
hide "imagecontainer" and show "videocontainer".

The problem is, that my “maincontainer” height is not fixed. When user switches from videos to images, back and force, and since images and videos are sometimes different in sizes, my “button-row” shifts also up and down. Making experience inconsistent.

I am not allowed to change "maincontainer" width , change it's properties or position or add something to this layout. I can only change "videocontainer" or “button-row”.

I tried to make my "button-row" with absolute position and give to it "bottom:0" to stick it to the bottom of parent container. However it didn't worked.

Is there any workarounds? Can I do it through jquery? Somehow capture initial height of maincontainer. And then, if user clicks Videos button, force maincontainer to have the same height that I captured on initial page load (when Image button is selected)

Some data

 My image is here

 My video is here

        <button id=“imagebutton” class="selected" type="button">Image</button>
        <button id=“videobutton” type="button">Video</button>

Css for main container:

#maincontainer{
    position: relative;
    width: 350px;
}

Body:
Would this work (untested)

$(document).ready(function() {
    if($("#imagecontainer").height() > $("#videocontainer").height()) {
        $("#videocontainer").height($("#imagecontainer").height());
    } else {
        $("#imagecontainer").height($("#videocontainer").height());
    }
});


问:
Django Rest Framework: Use DELETE on GenericAPIView without implementing Retrieve
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

```<code>class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')
</code>```

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

```<code>from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)
</code>```

Results in:

```<code>Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.
</code>```

答:
My solution for part 1. is to include the mixin but restrict the http_method_names:

```<code>class ContentViewSet(RetrieveModelMixin, GenericViewSet):
    http_method_names = ['delete']
    ...
</code>```

However, I still don't know why I have to include RetrieveModelMixin at all.

Body:
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)

Results in:

Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

Body:
My solution for part 1. is to include the mixin but restrict the http_method_names:

class ContentViewSet(RetrieveModelMixin, GenericViewSet):
    http_method_names = ['delete']
    ...

However, I still don't know why I have to include RetrieveModelMixin at all.


问:
How do I add Headers Name in Modal LOV plug-ins
I'm setting up a Modal LOV plugin and I want to Give the Header name into plugin with my sql query

```<code>select com_id r,
         com_name d,
         com_name "COMPANY",
         com_add "ADDRESS",
         PHONE_NO "PHONE"
 from PH_COMPANY;
</code>```

I expected the output of this Modal LOV display data with the Headers. But the Output is wrong.

答: Have you checked this attribute?

Body:
I'm setting up a Modal LOV plugin and I want to Give the Header name into plugin with my sql query

select com_id r,
         com_name d,
         com_name "COMPANY",
         com_add "ADDRESS",
         PHONE_NO "PHONE"
 from PH_COMPANY;

I expected the output of this Modal LOV display data with the Headers. But the Output is wrong.

Body: Have you checked this attribute?