问:
Send parallel requests but only one per host with HttpClient and Polly to gracefully handle 429 responses
Intro:

I am building a single-node web crawler to simply validate URLs are 200 OK in a .NET Core console application. I have a collection of URLs at different hosts to which I am sending requests with HttpClient. I am fairly new to using Polly and TPL Dataflow.

Requirements:

I want to support sending multiple HTTP requests in parallel with a
configurable MaxDegreeOfParallelism.

I want to limit the number of parallel requests to any given host to 1 (or configurable). This is in order to gracefully handle per-host 429 TooManyRequests responses with a Polly policy. Alternatively, I could maybe use a Circuit Breaker to cancel concurrent requests to the same host on receipt of one 429 response and then proceed one-at-a-time to that specific host?

I am perfectly fine with not using TPL Dataflow at all in favor of maybe using a Polly Bulkhead or some other mechanism for throttled parallel requests, but I am not sure what that configuration would look like in order to implement requirement #2.

Current Implementation:

My current implementation works, except that I often see that I'll have x parallel requests to the same host return 429 at about the same time... Then, they all pause for the retry policy... Then, they all slam the same host again at the same time often still receiving 429s. Even if I distribute multiple instances of the same host evenly throughout the queue, my URL collection is overweighted with a few specific hosts that still start generating 429s eventually.

After receiving a 429, I think I only want to send one concurrent request to that host going forward to respect the remote host and pursue 200s.

Validator Method:

```<code>public async Task<int> GetValidCount(IEnumerable<Uri> urls, CancellationToken cancellationToken)
{
    var validator = new TransformBlock<Uri, bool>(
        async u => (await _httpClient.GetAsync(u, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).IsSuccessStatusCode,
        new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = MaxDegreeOfParallelism}
    );
    foreach (var url in urls)
        await validator.SendAsync(url, cancellationToken);
    validator.Complete();
    var validUrlCount = 0;
    while (await validator.OutputAvailableAsync(cancellationToken))
    {
        if(await validator.ReceiveAsync(cancellationToken))
            validUrlCount++;
    }
    await validator.Completion;
    return validUrlCount;
}
</code>```

The Polly policy applied to the HttpClient instance used in GetValidCount() above.

```<code>IAsyncPolicy<HttpResponseMessage> waitAndRetryTooManyRequests = Policy
    .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
    .WaitAndRetryAsync(3,
        (retryCount, response, context) =>
            response.Result?.Headers.RetryAfter.Delta ?? TimeSpan.FromMilliseconds(120),
        async (response, timespan, retryCount, context) =>
        {
            // log stuff
        });
</code>```

Question:

How can I modify or replace this solution to add satisfaction of requirement #2?

答:
Here is a method that creates a TransformBlock which prevents concurrent execution for messages with the same key. The key of each message is obtained by invoking the supplied keySelector function. Messages with the same key are processed sequentially to each other (not in parallel). The key is also passed as an argument to the transform function, because it can be useful in some cases.

```<code>public static TransformBlock<TInput, TOutput>
    CreateExclusivePerKeyTransformBlock<TInput, TKey, TOutput>(
    Func<TInput, TKey, Task<TOutput>> transform,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (transform == null) throw new ArgumentNullException(nameof(transform));
    if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
    if (dataflowBlockOptions == null)
        throw new ArgumentNullException(nameof(dataflowBlockOptions));
    keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;

    var internalCTS = CancellationTokenSource
        .CreateLinkedTokenSource(dataflowBlockOptions.CancellationToken);

    var maxDOP = dataflowBlockOptions.MaxDegreeOfParallelism;
    var taskScheduler = dataflowBlockOptions.TaskScheduler;

    var perKeySemaphores = new ConcurrentDictionary<TKey, SemaphoreSlim>(
        keyComparer);

    SemaphoreSlim maxDopSemaphore;
    if (maxDOP == DataflowBlockOptions.Unbounded)
    {
        maxDopSemaphore = new SemaphoreSlim(Int32.MaxValue);
    }
    else
    {
        maxDopSemaphore = new SemaphoreSlim(maxDOP, maxDOP);

        // The degree of parallelism is controlled by the semaphore
        dataflowBlockOptions.MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded;

        // Use a limited-concurrency scheduler for preserving the processing order
        dataflowBlockOptions.TaskScheduler = new ConcurrentExclusiveSchedulerPair(
            taskScheduler, maxDOP).ConcurrentScheduler;
    }

    var block = new TransformBlock<TInput, TOutput>(async item =>
    {
        var key = keySelector(item);
        var perKeySemaphore = perKeySemaphores
            .GetOrAdd(key, _ => new SemaphoreSlim(1, 1));

        // Continue on captured context before invoking the transform
        await perKeySemaphore.WaitAsync(internalCTS.Token);
        try
        {
            await maxDopSemaphore.WaitAsync(internalCTS.Token);
            try
            {
                return await transform(item, key).ConfigureAwait(false);
            }
            catch (Exception ex) when (!(ex is OperationCanceledException))
            {
                internalCTS.Cancel(); // The block has failed
                throw;
            }
            finally
            {
                maxDopSemaphore.Release();
            }
        }
        finally
        {
            perKeySemaphore.Release();
        }
    }, dataflowBlockOptions);

    dataflowBlockOptions.MaxDegreeOfParallelism = maxDOP; // Restore initial value
    dataflowBlockOptions.TaskScheduler = taskScheduler; // Restore initial value
    return block;
}
</code>```

Usage example:

```<code>var validator = CreateExclusivePerKeyTransformBlock<Uri, string, bool>(
    async (uri, host) =>
    {
        return (await _httpClient.GetAsync(uri, HttpCompletionOption
            .ResponseHeadersRead, token)).IsSuccessStatusCode;
    },
    new ExecutionDataflowBlockOptions
    {
        MaxDegreeOfParallelism = 30,
        CancellationToken = token,
    },
    keySelector: uri => uri.Host,
    keyComparer: StringComparer.OrdinalIgnoreCase);
</code>```

All execution options are supported (MaxDegreeOfParallelism, BoundedCapacity, CancellationToken, EnsureOrdered etc).

Below is an overload of the CreateExclusivePerKeyTransformBlock that accepts a synchronous delegate, and another method+overload that returns an ActionBlock instead of a TransformBlock, with the same behavior.

```<code>public static TransformBlock<TInput, TOutput>
    CreateExclusivePerKeyTransformBlock<TInput, TKey, TOutput>(
    Func<TInput, TKey, TOutput> transform,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (transform == null) throw new ArgumentNullException(nameof(transform));
    return CreateExclusivePerKeyTransformBlock(
        (item, key) => Task.FromResult(transform(item, key)),
        dataflowBlockOptions, keySelector, keyComparer);
}

// An ITargetBlock is similar to an ActionBlock
public static ITargetBlock<TInput>
    CreateExclusivePerKeyActionBlock<TInput, TKey>(
    Func<TInput, TKey, Task> action,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (action == null) throw new ArgumentNullException(nameof(action));
    var block = CreateExclusivePerKeyTransformBlock(async (item, key) =>
        { await action(item, key).ConfigureAwait(false); return (object)null; },
        dataflowBlockOptions, keySelector, keyComparer);
    block.LinkTo(DataflowBlock.NullTarget<object>());
    return block;
}

public static ITargetBlock<TInput>
    CreateExclusivePerKeyActionBlock<TInput, TKey>(
    Action<TInput, TKey> action,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (action == null) throw new ArgumentNullException(nameof(action));
    return CreateExclusivePerKeyActionBlock(
        (item, key) => { action(item, key); return Task.CompletedTask; },
        dataflowBlockOptions, keySelector, keyComparer);
}
</code>```

Caution: This class allocates one SemaphoreSlim per key, and keeps a reference to it until the class instance is finally garbage collected. This could be an issue in case the number of different keys is huge. There is an implementation of a less allocatey async lock here, that stores internally only the SemaphoreSlims that are currently in use (plus a small pool of released SemaphoreSlims that can be reused), which could replace the ConcurrentDictionary<TKey, SemaphoreSlim> used by this implementation.

Body:
Intro:

I am building a single-node web crawler to simply validate URLs are 200 OK in a .NET Core console application. I have a collection of URLs at different hosts to which I am sending requests with HttpClient. I am fairly new to using Polly and TPL Dataflow.

Requirements:

I want to support sending multiple HTTP requests in parallel with a
configurable MaxDegreeOfParallelism.

I want to limit the number of parallel requests to any given host to 1 (or configurable). This is in order to gracefully handle per-host 429 TooManyRequests responses with a Polly policy. Alternatively, I could maybe use a Circuit Breaker to cancel concurrent requests to the same host on receipt of one 429 response and then proceed one-at-a-time to that specific host?

I am perfectly fine with not using TPL Dataflow at all in favor of maybe using a Polly Bulkhead or some other mechanism for throttled parallel requests, but I am not sure what that configuration would look like in order to implement requirement #2.

Current Implementation:

My current implementation works, except that I often see that I'll have x parallel requests to the same host return 429 at about the same time... Then, they all pause for the retry policy... Then, they all slam the same host again at the same time often still receiving 429s. Even if I distribute multiple instances of the same host evenly throughout the queue, my URL collection is overweighted with a few specific hosts that still start generating 429s eventually.

After receiving a 429, I think I only want to send one concurrent request to that host going forward to respect the remote host and pursue 200s.

Validator Method:

public async Task<int> GetValidCount(IEnumerable<Uri> urls, CancellationToken cancellationToken)
{
    var validator = new TransformBlock<Uri, bool>(
        async u => (await _httpClient.GetAsync(u, HttpCompletionOption.ResponseHeadersRead, cancellationToken)).IsSuccessStatusCode,
        new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = MaxDegreeOfParallelism}
    );
    foreach (var url in urls)
        await validator.SendAsync(url, cancellationToken);
    validator.Complete();
    var validUrlCount = 0;
    while (await validator.OutputAvailableAsync(cancellationToken))
    {
        if(await validator.ReceiveAsync(cancellationToken))
            validUrlCount++;
    }
    await validator.Completion;
    return validUrlCount;
}

The Polly policy applied to the HttpClient instance used in GetValidCount() above.

IAsyncPolicy<HttpResponseMessage> waitAndRetryTooManyRequests = Policy
    .HandleResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.TooManyRequests)
    .WaitAndRetryAsync(3,
        (retryCount, response, context) =>
            response.Result?.Headers.RetryAfter.Delta ?? TimeSpan.FromMilliseconds(120),
        async (response, timespan, retryCount, context) =>
        {
            // log stuff
        });

Question:

How can I modify or replace this solution to add satisfaction of requirement #2?

Body:
Here is a method that creates a TransformBlock which prevents concurrent execution for messages with the same key. The key of each message is obtained by invoking the supplied keySelector function. Messages with the same key are processed sequentially to each other (not in parallel). The key is also passed as an argument to the transform function, because it can be useful in some cases.

public static TransformBlock<TInput, TOutput>
    CreateExclusivePerKeyTransformBlock<TInput, TKey, TOutput>(
    Func<TInput, TKey, Task<TOutput>> transform,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (transform == null) throw new ArgumentNullException(nameof(transform));
    if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
    if (dataflowBlockOptions == null)
        throw new ArgumentNullException(nameof(dataflowBlockOptions));
    keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;

    var internalCTS = CancellationTokenSource
        .CreateLinkedTokenSource(dataflowBlockOptions.CancellationToken);

    var maxDOP = dataflowBlockOptions.MaxDegreeOfParallelism;
    var taskScheduler = dataflowBlockOptions.TaskScheduler;

    var perKeySemaphores = new ConcurrentDictionary<TKey, SemaphoreSlim>(
        keyComparer);

    SemaphoreSlim maxDopSemaphore;
    if (maxDOP == DataflowBlockOptions.Unbounded)
    {
        maxDopSemaphore = new SemaphoreSlim(Int32.MaxValue);
    }
    else
    {
        maxDopSemaphore = new SemaphoreSlim(maxDOP, maxDOP);

        // The degree of parallelism is controlled by the semaphore
        dataflowBlockOptions.MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded;

        // Use a limited-concurrency scheduler for preserving the processing order
        dataflowBlockOptions.TaskScheduler = new ConcurrentExclusiveSchedulerPair(
            taskScheduler, maxDOP).ConcurrentScheduler;
    }

    var block = new TransformBlock<TInput, TOutput>(async item =>
    {
        var key = keySelector(item);
        var perKeySemaphore = perKeySemaphores
            .GetOrAdd(key, _ => new SemaphoreSlim(1, 1));

        // Continue on captured context before invoking the transform
        await perKeySemaphore.WaitAsync(internalCTS.Token);
        try
        {
            await maxDopSemaphore.WaitAsync(internalCTS.Token);
            try
            {
                return await transform(item, key).ConfigureAwait(false);
            }
            catch (Exception ex) when (!(ex is OperationCanceledException))
            {
                internalCTS.Cancel(); // The block has failed
                throw;
            }
            finally
            {
                maxDopSemaphore.Release();
            }
        }
        finally
        {
            perKeySemaphore.Release();
        }
    }, dataflowBlockOptions);

    dataflowBlockOptions.MaxDegreeOfParallelism = maxDOP; // Restore initial value
    dataflowBlockOptions.TaskScheduler = taskScheduler; // Restore initial value
    return block;
}

Usage example:

var validator = CreateExclusivePerKeyTransformBlock<Uri, string, bool>(
    async (uri, host) =>
    {
        return (await _httpClient.GetAsync(uri, HttpCompletionOption
            .ResponseHeadersRead, token)).IsSuccessStatusCode;
    },
    new ExecutionDataflowBlockOptions
    {
        MaxDegreeOfParallelism = 30,
        CancellationToken = token,
    },
    keySelector: uri => uri.Host,
    keyComparer: StringComparer.OrdinalIgnoreCase);

All execution options are supported (MaxDegreeOfParallelism, BoundedCapacity, CancellationToken, EnsureOrdered etc).

Below is an overload of the CreateExclusivePerKeyTransformBlock that accepts a synchronous delegate, and another method+overload that returns an ActionBlock instead of a TransformBlock, with the same behavior.

public static TransformBlock<TInput, TOutput>
    CreateExclusivePerKeyTransformBlock<TInput, TKey, TOutput>(
    Func<TInput, TKey, TOutput> transform,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (transform == null) throw new ArgumentNullException(nameof(transform));
    return CreateExclusivePerKeyTransformBlock(
        (item, key) => Task.FromResult(transform(item, key)),
        dataflowBlockOptions, keySelector, keyComparer);
}

// An ITargetBlock is similar to an ActionBlock
public static ITargetBlock<TInput>
    CreateExclusivePerKeyActionBlock<TInput, TKey>(
    Func<TInput, TKey, Task> action,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (action == null) throw new ArgumentNullException(nameof(action));
    var block = CreateExclusivePerKeyTransformBlock(async (item, key) =>
        { await action(item, key).ConfigureAwait(false); return (object)null; },
        dataflowBlockOptions, keySelector, keyComparer);
    block.LinkTo(DataflowBlock.NullTarget<object>());
    return block;
}

public static ITargetBlock<TInput>
    CreateExclusivePerKeyActionBlock<TInput, TKey>(
    Action<TInput, TKey> action,
    ExecutionDataflowBlockOptions dataflowBlockOptions,
    Func<TInput, TKey> keySelector,
    IEqualityComparer<TKey> keyComparer = null)
{
    if (action == null) throw new ArgumentNullException(nameof(action));
    return CreateExclusivePerKeyActionBlock(
        (item, key) => { action(item, key); return Task.CompletedTask; },
        dataflowBlockOptions, keySelector, keyComparer);
}

Caution: This class allocates one SemaphoreSlim per key, and keeps a reference to it until the class instance is finally garbage collected. This could be an issue in case the number of different keys is huge. There is an implementation of a less allocatey async lock here, that stores internally only the SemaphoreSlims that are currently in use (plus a small pool of released SemaphoreSlims that can be reused), which could replace the ConcurrentDictionary<TKey, SemaphoreSlim> used by this implementation.


来源: stackexchange

问:
How to write a $match on a $lookup document in MongoDB
I have two MongoDB collections that look like this:

```<code>Products      Specials
----------    ----------
_id           _id
name          product_id
country       zip
price         percent_discount
              out_of_stock
</code>```

I'm using GraphQL as well so I wrote up an aggregate pipeline that returns the data in this structure:

```<code>specials {
  _id
  product {
    _id
    name
    country
    price
  }
  zip
  percent_discount
  out_of_stock
}
</code>```

This aggregate pipeline I wrote works great and looks like this:

```<code>let response = await Specials.aggregate([
    {
        $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'product'
        }
    },
    {
        $unwind: '$product'
    },
    {
        $match: {
            zip: zip
        }
    }
])

return response;
</code>```

Now I'm trying to add a filter into this. The filter should match the name or country in the product collection preferably with regex. So I tried writing something like this but it's yielding over 8000 results when there should be only 2-3:

```<code>let response = await Specials.aggregate([
    {
        $match: { zip: zip }
    },
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    _id: "$$product_id"
                                },
                                {
                                    $or: [
                                        {
                                            name: filter
                                        },
                                        {
                                            country: filter
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    }
])
</code>```

答:
This is the following solution that I was able to get working:

```<code>let response = await Specials.aggregate([
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $and: [
                            {
                                $or: [
                                    {
                                        name: { $regex: filter }
                                    },
                                    {
                                        country: { $regex: filter }
                                    }
                                ]
                            },
                            {
                                $expr: {
                                    $eq: ["$$product_id", "$_id"]
                                }
                            }
                        ]
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    },
    {
        $match: {
            $and: [
                {
                    zip: zip
                }
            ]
        }
    }
])

return response;
</code>```

** Updated with the working $regex implementation

ContentLicense: CC BY-SA 4.0

Body:
I have two MongoDB collections that look like this:

Products      Specials
----------    ----------
_id           _id
name          product_id
country       zip
price         percent_discount
              out_of_stock

I'm using GraphQL as well so I wrote up an aggregate pipeline that returns the data in this structure:

specials {
  _id
  product {
    _id
    name
    country
    price
  }
  zip
  percent_discount
  out_of_stock
}

This aggregate pipeline I wrote works great and looks like this:

let response = await Specials.aggregate([
    {
        $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'product'
        }
    },
    {
        $unwind: '$product'
    },
    {
        $match: {
            zip: zip
        }
    }
])

return response;

Now I'm trying to add a filter into this. The filter should match the name or country in the product collection preferably with regex. So I tried writing something like this but it's yielding over 8000 results when there should be only 2-3:

let response = await Specials.aggregate([
    {
        $match: { zip: zip }
    },
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                {
                                    _id: "$$product_id"
                                },
                                {
                                    $or: [
                                        {
                                            name: filter
                                        },
                                        {
                                            country: filter
                                        }
                                    ]
                                }
                            ]
                        }
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    }
])

Body:
This is the following solution that I was able to get working:

let response = await Specials.aggregate([
    {
        $lookup: {
            from: "products",
            let: { product_id: "$product_id" },
            pipeline: [
                {
                    $match: {
                        $and: [
                            {
                                $or: [
                                    {
                                        name: { $regex: filter }
                                    },
                                    {
                                        country: { $regex: filter }
                                    }
                                ]
                            },
                            {
                                $expr: {
                                    $eq: ["$$product_id", "$_id"]
                                }
                            }
                        ]
                    }
                }
            ],
            as: "product"
        }
    },
    {
        $unwind: "$product"
    },
    {
        $match: {
            $and: [
                {
                    zip: zip
                }
            ]
        }
    }
])

return response;

** Updated with the working $regex implementation


问:
Fixing Indexing when Appending Dataframes
I am appending three CSVs:

```<code>
df = pd.read_csv("places_1.csv")
temp = pd.read_csv("places_2.csv")
df = df.append(temp)
temp = pd.read_csv("places_3.csv")
df = df.append(temp)
print(df.head(20))
</code>```

the joined table looks like:

```<code>  location  device_count  population
0        A            11         NaN
1        B            12         NaN
2        C            13         NaN
3        D            14         NaN
4        E            15         NaN
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN
</code>```

As you can see the indices are not unique.

When I call this iloc function to multiply the population column by 2:

```<code>df2 = df.copy
for index, row in df.iterrows():
    df.iloc[index, df.columns.get_loc('population')] = row['device_count'] * 2
</code>```

I get the following erronious result:

```<code>  location  device_count  population
0        A            11        62.0
1        B            12        64.0
2        C            13        66.0
3        D            14        68.0
4        E            15        70.0
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN
</code>```

For each CSV it is overwriting the indexes of the first CSV
I have also tried creating a new column of integers and calling df.set_index(). That did not work.

Any tips?

答:
As others have stated, you can use ignore_index, and you probably should use pd.concat here. Alternatively, for other situations where you are not combining DataFrames, you can also use df = df.reset_index(drop=True) to change the indices after the fact.

Additionally, you should avoid using iterrows() for reasons listed in the docs here. Using the following works way better:

```<code>df.loc[:, 'population'] = df.loc[:, 'device_count'].astype('int') * 2
</code>```

Body:
I am appending three CSVs:

df = pd.read_csv("places_1.csv")
temp = pd.read_csv("places_2.csv")
df = df.append(temp)
temp = pd.read_csv("places_3.csv")
df = df.append(temp)
print(df.head(20))

the joined table looks like:

  location  device_count  population
0        A            11         NaN
1        B            12         NaN
2        C            13         NaN
3        D            14         NaN
4        E            15         NaN
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN

As you can see the indices are not unique.

When I call this iloc function to multiply the population column by 2:

df2 = df.copy
for index, row in df.iterrows():
    df.iloc[index, df.columns.get_loc('population')] = row['device_count'] * 2

I get the following erronious result:

  location  device_count  population
0        A            11        62.0
1        B            12        64.0
2        C            13        66.0
3        D            14        68.0
4        E            15        70.0
0        F            21         NaN
1        G            22         NaN
2        H            23         NaN
3        I            24         NaN
4        J            25         NaN
0        K            31         NaN
1        L            32         NaN
2        M            33         NaN
3        N            34         NaN
4        O            35         NaN

For each CSV it is overwriting the indexes of the first CSV
I have also tried creating a new column of integers and calling df.set_index(). That did not work.

Any tips?

Body:
As others have stated, you can use ignore_index, and you probably should use pd.concat here. Alternatively, for other situations where you are not combining DataFrames, you can also use df = df.reset_index(drop=True) to change the indices after the fact.

Additionally, you should avoid using iterrows() for reasons listed in the docs here. Using the following works way better:

df.loc[:, 'population'] = df.loc[:, 'device_count'].astype('int') * 2


问:
How do I check if a users input is a valid IP address or not?
I want to check if an entered input is a valid IP address or not. I would like a specific function that will help me validate a users input.</p>

答:
```<code>filter_var($ip, FILTER_VALIDATE_IP)
</code>```

http://www.php.net/filter_var

Example:-

```<code>if(filter_var($ip, FILTER_VALIDATE_IP)){
  echo 'Valid IP';
} else {
  echo 'Not Valid IP';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
filter_var($ip, FILTER_VALIDATE_IP)

http://www.php.net/filter_var

Example:-

if(filter_var($ip, FILTER_VALIDATE_IP)){
  echo 'Valid IP';
} else {
  echo 'Not Valid IP';
}


问:
Server Discovery And Monitoring engine is deprecated
I am using Mongoose with my Node.js app and this is my configuration:

```<code>mongoose.connect(process.env.MONGO_URI, {
   useNewUrlParser: true,
   useUnifiedTopology: true,
   useCreateIndex: true,
   useFindAndModify: false
}).then(()=>{
    console.log(`connection to database established`)
}).catch(err=>{
    console.log(`db error ${err.message}`);
    process.exit(-1)
})
</code>```

but in the console it still gives me the warning:

DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

What is the problem? I was not using useUnifiedTopology before but now it shows up in the console. I added it to the config but it still gives me this warning, why? I do not even use MongoClient.

Edit

As Felipe Plets answered there was a problem in Mongoose and they fixed this bug in later versions. So you can solve problem by updating mongoose version.

答:
```<code>const mongoose = require("mongoose");

mongoose.connect('mongodb://localhost:27017/Edureka',{ useNewUrlParser: true, useUnifiedTopology: true }, (error)=> {
    const connectionStatus = !error ? 'Success': 'Error Connecting to database';
    console.log(connectionStatus);
});
</code>```

Body:
I am using Mongoose with my Node.js app and this is my configuration:

mongoose.connect(process.env.MONGO_URI, {
   useNewUrlParser: true,
   useUnifiedTopology: true,
   useCreateIndex: true,
   useFindAndModify: false
}).then(()=>{
    console.log(`connection to database established`)
}).catch(err=>{
    console.log(`db error ${err.message}`);
    process.exit(-1)
})

but in the console it still gives me the warning:

DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

What is the problem? I was not using useUnifiedTopology before but now it shows up in the console. I added it to the config but it still gives me this warning, why? I do not even use MongoClient.

Edit

As Felipe Plets answered there was a problem in Mongoose and they fixed this bug in later versions. So you can solve problem by updating mongoose version.


问:
dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
Using electron-builder to build Windows app, When signing up, I got this error :</p>

```<code>dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
  Referenced from: /Users/puss/Library/Caches/electron-builder/winCodeSign/winCodeSign-1.7.0/darwin/osslsigncode
  Reason: image not found
</code>```

答:
Here's what worked for me</p>

```<code>brew update && brew upgrade
brew uninstall --ignore-dependencies openssl
brew install openssl
</code>```

Body:
Using electron-builder to build Windows app, When signing up, I got this error :

dyld: Library not loaded: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib
  Referenced from: /Users/puss/Library/Caches/electron-builder/winCodeSign/winCodeSign-1.7.0/darwin/osslsigncode
  Reason: image not found

Body:
Here's what worked for me

brew update && brew upgrade
brew uninstall --ignore-dependencies openssl
brew install openssl


问:
Is it possible to judge npm script in a JavaScript file in vue.js?
I have a config file in my vue.js + webpack + npm project

/plugins/http/GLOBAL_CONST.js

```<code>const GLOBAL_CONST = {}

GLOBAL_CONST.BASE_URL = "http://www.example.com/"  // "http://localhost:3000/"

GLOBAL_CONST.BASE_API = "http://www.example:8000/"  //  "http://localhost:8000/"

export default GLOBAL_CONST

</code>```

I have a requirement, if I run npm run dev, the

```<code>GLOBAL_CONST.BASE_URL = "http://localhost:3000/"
GLOBAL_CONST.BASE_API = "http://localhost:8000/"
</code>```

if I run npm run build it use:

```<code>GLOBAL_CONST.BASE_URL = "http://www.example.com/"
GLOBAL_CONST.BASE_API = "http://www.example:8000/"
</code>```

is it possible to make it come true?

答:
This is commonly done with if (process.env.NODE_ENV === 'production') (equals true for npm run build), so you could use that condition when setting BASE_URL:

GLOBAL_CONST.BASE_URL = (process.env.NODE_ENV === 'production')
                      ? "http://www.example.com/"
                      : "http://localhost:3000/"
```

<p>If using Vue CLI, the <code>NODE_ENV</code> environment variable is automatically set for you during the build. Otherwise, you could set it yourself in your build script:</p>

<pre class="lang-js prettyprint-override"><code>// package.json
{
  "scripts": {
    "build": "NODE_ENV=production node build.js",
    "dev": "NODE_ENV=development webpack-dev-server [...]"
  }
}
</code>```

Body:
I have a config file in my vue.js + webpack + npm project

/plugins/http/GLOBAL_CONST.js

const GLOBAL_CONST = {}

GLOBAL_CONST.BASE_URL = "http://www.example.com/"  // "http://localhost:3000/"

GLOBAL_CONST.BASE_API = "http://www.example:8000/"  //  "http://localhost:8000/"

export default GLOBAL_CONST

I have a requirement, if I run npm run dev, the

GLOBAL_CONST.BASE_URL = "http://localhost:3000/"
GLOBAL_CONST.BASE_API = "http://localhost:8000/"

if I run npm run build it use:

GLOBAL_CONST.BASE_URL = "http://www.example.com/"
GLOBAL_CONST.BASE_API = "http://www.example:8000/"

is it possible to make it come true?

Body:
This is commonly done with if (process.env.NODE_ENV === 'production') (equals true for npm run build), so you could use that condition when setting BASE_URL:

GLOBAL_CONST.BASE_URL = (process.env.NODE_ENV === 'production')
                      ? "http://www.example.com/"
                      : "http://localhost:3000/"

If using Vue CLI, the NODE_ENV environment variable is automatically set for you during the build. Otherwise, you could set it yourself in your build script:

// package.json
{
  "scripts": {
    "build": "NODE_ENV=production node build.js",
    "dev": "NODE_ENV=development webpack-dev-server [...]"
  }
}


问:
Can anyone break this code down for me please?
Write a function that takes in a list of integers and returns True if it contains 007 in order

```<code>spy_game([1,2,4,0,0,7,5]) --> True

spy_game([1,0,2,4,0,5,7]) --> True

spy_game([1,7,2,0,4,5,0]) --> False
</code>```

```<code>def spy_game(nums):
            code = [0, 0, 7, 'x']

            for num in nums:
                if num == code[0]:
                code.pop(0)      #code.remove(num) also works

        return len(code)==1
        print(spy_game([1,2,4,0,1,0,7]))
</code>```

Can anyone break this code down, especially this line:

return len(code)==1                      what does mean in this code ?

答:
```<code>def spy_game(nums):
        code = [0, 0, 7, 'x']
</code>```

Defining a function, which takes in a list, for function purposes, it is called nums.
Then it defines a list code which has 007 in the order and a character which is sure to not appear in any of the sample list. For each number in the list

```<code>for num in nums:
            if num == code[0]:
            code.pop(0)
</code>```

For each number in the list, if the number is same as the code's first number, it will pop it out.
if your nums is [1,0,6,0,7],

num = 1, num != code[0] which is 0. "next index"

num = 0, num == code[0] which is 0. "code[0] popped" "code is now [0,7,'x']

num = 6, num != code[0] which is 0. "next index"

num = 0, num == code[0] which is 0. "code[0] popped" "code is now [7,'x']

num = 7, num == code[0] which is 7. "code[0] popped" "code is now ['x']

As you can see, nums has been fully iterated and code length is only 1. Hence function returns true.

Body:
Write a function that takes in a list of integers and returns True if it contains 007 in order

spy_game([1,2,4,0,0,7,5]) --> True

spy_game([1,0,2,4,0,5,7]) --> True

spy_game([1,7,2,0,4,5,0]) --> False

def spy_game(nums):
            code = [0, 0, 7, 'x']

            for num in nums:
                if num == code[0]:
                code.pop(0)      #code.remove(num) also works

        return len(code)==1
        print(spy_game([1,2,4,0,1,0,7]))

Can anyone break this code down, especially this line:

return len(code)==1                      what does mean in this code ?

Body:
def spy_game(nums):
        code = [0, 0, 7, 'x']

Defining a function, which takes in a list, for function purposes, it is called nums.
Then it defines a list code which has 007 in the order and a character which is sure to not appear in any of the sample list. For each number in the list

for num in nums:
            if num == code[0]:
            code.pop(0)

For each number in the list, if the number is same as the code's first number, it will pop it out.
if your nums is [1,0,6,0,7],

num = 1, num != code[0] which is 0. "next index"

num = 0, num == code[0] which is 0. "code[0] popped" "code is now [0,7,'x']

num = 6, num != code[0] which is 0. "next index"

num = 0, num == code[0] which is 0. "code[0] popped" "code is now [7,'x']

num = 7, num == code[0] which is 7. "code[0] popped" "code is now ['x']

As you can see, nums has been fully iterated and code length is only 1. Hence function returns true.


问:
Problem with php and mysql connection xamp
So I am a user of windows 10 and have xammp in my computer. When I first try to run MySQL server, had problem with 3306 port because I didn't had configured ports free. So I changed it to run on port 3307 and it worked.
After that I am trying to connect to localhost/phpmyadmin, and for a reason I just can't....
Anybody have any advice/idea what is going on ?

答:
On the xampp config file :  xampp\phpMyAdmin\config.inc:
ADD THIS LINE

$cfg['Servers'][$i]['port'] = '3307';]

(I just found the answer, so... I thought would be good to leave this here.. )


问:
Writing input of a user into a file within an if-statement. (python)
I am trying to take the input from the user and put it into a file
within an if-statement. When I run the code, it runs smoothly, but it does not write the input into the names.txt file. Here's the code

if click.confirm('Are you a new user?', default=True):
    user_name = input("Welcome. What's your name? ")
    names_file = open("names.txt", "a")
    names_file.write(user_name)
else:
    print("Welcome back")
```

答:
Try this script simple build on pythin 3.x</p>

```<code>if True:
    f = open('test.text', 'w')
    f.write('Hello World from python file write')
    f.close()
</code>```

Body:
Try this script simple build on pythin 3.x

if True:
    f = open('test.text', 'w')
    f.write('Hello World from python file write')
    f.close()


问:
How to catch Exception like in a FrontController in Spring
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.</p>

```<code>@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}
</code>```

答:
To catch the exceptions in one central place you can use a common class annotated with ControllerAdvice. Below is a snippet for reference,

```<code>@ControllerAdvice
public class CustomizedExceptionHandler extends ResponseEntityExceptionHandler {

   @ExceptionHandler(DataAccessException .class)
   public final ResponseEntity<ErrorDetails> externalIdmException(DataAccessException ex,
        WebRequest request) {
    // exception handling
   }
}
</code>```

This Class will catch exceptions of type to which it is defined in a central place. If you want more specific exceptions to be handled at the class level, @ExceptionHandler method can be preferred.

Body:
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.

@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}

Body:
To catch the exceptions in one central place you can use a common class annotated with ControllerAdvice. Below is a snippet for reference,

@ControllerAdvice
public class CustomizedExceptionHandler extends ResponseEntityExceptionHandler {

   @ExceptionHandler(DataAccessException .class)
   public final ResponseEntity<ErrorDetails> externalIdmException(DataAccessException ex,
        WebRequest request) {
    // exception handling
   }
}

This Class will catch exceptions of type to which it is defined in a central place. If you want more specific exceptions to be handled at the class level, @ExceptionHandler method can be preferred.


问:
Stata and global variables
I am working with Stata.
I have a variable called graduate_secondary.
I generate a global variable called outcome, because eventually I will use another outcome.
Now I want to replace  the variable graduate if a condition relative to global is met, but I get an error:

My code is:

```<code>global outcome "graduate_secondary"

gen graduate=.

replace graduate=1 if graduate_primary==1 & `outcome'==1
</code>```

But i receive the symbol ==1 invalid name.
Does anyone know why?

答:
Another solution is to replace global outcome "graduate_secondary" with local outcome "graduate_secondary".

Stata has two types of macros: global, which are accessed with a $, and local, which are accessed with single quotes `' around the name -- as you did in your original code.

You get an error message because a local by the name of outcome has no value assigned to it in your workspace. By design, this will not itself produce an error but instead will the reference to the macro will evaluate as a blank value. You can see the result of evaluating macro references when you type them by using display as follows. You can also see all of the macros in your workspace with macro dir (the locals start with an underscore):

```<code>display `outcome'
display $outcome
</code>```

Here is a blog post about using macros in Stata. In general, I only use global macros when I have to pass something between multiple routines, but this seems like a good use case for locals.

Title: Stata and global variables

Body:
I am working with Stata.
I have a variable called graduate_secondary.
I generate a global variable called outcome, because eventually I will use another outcome.
Now I want to replace  the variable graduate if a condition relative to global is met, but I get an error:

My code is:

global outcome "graduate_secondary"

gen graduate=.

replace graduate=1 if graduate_primary==1 & `outcome'==1

But i receive the symbol ==1 invalid name.
Does anyone know why?

Body:
Another solution is to replace global outcome "graduate_secondary" with local outcome "graduate_secondary".

Stata has two types of macros: global, which are accessed with a $, and local, which are accessed with single quotes `' around the name -- as you did in your original code.

You get an error message because a local by the name of outcome has no value assigned to it in your workspace. By design, this will not itself produce an error but instead will the reference to the macro will evaluate as a blank value. You can see the result of evaluating macro references when you type them by using display as follows. You can also see all of the macros in your workspace with macro dir (the locals start with an underscore):

display `outcome'
display $outcome

Here is a blog post about using macros in Stata. In general, I only use global macros when I have to pass something between multiple routines, but this seems like a good use case for locals.


问:
How do I iterate through a file containing a list of floating point numbers in Python?
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.

numbers.txt -

5.0

15.0

25.0

This is my python code -

```<code>in_file = open("numbers.txt", "r")
number = float(in_file.read())  # error in python
user_input = float(input("Threshold: "))
if number > user_input:
    print(number)
in_file.close()

</code>```

Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. I tried to change line 2 in my code to add a strip method but it still comes up with the same error.

答:
```<code>for line in open("numbers.txt", "r"):
    line = line.replace("\n","")
    num = float(line)
</code>```

im sure you can continue from here..

Body:
I need to write a program that reads a file containing a list of floating-point numbers and counts how many of those numbers are larger than a user-specified threshold.

numbers.txt -

5.0

15.0

25.0

This is my python code -

in_file = open("numbers.txt", "r")
number = float(in_file.read())  # error in python
user_input = float(input("Threshold: "))
if number > user_input:
    print(number)
in_file.close()

Python is unable to convert the string to a float because the numbers have a new line after each number and python is trying to convert that into a float. I tried to change line 2 in my code to add a strip method but it still comes up with the same error.

Body:
for line in open("numbers.txt", "r"):
    line = line.replace("\n","")
    num = float(line)

im sure you can continue from here..


问:
LINQ Query to join 2 different tables
I am currently working on library management project, which users update their reading status when they borrow a book. When I use linq to join tables, everything else except status is there.
Here are my models:
User model(TblUser):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}
```

<p>Book Model(TblBook):</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace LibMan.Models.DB
{
    public partial class TblBook
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string Translator { get; set; }
        public string Publisher { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public byte[] Cover { get; set; }
    }
}

</code>```

Book Status Model(TblBookStatus):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

```

<p>And moving on to my code below, you can see I created DisplayBook with linq query join, but I can't display status in html side. It says it </p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LibMan.Models.DB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

namespace LibMan.Pages
{
    public class LibraryModel : PageModel
    {
        private readonly LibMan.Models.DB.LibManContext _context;
        public string Message { get; set; }
        public LibraryModel(LibMan.Models.DB.LibManContext context)
        {
            _context = context;
            DisplayBook = new List<TblBook>();
;       }
        public IList<TblBookStatus> TblBookStatus { get; set; }
        public IList<TblBook> TblBook { get; set; }
        public IList<TblBook> DisplayBook { get; set; }
        public IList<TblUser> TblUser{ get; set; }
        [BindProperty]
        public async Task OnGetAsync()
        {
            TblBookStatus = await _context.TblBookStatus.ToListAsync();
            TblBook = await _context.TblBook.ToListAsync();
            TblUser = await _context.TblUser.ToListAsync();
            var UserEmail = HttpContext.Session.GetString("Email");

            if (TblBookStatus != null && TblBook != null)
            {
                DisplayBook = (from book in TblBook
                                join stat in TblBookStatus
                                on book.BookId equals stat.BookId
                                join usr in TblUser
                                on stat.UserEmail equals usr.Email
                                where (usr.Email == UserEmail)
                                select book).ToList();
            }
        }
    }
}
</code>```

How can I do this? Can I do this inside the statement that DisplayBook is assigned to the Linq query result? What is the best way to do this? Thanks!
Note: I can provide html code if needed.

答:
No need to query each table separately, and then join.  Let LINQ do it for you.

```<code>var UserEmail = HttpContext.Session.GetString("Email");

var books = _context.TblBookStatus
     .Where(
        tbs => (tbs.Book != null && tbs.BookId == tbs.Book.BookId) &&
               (tbs.User != null && tbs.UserEmail == tbs.User.Email) &&
               tbs.UserEmail == UserEmail)
     .Select(tbs => tbs.Book);
</code>```

Because you have navigation properties defined in the EF models (using virtual properties), the joins will automatically be done for you.  In the above example, I am setting tbs.BookId == tbs.Book.BookId.  This does not need to be done if you have foreign key defined in entity type configurations.  You can alternatively define these relationships using attributes in your EF models.

Example:

```<code>[ForeignKey("BookId")]
public virtual TblBook Book { get; set; }
</code>```

EDIT: Break down what you need to return:

```<code>var books = _context.TblBookStatus
         .Where(
            tbs => (tbs.Book != null && tbs.BookId == tbs.Book.BookId) &&
                   (tbs.User != null && tbs.UserEmail == tbs.User.Email) &&
                   tbs.UserEmail == UserEmail)
         .Select(tbs => new {
                   Status = tbs.Status,
                   BookName = tbs.Book.Name
                             });
</code>```

Title: LINQ Query to join 2 different tables

Body:
I am currently working on library management project, which users update their reading status when they borrow a book. When I use linq to join tables, everything else except status is there.
Here are my models:
User model(TblUser):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

Book Model(TblBook):

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace LibMan.Models.DB
{
    public partial class TblBook
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Author { get; set; }
        public string Translator { get; set; }
        public string Publisher { get; set; }
        public string Description { get; set; }
        public string Category { get; set; }
        public byte[] Cover { get; set; }
    }
}

Book Status Model(TblBookStatus):

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;

namespace LibMan.Models.DB
{
    public partial class TblBookStatus
    {
        public int ResId { get; set; }
        public string UserEmail { get; set; }
        public int? BookId { get; set; }
        public string Status { get; set; }

        public virtual TblBook Book { get; set; }
        public virtual TblUser User { get; set; }
    }

}

And moving on to my code below, you can see I created DisplayBook with linq query join, but I can't display status in html side. It says it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LibMan.Models.DB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;

namespace LibMan.Pages
{
    public class LibraryModel : PageModel
    {
        private readonly LibMan.Models.DB.LibManContext _context;
        public string Message { get; set; }
        public LibraryModel(LibMan.Models.DB.LibManContext context)
        {
            _context = context;
            DisplayBook = new List<TblBook>();
;       }
        public IList<TblBookStatus> TblBookStatus { get; set; }
        public IList<TblBook> TblBook { get; set; }
        public IList<TblBook> DisplayBook { get; set; }
        public IList<TblUser> TblUser{ get; set; }
        [BindProperty]
        public async Task OnGetAsync()
        {
            TblBookStatus = await _context.TblBookStatus.ToListAsync();
            TblBook = await _context.TblBook.ToListAsync();
            TblUser = await _context.TblUser.ToListAsync();
            var UserEmail = HttpContext.Session.GetString("Email");

            if (TblBookStatus != null && TblBook != null)
            {
                DisplayBook = (from book in TblBook
                                join stat in TblBookStatus
                                on book.BookId equals stat.BookId
                                join usr in TblUser
                                on stat.UserEmail equals usr.Email
                                where (usr.Email == UserEmail)
                                select book).ToList();
            }
        }
    }
}

How can I do this? Can I do this inside the statement that DisplayBook is assigned to the Linq query result? What is the best way to do this? Thanks!
Note: I can provide html code if needed.

Body:
No need to query each table separately, and then join.  Let LINQ do it for you.

var UserEmail = HttpContext.Session.GetString("Email");

var books = _context.TblBookStatus
     .Where(
        tbs => (tbs.Book != null && tbs.BookId == tbs.Book.BookId) &&
               (tbs.User != null && tbs.UserEmail == tbs.User.Email) &&
               tbs.UserEmail == UserEmail)
     .Select(tbs => tbs.Book);

Because you have navigation properties defined in the EF models (using virtual properties), the joins will automatically be done for you.  In the above example, I am setting tbs.BookId == tbs.Book.BookId.  This does not need to be done if you have foreign key defined in entity type configurations.  You can alternatively define these relationships using attributes in your EF models.

Example:

[ForeignKey("BookId")]
public virtual TblBook Book { get; set; }

EDIT: Break down what you need to return:

var books = _context.TblBookStatus
         .Where(
            tbs => (tbs.Book != null && tbs.BookId == tbs.Book.BookId) &&
                   (tbs.User != null && tbs.UserEmail == tbs.User.Email) &&
                   tbs.UserEmail == UserEmail)
         .Select(tbs => new {
                   Status = tbs.Status,
                   BookName = tbs.Book.Name
                             });


问:
Density Heatmap - odd scale and display issues, I think?
I am attempting to do some mapping of arrest-related data in Los Angeles (using this dataset: https://data.lacity.org/A-Safe-City/Arrest-Data-from-2010-to-Present/yru6-6re4).

When I run the code as shown below, I get the following error:

```<code>Warning message: Removed 11,578 rows containing non-finite values (stat_density2d).
</code>```

So, that means out of 11,808 data points, only 230 are showing on the map. This seems reasonable, considering I'm zooming in on the two or three-block radius around the LA Coliseum only. This means, in 2017, there were 230 arrests in this area. OK.

But, when I map it, I get a density scale running from 500 all the way up to 2,500 (as seen below).

Here is a tibble of the location2017.df:

```<code>> as_tibble(location2017.df)
# A tibble: 11,808 x 3
     lon   lat Frequency
   <dbl> <dbl>     <int>
 1 -118.  33.7         5
 2 -118.  33.7         2
 3 -118.  33.7         1
 4 -118.  33.7         1
 5 -118.  33.7         4
 6 -118.  33.7         2
 7 -118.  33.7         2
 8 -118.  33.7         1
 9 -118.  33.7         1
10 -118.  33.7         4
# … with 11,798 more rows
</code>```

Here is the code I'm using to set everything up.

```<code>
</code>```

And here is the plot output:

As you can see, it is quite "washed out" ... it just seems odd to me that there is a purple hue over the whole map based on an assumed 238 total arrests. As well, the density chart is strange ... why is it going from 500 to 2,500 when there is a limited number of arrests?

So, in the end, two questions:

1. Does it seem correct that there be a purple hue over the entire map?

2. Why is the density scale on the side of the map figuring the way it is with only 238 arrests plotted?

Any thoughts/suggestions/corrections on how to make this plot look/read better is greatly appreciated.

EDIT

Decided to quickly output a geom_point of the same information as above. Here is the plot:

As you can see, the "purple hue" from the first image makes sense. There is limited number of arrests throughout the area, with a large mass where the yellow part of the heatmap is.

So, is there a way to make a stronger contrast between less arrest and more arrest in order to limit the hue that is currently covering the map?

答:
Your second question can aid in answering your first:

ggplot2 calculates the scale range before it chooses which elements from the dataset it should plot, so it sees you have a range of values from 500 to 2500 - why is it? because of your data. Note that your long lat coordinate values are very wide ( i.e 33.7) while you zoom on very specific areas. Coordinates can have varied degrees of accuracy, so for example if you had some arrests at 33.72515 and more arrests at 33.71235, you would have numbers which more accurately describe the actual number of crimes inside your zoom perimeter.

This also explains why you have the purple tint over the entire plot- your data suggests that over 500 crimes were committed in those areas, even though it might be more specific streets/alleys in reality.

What can you do?

IF you preprocessed the coordinates to cut some of the numbers after the decimal point- you should try to use the original coordinate data.

Look at your dataset and find if there is a description of the place where the crime was commited ( usually in gov databases they have large input data for each entry) then you could try and find the exact coordinates of the street which is indicated for each crime, and get more exact coordinates that way - it will take some work and will depend on whether you have the street name for every row in the dataset.

plot a more zoomed out view of the map.

Here is an example for a project I worked on in the past, where I created a plot of parking citations in Washington DC. As you can see, my degree of accuracy from the dataset was quite high (4 after the decimal point) compared to your set, and you see how this reflects in the density plot:

Body:
I am attempting to do some mapping of arrest-related data in Los Angeles (using this dataset: https://data.lacity.org/A-Safe-City/Arrest-Data-from-2010-to-Present/yru6-6re4).

When I run the code as shown below, I get the following error:

Warning message: Removed 11,578 rows containing non-finite values (stat_density2d).

So, that means out of 11,808 data points, only 230 are showing on the map. This seems reasonable, considering I'm zooming in on the two or three-block radius around the LA Coliseum only. This means, in 2017, there were 230 arrests in this area. OK.

But, when I map it, I get a density scale running from 500 all the way up to 2,500 (as seen below).

Here is a tibble of the location2017.df:

> as_tibble(location2017.df)
# A tibble: 11,808 x 3
     lon   lat Frequency
   <dbl> <dbl>     <int>
 1 -118.  33.7         5
 2 -118.  33.7         2
 3 -118.  33.7         1
 4 -118.  33.7         1
 5 -118.  33.7         4
 6 -118.  33.7         2
 7 -118.  33.7         2
 8 -118.  33.7         1
 9 -118.  33.7         1
10 -118.  33.7         4
# … with 11,798 more rows

Here is the code I'm using to set everything up.

And here is the plot output:

As you can see, it is quite "washed out" ... it just seems odd to me that there is a purple hue over the whole map based on an assumed 238 total arrests. As well, the density chart is strange ... why is it going from 500 to 2,500 when there is a limited number of arrests?

So, in the end, two questions:

1. Does it seem correct that there be a purple hue over the entire map?

2. Why is the density scale on the side of the map figuring the way it is with only 238 arrests plotted?

Any thoughts/suggestions/corrections on how to make this plot look/read better is greatly appreciated.

EDIT

Decided to quickly output a geom_point of the same information as above. Here is the plot:

As you can see, the "purple hue" from the first image makes sense. There is limited number of arrests throughout the area, with a large mass where the yellow part of the heatmap is.

So, is there a way to make a stronger contrast between less arrest and more arrest in order to limit the hue that is currently covering the map?


问:
How to count rows in a database
How do I count the rows in a database using PHP?

For example I have database called DB and a table inside called members. Inside the members table I want to count all rows to make a site statistics total number of members.

I use

```<code>$Profile = $core_db->Execute("Select ID, Name, Age, Nationality, Age from Profiles where Name='NAME'");
</code>```

So I'm trying to count the number of names here.

答:
$core_db->Execute("SELECT COUNT(ID) FROM Profiles WHERE Name='NAME'").

Welcome to stack overflow, just a gentle reminder. You can always try to google first before posting your question here.

Title: How to count rows in a database

Body:
How do I count the rows in a database using PHP?

For example I have database called DB and a table inside called members. Inside the members table I want to count all rows to make a site statistics total number of members.

I use

$Profile = $core_db->Execute("Select ID, Name, Age, Nationality, Age from Profiles where Name='NAME'");

So I'm trying to count the number of names here.


问:
How to set current page "active" in php
Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on.
Here is my code: please help me

menu.php:

```<code><li class=" has-sub">
    <a class="" href="javascript:;"><i class=" icon-time"></i> Zeiten<span class="arrow"></span></a>
    <ul class="sub">
       <li><a class="" href="offnungszeiten.php">Öffnungszeiten</a></li>
       <li><a class="" href="sauna.php">Sauna</a></li>
       <li><a class="" href="frauensauna.php">Frauensauna</a></li>
       <li class=""><a class="" href="custom.php">Beauty Lounge</a></li>
       <li><a class="" href="feiertage.php">Feiertage</a></li>
    </ul>
</li>
</code>```

答:
Assume you have a navbar with the following items:

```<code><ul>
   <li id="menu-item-home"><a href="index.php">HOME</a></li>
   <li id="menu-item-services"><a href="/services.php">SERVICES</a></li>
   <li id="menu-item-about-us"><a href="/about-us.php">ABOUT US</a></li>
   <li id="menu-item-contact"><a href="/contact.php">CONTACT</a></li>
</ul>
</code>```

Then, declare a javascript variable in each page as below:

```<code><script>
    <?php echo("var active = 'menu-item-home';"); ?>
</script>
</code>```

The variable "active" is assigned with the corresponding item of each page.

Now, you can use this variable to highlight the active menu item as below.

```<code>$(window).ready(function(){$("#" + active).addClass("active");});
</code>```

Title: How to set current page "active" in php

Body:
Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on.
Here is my code: please help me

menu.php:

     Zeiten

Öffnungszeiten

Sauna

Frauensauna

Beauty Lounge

Feiertage

Body:
Assume you have a navbar with the following items:

<ul>
   <li id="menu-item-home"><a href="index.php">HOME</a></li>
   <li id="menu-item-services"><a href="/services.php">SERVICES</a></li>
   <li id="menu-item-about-us"><a href="/about-us.php">ABOUT US</a></li>
   <li id="menu-item-contact"><a href="/contact.php">CONTACT</a></li>
</ul>

Then, declare a javascript variable in each page as below:

<script>
    <?php echo("var active = 'menu-item-home';"); ?>
</script>

The variable "active" is assigned with the corresponding item of each page.

Now, you can use this variable to highlight the active menu item as below.

$(window).ready(function(){$("#" + active).addClass("active");});


问:
TD works center and left align but not right align
My code add one row of a table dinamicaly. The alignment wrks for the firs row that is static but not for the other rows. Intead of this I have tested the dinamic content with center align attribute and it works.

Here is the part of the code that I am refering, and below the complete function.

```<code>colsfila=document.createElement('td');
textonodo=document.createTextNode(qTrib);
idnodo='qTrib'+NUM_FILAS;
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.setAttribute('style', 'text-align: center;');
colsfila.appendChild(textonodo);
novafila.appendChild(colsfila);

colsfila=document.createElement('td');
textonodo=document.createTextNode(vUnTrib);
idnodo='vUnTrib'+NUM_FILAS;
var align='rigth';
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.appendChild(textonodo);
colsfila.setAttribute('style','text-align :rigth;');
novafila.appendChild(colsfila);

function importxmlcompra(){
    var novostring= new String(document.getElementById('file').value);

    if (novostring!=''){
        oPed.open("GET",novostring, false);
        oPed.send();
        var result = oPed.responseXML;
        if (!result.documentElement && oPed.responseStream) {
        result.load(oPed.responseStream);
        }
    }else{
            alert ("Por favor seleccione un arquivo XML");
    }
    if (!result||result.getElementsByTagName('emit').length==0){
        return};
    var emit=result.getElementsByTagName("emit")[0];
    var dEmi=result.getElementsByTagName('dEmi')[0].childNodes[0].nodeValue;
    dEmi=dataNF(dEmi);
    document.getElementById('dEmi').value=dEmi;
    var CNPJ=emit.getElementsByTagName('CNPJ')[0].childNodes[0].nodeValue;
    document.getElementById('cnpj').value=CNPJ;
    var razaosocialimportada=emit.getElementsByTagName("xNome")[0].childNodes[0].nodeValue;
    document.getElementById("xNome").value=razaosocialimportada;
    var ide=result.getElementsByTagName("ide")[0];
    var nNF=ide.getElementsByTagName("nNF")[0].childNodes[0].nodeValue;
    document.getElementById("nNF").value=nNF;
    var vNF='R$'+number_format(result.getElementsByTagName("vNF")[0].childNodes[0].nodeValue,2,',','.');
    document.getElementById("vNF").value=vNF;

    var detlength=result.getElementsByTagName("det").length;
    var j=0, cProd, xProd, vUnTrib, qTrib, vProd;
    var tabledet=document.getElementsByTagName('table')[0];
    var tablerows=document.getElementsByTagName('table')[0].rows.length;
    var novafila, colsfila, idnodo, textonodo, imgnodo, attid, ant;

    while(j<detlength){
        det=result.getElementsByTagName('det')[j];
        cProd=det.getElementsByTagName('cProd')[0].childNodes[0].nodeValue;
        xProd=det.getElementsByTagName('xProd')[0].childNodes[0].nodeValue;
        vUnTrib=number_format(det.getElementsByTagName('vUnTrib')[0].childNodes[0].nodeValue,2,',','.');
        qTrib=number_format(det.getElementsByTagName('qTrib')[0].childNodes[0].nodeValue,0,'','.');
        vProd=number_format(det.getElementsByTagName('vProd')[0].childNodes[0].nodeValue,2,',','.');

        if(validacProd(cProd)==true){

            if (tablerows==2&& document.getElementById('cProd0').innerHTML=='0'){
              document.getElementById('cProd0').innerHTML=cProd;
              document.getElementById('xProd0').innerHTML=xProd;
              document.getElementById('vUnTrib0').innerHTML=vUnTrib;
              document.getElementById('qTrib0').innerHTML=qTrib;
              document.getElementById('vProd0').innerHTML=vProd;
            }else{
                novafila=document.createElement('tr');
                textonodo=document.createTextNode(cProd);
                attid=document.createAttribute('id');
                colsfila=document.createElement('td');
                idnodo='cProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);
                tabledet.appendChild(novafila)

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(xProd);
                idnodo='xProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='codproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('style','display:none');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='descproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(qTrib);
                idnodo='qTrib'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.setAttribute('style', 'text-align: center;');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vUnTrib);
                idnodo='vUnTrib'+NUM_FILAS;
                var align='rigth';
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                colsfila.setAttribute('style','text-align :rigth;');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vProd);
                idnodo='vProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('align', 'rigth');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                imgnodo=document.createElement('img');
                idnodo='addrow'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addRowdetCompra(this)');
                imgnodo.setAttribute('src','../../../imagens/addrow/addrow.png');
                colsfila.appendChild(imgnodo);
                novafila.appendChild(colsfila);
                document.getElementsByTagName('table')[0].appendChild(novafila);
            }
        }
        tablerows=document.getElementsByTagName('table')[0].rows.length;
        NUM_FILAS++;
        j++;
    }
    comandosfilas();
}
</code>```

答: You're spelling right incorrectly in multiple places. Do a search and replace for rigth to right.

Body:
My code add one row of a table dinamicaly. The alignment wrks for the firs row that is static but not for the other rows. Intead of this I have tested the dinamic content with center align attribute and it works.

Here is the part of the code that I am refering, and below the complete function.

colsfila=document.createElement('td');
textonodo=document.createTextNode(qTrib);
idnodo='qTrib'+NUM_FILAS;
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.setAttribute('style', 'text-align: center;');
colsfila.appendChild(textonodo);
novafila.appendChild(colsfila);

colsfila=document.createElement('td');
textonodo=document.createTextNode(vUnTrib);
idnodo='vUnTrib'+NUM_FILAS;
var align='rigth';
colsfila.setAttribute('id', idnodo);
colsfila.setAttribute('onclick','addInputdetCompra(this)');
colsfila.appendChild(textonodo);
colsfila.setAttribute('style','text-align :rigth;');
novafila.appendChild(colsfila);

function importxmlcompra(){
    var novostring= new String(document.getElementById('file').value);

    if (novostring!=''){
        oPed.open("GET",novostring, false);
        oPed.send();
        var result = oPed.responseXML;
        if (!result.documentElement && oPed.responseStream) {
        result.load(oPed.responseStream);
        }
    }else{
            alert ("Por favor seleccione un arquivo XML");
    }
    if (!result||result.getElementsByTagName('emit').length==0){
        return};
    var emit=result.getElementsByTagName("emit")[0];
    var dEmi=result.getElementsByTagName('dEmi')[0].childNodes[0].nodeValue;
    dEmi=dataNF(dEmi);
    document.getElementById('dEmi').value=dEmi;
    var CNPJ=emit.getElementsByTagName('CNPJ')[0].childNodes[0].nodeValue;
    document.getElementById('cnpj').value=CNPJ;
    var razaosocialimportada=emit.getElementsByTagName("xNome")[0].childNodes[0].nodeValue;
    document.getElementById("xNome").value=razaosocialimportada;
    var ide=result.getElementsByTagName("ide")[0];
    var nNF=ide.getElementsByTagName("nNF")[0].childNodes[0].nodeValue;
    document.getElementById("nNF").value=nNF;
    var vNF='R$'+number_format(result.getElementsByTagName("vNF")[0].childNodes[0].nodeValue,2,',','.');
    document.getElementById("vNF").value=vNF;

    var detlength=result.getElementsByTagName("det").length;
    var j=0, cProd, xProd, vUnTrib, qTrib, vProd;
    var tabledet=document.getElementsByTagName('table')[0];
    var tablerows=document.getElementsByTagName('table')[0].rows.length;
    var novafila, colsfila, idnodo, textonodo, imgnodo, attid, ant;

    while(j<detlength){
        det=result.getElementsByTagName('det')[j];
        cProd=det.getElementsByTagName('cProd')[0].childNodes[0].nodeValue;
        xProd=det.getElementsByTagName('xProd')[0].childNodes[0].nodeValue;
        vUnTrib=number_format(det.getElementsByTagName('vUnTrib')[0].childNodes[0].nodeValue,2,',','.');
        qTrib=number_format(det.getElementsByTagName('qTrib')[0].childNodes[0].nodeValue,0,'','.');
        vProd=number_format(det.getElementsByTagName('vProd')[0].childNodes[0].nodeValue,2,',','.');

        if(validacProd(cProd)==true){

            if (tablerows==2&& document.getElementById('cProd0').innerHTML=='0'){
              document.getElementById('cProd0').innerHTML=cProd;
              document.getElementById('xProd0').innerHTML=xProd;
              document.getElementById('vUnTrib0').innerHTML=vUnTrib;
              document.getElementById('qTrib0').innerHTML=qTrib;
              document.getElementById('vProd0').innerHTML=vProd;
            }else{
                novafila=document.createElement('tr');
                textonodo=document.createTextNode(cProd);
                attid=document.createAttribute('id');
                colsfila=document.createElement('td');
                idnodo='cProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);
                tabledet.appendChild(novafila)

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(xProd);
                idnodo='xProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='codproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('style','display:none');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                idnodo='descproduto'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(qTrib);
                idnodo='qTrib'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.setAttribute('style', 'text-align: center;');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vUnTrib);
                idnodo='vUnTrib'+NUM_FILAS;
                var align='rigth';
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addInputdetCompra(this)');
                colsfila.appendChild(textonodo);
                colsfila.setAttribute('style','text-align :rigth;');
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                textonodo=document.createTextNode(vProd);
                idnodo='vProd'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('align', 'rigth');
                colsfila.appendChild(textonodo);
                novafila.appendChild(colsfila);

                colsfila=document.createElement('td');
                imgnodo=document.createElement('img');
                idnodo='addrow'+NUM_FILAS;
                colsfila.setAttribute('id', idnodo);
                colsfila.setAttribute('onclick','addRowdetCompra(this)');
                imgnodo.setAttribute('src','../../../imagens/addrow/addrow.png');
                colsfila.appendChild(imgnodo);
                novafila.appendChild(colsfila);
                document.getElementsByTagName('table')[0].appendChild(novafila);
            }
        }
        tablerows=document.getElementsByTagName('table')[0].rows.length;
        NUM_FILAS++;
        j++;
    }
    comandosfilas();
}


问:
Google Chrome Flicker
Hi guys I am new here and not a coder but rather a manager for our upocoming project to be released in the summer of 2017.

My developers and coders could not find what is the cause of the flicker that exists on Chrome alone for our website at www.playinera.com

I am well aware that this is a Chrome issue and well documented bug. After searching for weeks on various sites, including stackoverflow, we were not able to pinpoint its cause.

If anyone has experience with this flickering issue and would like to take a stab at it, that would be greatly appreciated. I really can't post any snippets of code because we don't know where the issue lies.

Willing to give access to any tools or credentials you may need and can spare time to go over any details in private.

答:
Changing personalization settings doesn't work for Chrome flickering in some cases.

Just go to the Chrome settings, search for

```<code>Use hardware acceleration when available
</code>```

uncheck it and relaunch Chrome.

Title: Google Chrome Flicker

Body:
Changing personalization settings doesn't work for Chrome flickering in some cases.

Just go to the Chrome settings, search for

Use hardware acceleration when available

uncheck it and relaunch Chrome.


问:
\r keep printing time on same line even after another print is made
i have a thread that calculates the time every 1 second to get the total elapsed time. This works great but i need to make it stay on the same line even after printing another line. Currently it is doing this:

```<code>[~] 00:00:02
ok #this is a test print to see if it stays on the same line and of course it dosen't.
[~] 00:00:08
</code>```

```<code>def total_elapsed_time(start):
    while True:
        elapsed_time = time.time() - start
        print(colorama.Fore.LIGHTBLUE_EX + "[~] " + time.strftime("%H:%M:%S", time.gmtime(elapsed_time)), end="\r")
        time.sleep(1) #updates every second
</code>```

this is my code. Ive been reading about \r \n and \r\n and \r does the job partially but i still need it to stay on the same line always. I'm not sure if this is even possible although i have seen it done in other languages so i think it is.

答:
You can use \r to rewrite the bottom line.

If you want to print something else (like "ok") "above" the timestamp:

erase the bottom line with the timestamp first (you may have to overwrite it with spaces and then use \r again if the next thing isn't long enough), then

print the other thing (the "ok"), then

write the timestamp again below it on a new line.

For example,

```<code>>>> from datetime import datetime
>>> import time
>>> for c in 'abcdefg':
...   print(datetime.now(), end='\r')  # timestamp
...   time.sleep(1)
...   print(' '*80, end='\r')  # overwrite timestamp line with spaces
...   print(c)  # print something else "above" the next timestamp
...
a
b
c
d
e
f
g
>>>
</code>```

The end result has no timestamp, but you can see it while it's looping. Try it.

If you don't start out scrolled to the bottom, the timestamp line "moves" but once you print enough lines to fill the terminal, the bottom line will stay in place at the bottom. You can also use this to display progress bars and spinners and things like that.

Note also that you can use the backspace character to back up one character instead of the carriage return to back up to the beginning of the line.

Body:
i have a thread that calculates the time every 1 second to get the total elapsed time. This works great but i need to make it stay on the same line even after printing another line. Currently it is doing this:

[~] 00:00:02
ok #this is a test print to see if it stays on the same line and of course it dosen't.
[~] 00:00:08

def total_elapsed_time(start):
    while True:
        elapsed_time = time.time() - start
        print(colorama.Fore.LIGHTBLUE_EX + "[~] " + time.strftime("%H:%M:%S", time.gmtime(elapsed_time)), end="\r")
        time.sleep(1) #updates every second

this is my code. Ive been reading about \r \n and \r\n and \r does the job partially but i still need it to stay on the same line always. I'm not sure if this is even possible although i have seen it done in other languages so i think it is.

Body:
You can use \r to rewrite the bottom line.

If you want to print something else (like "ok") "above" the timestamp:

erase the bottom line with the timestamp first (you may have to overwrite it with spaces and then use \r again if the next thing isn't long enough), then

print the other thing (the "ok"), then

write the timestamp again below it on a new line.

For example,

>>> from datetime import datetime
>>> import time
>>> for c in 'abcdefg':
...   print(datetime.now(), end='\r')  # timestamp
...   time.sleep(1)
...   print(' '*80, end='\r')  # overwrite timestamp line with spaces
...   print(c)  # print something else "above" the next timestamp
...
a
b
c
d
e
f
g
>>>

The end result has no timestamp, but you can see it while it's looping. Try it.

If you don't start out scrolled to the bottom, the timestamp line "moves" but once you print enough lines to fill the terminal, the bottom line will stay in place at the bottom. You can also use this to display progress bars and spinners and things like that.

Note also that you can use the backspace character to back up one character instead of the carriage return to back up to the beginning of the line.


问:
How should I call the network request in the tab bar controller and pass data to different view controllers?
I'm doing a network request twice, in the view controllers connected to a tab bar. If I can do the network request directly in the tab bar controller, I can pass the data from there in just one network request.

I tried this but it is giving a lot of errors.
- var pages : [page] = [] is an array of structs that I want to pass. It is working fine, I just need to figure out the passing part.

```<code> override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let feedVC = segue.destination as! FeedViewController
        let categoriesVC = segue.destination as! CategoriesGridViewController
        feedVC.pages = pages as! [[String:Any]]
        categoriesVC.pages = pages [[String:Any]]
    }
</code>```

Screenshot of my StoryBoard

I fetch from a database of images and their information. I make an array of structs and use that to display the data in the App. All of that is working fine.
Page -

```<code>struct page {
    var urlsArray : [String]
    var caption : String
    var title : String
    var time : String
}
</code>```

答:
Without seeing what data you are actually trying to pass, I would guess you should create a Class (not struct) of type Page (or whatever you want to call it) and pass an array of [Page] through the view controllers. Here's an example of how to set it up:

```<code>class Page {

    private var _title: String
    private var _otherVariable: Int

    var title: String {
        return _title
    }

    var otherVariable: Int {
        return _otherVariable
    }

    init(title: String, otherVariable: Int) {
        self._title = title
        self._otherVariable = otherVariable
    }

}
</code>```

//IN VIEW CONTROLLER 1

```<code>//when you get the data, set data for a Page
let item = Page(title: "Example", otherVariable: 12345)
let item2 = Page(title: "Example2", otherVariable: 67890)

//call this to segue
func segueToFeedViewController() {
    let dataToSendToNextViewController: [Page] = [item, item2] //add data here
    performSegue(withIdentifier: "ToFeedViewController", sender: dataToSendToNextViewController)
}

//use if let for safety
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let newVC = segue.destination as? FeedViewController {
        assert(sender as? [Page] != nil)
        newVC.pages = sender as! [Page]
    }
}
</code>```

Body:
I'm doing a network request twice, in the view controllers connected to a tab bar. If I can do the network request directly in the tab bar controller, I can pass the data from there in just one network request.

I tried this but it is giving a lot of errors.
- var pages : [page] = [] is an array of structs that I want to pass. It is working fine, I just need to figure out the passing part.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let feedVC = segue.destination as! FeedViewController
        let categoriesVC = segue.destination as! CategoriesGridViewController
        feedVC.pages = pages as! [[String:Any]]
        categoriesVC.pages = pages [[String:Any]]
    }

Screenshot of my StoryBoard

I fetch from a database of images and their information. I make an array of structs and use that to display the data in the App. All of that is working fine.
Page -

struct page {
    var urlsArray : [String]
    var caption : String
    var title : String
    var time : String
}

Body:
Without seeing what data you are actually trying to pass, I would guess you should create a Class (not struct) of type Page (or whatever you want to call it) and pass an array of [Page] through the view controllers. Here's an example of how to set it up:

class Page {

    private var _title: String
    private var _otherVariable: Int

    var title: String {
        return _title
    }

    var otherVariable: Int {
        return _otherVariable
    }

    init(title: String, otherVariable: Int) {
        self._title = title
        self._otherVariable = otherVariable
    }

}

//IN VIEW CONTROLLER 1

//when you get the data, set data for a Page
let item = Page(title: "Example", otherVariable: 12345)
let item2 = Page(title: "Example2", otherVariable: 67890)

//call this to segue
func segueToFeedViewController() {
    let dataToSendToNextViewController: [Page] = [item, item2] //add data here
    performSegue(withIdentifier: "ToFeedViewController", sender: dataToSendToNextViewController)
}

//use if let for safety
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let newVC = segue.destination as? FeedViewController {
        assert(sender as? [Page] != nil)
        newVC.pages = sender as! [Page]
    }
}


答:
Try this:</p>

```<code>with open('numbers.txt') as fp:
    lst = [float(line.strip()) for line in fp if line.strip()]
    user_input = float(input("Threshold: "))
    for num in lst:
        if num > user_input:
            print(num)
</code>```

Title: How do I iterate through a file containing a list of floating point numbers in Python?

Body:
Try this:

with open('numbers.txt') as fp:
    lst = [float(line.strip()) for line in fp if line.strip()]
    user_input = float(input("Threshold: "))
    for num in lst:
        if num > user_input:
            print(num)


问:
Android Studio 4.0 shortcuts changed
This week I updated to Android Studio 4.0, and one of the first things I noticed was that some of my favorite shortcuts like CMD+W has changed to CMD+F4 (which the touchbar wont actually show the F keys anymore), and also CMD+O changed to CMD+N.  Is there any way to get them back to what they were to set to in Android Studio 3?</p>

答:
Method 1:

Go to this location :

```<code>C:\Users\<user_name>\.AndroidStudio3.0\config\keymaps
</code>```

And copy the file present inside that (Usually Default Proper Redo.xml) and paste it inside

```<code>C:\Users\<user_name>\.AndroidStudio4.0\config\keymaps
</code>```

It will bring back all old shortcuts or alternatively

Method 2:

go to settings and search for keymap this window will come up

and search for the keystroke you want or navigate around those

Right-click on the shortcut you want to change and a window will come up just press the new keystroke that you want to assign

If the same keystroke is applied to some other actions it will show a dailog just confirm it by removing old keystrokes ...

You can relate to MacOS ...

Title: Android Studio 4.0 shortcuts changed

Body:
Method 1:

Go to this location :

C:\Users\<user_name>\.AndroidStudio3.0\config\keymaps

And copy the file present inside that (Usually Default Proper Redo.xml) and paste it inside

C:\Users\<user_name>\.AndroidStudio4.0\config\keymaps

It will bring back all old shortcuts or alternatively

Method 2:

go to settings and search for keymap this window will come up

and search for the keystroke you want or navigate around those

Right-click on the shortcut you want to change and a window will come up just press the new keystroke that you want to assign

If the same keystroke is applied to some other actions it will show a dailog just confirm it by removing old keystrokes ...

You can relate to MacOS ...