问:
Invalid argument supplied for foreach() in Form and Multi Image upload in Laravel
The Form upload and the product image as featured image and other other images using the store function of laravel     </p>

```<code>use App\Productimage;
use App\Products;
public function store(Request $request)
{
    $featured = $request->featured_image->store('products_featured');
    $product = Products::create([       //uploading successfully
    'name'=>$request->name,
    'featured_image' => $featured,
    ]);
             foreach ($request->photos as $photo) {   //error
        $filename = $photo->store('product_images');
        Productimage::create([
            'product_id' => $product->id,
            'image_name' => $filename,
        ]);
    }
    return back();
}
</code>```

答:
Make sure $request->photos is an array and your form is a multipart/form-data.
You need to send your files from your blade (or wherever your are sending them from) in photos[], e.g.

```<code><input type="file" name="photos[]"/>
</code>```

P.S - In your controller method, you should access $request->photos like this $request->file('photos'). - This is not the cause of your error but if you don't do this, you'll get a JSON object instead of file content.

Body:
The Form upload and the product image as featured image and other other images using the store function of laravel

use App\Productimage;
use App\Products;
public function store(Request $request)
{
    $featured = $request->featured_image->store('products_featured');
    $product = Products::create([       //uploading successfully
    'name'=>$request->name,
    'featured_image' => $featured,
    ]);
             foreach ($request->photos as $photo) {   //error
        $filename = $photo->store('product_images');
        Productimage::create([
            'product_id' => $product->id,
            'image_name' => $filename,
        ]);
    }
    return back();
}

Body:
Make sure $request->photos is an array and your form is a multipart/form-data.
You need to send your files from your blade (or wherever your are sending them from) in photos[], e.g.

<input type="file" name="photos[]"/>

P.S - In your controller method, you should access $request->photos like this $request->file('photos'). - This is not the cause of your error but if you don't do this, you'll get a JSON object instead of file content.


来源: stackexchange

问:
how to show user's username when logged into a wordpress site?
I would like to have the header of my site reading "Logged in as " when a user is logged into my wordpress site.

I dont know how to echo the username of the current user, heres the code I'm got...

```<code><?php

if ( is_user_logged_in() ) {
echo '<ul id="mem" class="clearfix">
            <li><a href="#">Logged in as Username</a></li>
            <li><a href="#">Logout</a></li>
        </ul>';
} else {
echo '<ul id="mem" class="clearfix">
            <li><a href="#">Register</a></li>
            <li><a href="#">Login</a></li>
        </ul>';
}
?>
</code>```

and I'd like to replace Username.

Any help is much appreciated.

Thanks,

Mark

答:
you can use get_currentuserinfo() function to grab any logged in users info..

```<code><?php global $current_user;
      get_currentuserinfo();

      echo 'Username: ' . $current_user->user_login . "\n";
      echo 'User email: ' . $current_user->user_email . "\n";
      echo 'User first name: ' . $current_user->user_firstname . "\n";
      echo 'User last name: ' . $current_user->user_lastname . "\n";
      echo 'User display name: ' . $current_user->display_name . "\n";
      echo 'User ID: ' . $current_user->ID . "\n";
?>
</code>```

in your case it could be

```<code><?php
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();

echo '<ul id="mem" class="clearfix">
            <li><a href="#">Logged in as '.$current_user->display_name.'</a></li>
            <li><a href="#">Logout</a></li>
        </ul>';
} else {
echo '<ul id="mem" class="clearfix">
            <li><a href="#">Register</a></li>
            <li><a href="#">Login</a></li>
        </ul>';
}
?>
</code>```

:)

ContentLicense: CC BY-SA 3.0

Body:
I would like to have the header of my site reading "Logged in as " when a user is logged into my wordpress site.

I dont know how to echo the username of the current user, heres the code I'm got...

<?php

if ( is_user_logged_in() ) {
echo '

Logged in as Username

Logout

';
} else {
echo '

Register

Login

';
}
?>

and I'd like to replace Username.

Any help is much appreciated.

Thanks,

Mark

Body:
you can use get_currentuserinfo() function to grab any logged in users info..

<?php global $current_user;
      get_currentuserinfo();

      echo 'Username: ' . $current_user->user_login . "\n";
      echo 'User email: ' . $current_user->user_email . "\n";
      echo 'User first name: ' . $current_user->user_firstname . "\n";
      echo 'User last name: ' . $current_user->user_lastname . "\n";
      echo 'User display name: ' . $current_user->display_name . "\n";
      echo 'User ID: ' . $current_user->ID . "\n";
?>

in your case it could be

<?php
if ( is_user_logged_in() ) {
global $current_user;
get_currentuserinfo();

echo '<ul id="mem" class="clearfix">
            <li><a href="#">Logged in as '.$current_user->display_name.'</a></li>
            <li><a href="#">Logout</a></li>
        </ul>';
} else {
echo '<ul id="mem" class="clearfix">
            <li><a href="#">Register</a></li>
            <li><a href="#">Login</a></li>
        </ul>';
}
?>

:)


问:
Tasks created with create_task that are never awaited, seem to break expectations of cancelation for child tasks
Imagine we're writing an application which allows a user to run an application (let's say it's a series of important operations against an API) continuously, and can run multiple applications concurrently. Requirements include:

the user can control the number of concurrent applications (which may limit concurrent load against an API, which is often important)

if the OS tries to close the Python program running this thing, it should gracefully terminate, allowing any in-progress applications to complete their run before closing

The question here is specifically about the task manager we've coded, so let's stub out some code that illustrates this problem:

```<code>import asyncio
import signal

async def work_chunk():
    """Simulates a chunk of work that can possibly fail"""
    await asyncio.sleep(1)

async def protected_work():
    """All steps of this function MUST complete, the caller should shield it from cancelation."""
    print("protected_work start")
    for i in range(3):
        await work_chunk()
        print(f"protected_work working... {i+1} out of 3 steps complete")
    print("protected_work done... ")

async def subtask():
    print("subtask: starting loop of protected work...")
    cancelled = False
    while not cancelled:
        protected_coro = asyncio.create_task(protected_work())
        try:
            await asyncio.shield(protected_coro)
        except asyncio.CancelledError:
            cancelled = True
            await protected_coro
    print("subtask: cancelation complete")

async def subtask_manager():
    """
    Manage a pool of subtask workers.
    (In the real world, the user can dynamically change the concurrency, but here we'll
    hard code it at 3.)
    """
    tasks = {}
    while True:
        for i in range(3):
            task = tasks.get(i)
            if not task or task.done():
                tasks[i] = asyncio.create_task(subtask())
        await asyncio.sleep(5)

def shutdown(signal, main_task):
    """Cleanup tasks tied to the service's shutdown."""
    print(f"Received exit signal {signal.name}. Scheduling cancelation:")
    main_task.cancel()

async def main():
    print("main... start")
    coro = asyncio.ensure_future(subtask_manager())
    loop = asyncio.get_running_loop()
    loop.add_signal_handler(signal.SIGINT, lambda: shutdown(signal.SIGINT, coro))
    loop.add_signal_handler(signal.SIGTERM, lambda: shutdown(signal.SIGTERM, coro))
    await coro
    print("main... done")

def run():
    asyncio.run(main())

run()
</code>```

subtask_manager manages a pool of workers, periodically looking up what the present concurrency requirement is and updating the number of active workers appropriately (note that the code above cuts out most of that, and just hard codes a number, since it isn't important to the question).

subtask is the worker loop itself, which continuously runs protected_work() until someone cancels it.

But this code is broken. When you give it a SIGINT, the whole thing immediately crashes.

Before I explain further, let me point you at a critical bit of code:

```<code>1   protected_coro = asyncio.create_task(protected_work())
2   try:
3       await asyncio.shield(protected_coro)
4   except asyncio.CancelledError:
5       cancelled = True
6       await protected_coro  # <-- This will raise CancelledError too!
</code>```

After some debugging, we find that our try/except block isn't working. We find that both line 3 AND line 6 raise CancelledError.

When we dig in further, we find that ALL "await" calls throw CancelledError after the subtask manager is canceled, not just the line noted above. (i.e., the second line of work_chunk(), await asyncio.sleep(1), and the 4th line of protected_work(), await work_chunk(), also raise CancelledError.)

What's going on here?

It would seem that Python, for some reason, isn't propagating cancelation as you would expect, and just throws up its hands and says "I'm canceling everything now".

Why?

Clearly, I don't understand how cancelation propagation works in Python. I've struggled to find documentation on how it works. Can someone describe to me how cancelation is propagated in a clear-minded way that explains the behavior found in the example above?

答:
What's going on here? It would seem that Python, for some reason, isn't propagating cancelation as you would expect, and just throws up its hands and says "I'm canceling everything now".

TL;DR Canceling everything is precisely what's happening, simply because the event loop is exiting.

To investigate this, I changed the invocation of add_signal_handler() to loop.call_later(.5, lambda: shutdown(signal.SIGINT, coro)). Python's Ctrl+C handling has odd corners, and I wanted to check whether the strange behavior is the result of that. But the bug was perfectly reproducible without signals, so it wasn't that.

And yet, asyncio cancellation really shouldn't work like your code shows. Canceling a task propagates to the future (or another task) it awaits, but shield is specifically implemented to circumvent that. It creates and returns a fresh future, and connects the result of the original (shielded) future to the new one in a way that cancel() doesn't know how to follow.

It took me some time to unearth what really happens, and that is:

await coro at the end of main awaits the task that gets cancelled, so it gets a CancelledError as soon as shutdown cancels it;

the exception causes main to exit and enters the cleanup sequence at the end of asyncio.run(). This cleanup sequence cancels all tasks, including the ones you've shielded.

You can test it by changing await coro at the end of main() to:

try:
    await coro
finally:
    print('main... done')
```

<p>And you will see that "main... done" is printed prior to all the mysterious cancellations you've been witnessing.</p>

<p>So that clears the mystery and to fix the issue, you should postpone exiting <code>main</code> until everything is done. For example, you can create the <code>tasks</code> dict in <code>main</code>, pass it to <code>subtask_manager()</code>, and then await those critical tasks when the main task gets cancelled:</p>

<pre class="lang-py prettyprint-override"><code>async def subtask_manager(tasks):
    while True:
        for i in range(3):
            task = tasks.get(i)
            if not task or task.done():
                tasks[i] = asyncio.create_task(subtask())

        try:
            await asyncio.sleep(5)
        except asyncio.CancelledError:
            for t in tasks.values():
                t.cancel()
            raise

# ... shutdown unchanged

async def main():
    print("main... start")
    tasks = {}
    main_task = asyncio.ensure_future(subtask_manager(tasks))
    loop = asyncio.get_running_loop()
    loop.add_signal_handler(signal.SIGINT, lambda: shutdown(signal.SIGINT, main_task))
    loop.add_signal_handler(signal.SIGTERM, lambda: shutdown(signal.SIGTERM, main_task))
    try:
        await main_task
    except asyncio.CancelledError:
        await asyncio.gather(*tasks.values())
    finally:
        print("main... done")
</code>```

Note that the main task must explicitly cancel its subtasks because that actually wouldn't happen automatically. Cancellation is propagated through a chain of awaits, and subtask_manager doesn't explicitly awaits its subtasks, it just spawns them and awaits something else, effectively shielding them.

ContentLicense: CC BY-SA 4.0

Body:
Imagine we're writing an application which allows a user to run an application (let's say it's a series of important operations against an API) continuously, and can run multiple applications concurrently. Requirements include:

the user can control the number of concurrent applications (which may limit concurrent load against an API, which is often important)

if the OS tries to close the Python program running this thing, it should gracefully terminate, allowing any in-progress applications to complete their run before closing

The question here is specifically about the task manager we've coded, so let's stub out some code that illustrates this problem:

import asyncio
import signal

async def work_chunk():
    """Simulates a chunk of work that can possibly fail"""
    await asyncio.sleep(1)

async def protected_work():
    """All steps of this function MUST complete, the caller should shield it from cancelation."""
    print("protected_work start")
    for i in range(3):
        await work_chunk()
        print(f"protected_work working... {i+1} out of 3 steps complete")
    print("protected_work done... ")

async def subtask():
    print("subtask: starting loop of protected work...")
    cancelled = False
    while not cancelled:
        protected_coro = asyncio.create_task(protected_work())
        try:
            await asyncio.shield(protected_coro)
        except asyncio.CancelledError:
            cancelled = True
            await protected_coro
    print("subtask: cancelation complete")

async def subtask_manager():
    """
    Manage a pool of subtask workers.
    (In the real world, the user can dynamically change the concurrency, but here we'll
    hard code it at 3.)
    """
    tasks = {}
    while True:
        for i in range(3):
            task = tasks.get(i)
            if not task or task.done():
                tasks[i] = asyncio.create_task(subtask())
        await asyncio.sleep(5)

def shutdown(signal, main_task):
    """Cleanup tasks tied to the service's shutdown."""
    print(f"Received exit signal {signal.name}. Scheduling cancelation:")
    main_task.cancel()

async def main():
    print("main... start")
    coro = asyncio.ensure_future(subtask_manager())
    loop = asyncio.get_running_loop()
    loop.add_signal_handler(signal.SIGINT, lambda: shutdown(signal.SIGINT, coro))
    loop.add_signal_handler(signal.SIGTERM, lambda: shutdown(signal.SIGTERM, coro))
    await coro
    print("main... done")

def run():
    asyncio.run(main())

run()

subtask_manager manages a pool of workers, periodically looking up what the present concurrency requirement is and updating the number of active workers appropriately (note that the code above cuts out most of that, and just hard codes a number, since it isn't important to the question).

subtask is the worker loop itself, which continuously runs protected_work() until someone cancels it.

But this code is broken. When you give it a SIGINT, the whole thing immediately crashes.

Before I explain further, let me point you at a critical bit of code:

1   protected_coro = asyncio.create_task(protected_work())
2   try:
3       await asyncio.shield(protected_coro)
4   except asyncio.CancelledError:
5       cancelled = True
6       await protected_coro  # <-- This will raise CancelledError too!

After some debugging, we find that our try/except block isn't working. We find that both line 3 AND line 6 raise CancelledError.

When we dig in further, we find that ALL "await" calls throw CancelledError after the subtask manager is canceled, not just the line noted above. (i.e., the second line of work_chunk(), await asyncio.sleep(1), and the 4th line of protected_work(), await work_chunk(), also raise CancelledError.)

What's going on here?

It would seem that Python, for some reason, isn't propagating cancelation as you would expect, and just throws up its hands and says "I'm canceling everything now".

Why?

Clearly, I don't understand how cancelation propagation works in Python. I've struggled to find documentation on how it works. Can someone describe to me how cancelation is propagated in a clear-minded way that explains the behavior found in the example above?

Body:
What's going on here? It would seem that Python, for some reason, isn't propagating cancelation as you would expect, and just throws up its hands and says "I'm canceling everything now".

TL;DR Canceling everything is precisely what's happening, simply because the event loop is exiting.

To investigate this, I changed the invocation of add_signal_handler() to loop.call_later(.5, lambda: shutdown(signal.SIGINT, coro)). Python's Ctrl+C handling has odd corners, and I wanted to check whether the strange behavior is the result of that. But the bug was perfectly reproducible without signals, so it wasn't that.

And yet, asyncio cancellation really shouldn't work like your code shows. Canceling a task propagates to the future (or another task) it awaits, but shield is specifically implemented to circumvent that. It creates and returns a fresh future, and connects the result of the original (shielded) future to the new one in a way that cancel() doesn't know how to follow.

It took me some time to unearth what really happens, and that is:

await coro at the end of main awaits the task that gets cancelled, so it gets a CancelledError as soon as shutdown cancels it;

the exception causes main to exit and enters the cleanup sequence at the end of asyncio.run(). This cleanup sequence cancels all tasks, including the ones you've shielded.

You can test it by changing await coro at the end of main() to:

try:
    await coro
finally:
    print('main... done')

And you will see that "main... done" is printed prior to all the mysterious cancellations you've been witnessing.

So that clears the mystery and to fix the issue, you should postpone exiting main until everything is done. For example, you can create the tasks dict in main, pass it to subtask_manager(), and then await those critical tasks when the main task gets cancelled:

async def subtask_manager(tasks):
    while True:
        for i in range(3):
            task = tasks.get(i)
            if not task or task.done():
                tasks[i] = asyncio.create_task(subtask())

        try:
            await asyncio.sleep(5)
        except asyncio.CancelledError:
            for t in tasks.values():
                t.cancel()
            raise

# ... shutdown unchanged

async def main():
    print("main... start")
    tasks = {}
    main_task = asyncio.ensure_future(subtask_manager(tasks))
    loop = asyncio.get_running_loop()
    loop.add_signal_handler(signal.SIGINT, lambda: shutdown(signal.SIGINT, main_task))
    loop.add_signal_handler(signal.SIGTERM, lambda: shutdown(signal.SIGTERM, main_task))
    try:
        await main_task
    except asyncio.CancelledError:
        await asyncio.gather(*tasks.values())
    finally:
        print("main... done")

Note that the main task must explicitly cancel its subtasks because that actually wouldn't happen automatically. Cancellation is propagated through a chain of awaits, and subtask_manager doesn't explicitly awaits its subtasks, it just spawns them and awaits something else, effectively shielding them.


问:
Oracle differences using Quotes in case statement and insert
I encountered this scenario where the insert based on '' on number column works fine while the case statement gives different error.
"inconsistent datatypes: expected %s got %s"

I have gone through some of the explanation given here (ORA-00932 inconsistent datatypes expected char got number ) and Oracle SQL CASE WHEN ORA-00932: inconsistent datatypes: expected CHAR got NUMBER 00932. 00000 - "inconsistent datatypes: expected %s got %s"  and I understand that I need to use it without quotes but I wanted to understand the behavior of case statement. SQL server does not behave like this, but why only oracle. Is this oracle default behavior with case statement.

If I create and insert values, I can do it without any error.

```<code>create table testtbl (name varchar2(50), id number(10,2));

insert into testtbl values ('abc', '123');
insert into testtbl values ('test', '200');
</code>```

When I try to update the column using case statement I am getting this error. I can use to_number or remove the quotes to avoid this error but wanted to understand why it happens with quotes when the column given in the else statement is number itself. Doesn't implicit conversion exist in Oracle?

```<code>update testtbl
set id = case when name = 'abc' then '5000' else id end;
</code>```

答:
Doesn't implicit conversion exist in Oracle?

It does. See documentation eg here.

Is this oracle default behavior with case statement.

Yes. From the documentation:

For both simple and searched CASE expressions, all of the return_exprs must either have the same datatype (CHAR, VARCHAR2, NCHAR, or NVARCHAR2, NUMBER, BINARY_FLOAT, or BINARY_DOUBLE) or must all have a numeric datatype.

Body:
I encountered this scenario where the insert based on '' on number column works fine while the case statement gives different error.
"inconsistent datatypes: expected %s got %s"

I have gone through some of the explanation given here (ORA-00932 inconsistent datatypes expected char got number ) and Oracle SQL CASE WHEN ORA-00932: inconsistent datatypes: expected CHAR got NUMBER 00932. 00000 - "inconsistent datatypes: expected %s got %s"  and I understand that I need to use it without quotes but I wanted to understand the behavior of case statement. SQL server does not behave like this, but why only oracle. Is this oracle default behavior with case statement.

If I create and insert values, I can do it without any error.

create table testtbl (name varchar2(50), id number(10,2));

insert into testtbl values ('abc', '123');
insert into testtbl values ('test', '200');

When I try to update the column using case statement I am getting this error. I can use to_number or remove the quotes to avoid this error but wanted to understand why it happens with quotes when the column given in the else statement is number itself. Doesn't implicit conversion exist in Oracle?

update testtbl
set id = case when name = 'abc' then '5000' else id end;


问:
Fullcalendar 4 not working today in a custom buttom
I have a custom button that i want to go today day.

```<code> customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          calendar.fullCalendar('today');
        }
      }
    }
</code>```

But my error is a fullCalendar('today') dont exist on v4. I can do this the other way

答:
I did the following is not the best but it works for me</p>

```<code>customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          location.href="http://localhost:8888/Proyecto/calendario-plantillas";
        }
      }
    },
</code>```

Body:
I have a custom button that i want to go today day.

 customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          calendar.fullCalendar('today');
        }
      }
    }

But my error is a fullCalendar('today') dont exist on v4. I can do this the other way

Body:
I did the following is not the best but it works for me

customButtons: {
      myCustomButton: {
        text: 'Día Actual',
        click: function(info) {
          location.href="http://localhost:8888/Proyecto/calendario-plantillas";
        }
      }
    },


问:
FirebaseRemoteConfig fetchAndActivate not updating new value
I have already set the minimum interval to be 0 when in Debug mode.
Currently what I do to fetch new data is by clearing the app storage first before launching the app.

Here is my code:

```<code>private fun initRemoteConfig() {
    remoteConfig = FirebaseRemoteConfig.getInstance()
    configSettings = FirebaseRemoteConfigSettings.Builder()
        .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
        .build()
    remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
    fetch()
}

private fun fetch() {
    remoteConfig.fetchAndActivate()
        .addOnCompleteListener {
            if (it.isSuccessful) {
                val updated = it.result
                Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false

                checkVersion()
            } else {
                Logger.d(TAG, "Fetch failed")
            }
        }

}
</code>```

答:
I changed my code from fetchAndActivate to fetch and it seems to be working as expected. I am now getting new data from the Firebase.

Here is my updated code:

```<code>private fun fetch() {
    val fetch = remoteConfig.fetch(if (BuildConfig.DEBUG) 0 else TimeUnit.HOURS.toSeconds(12))
    fetch.addOnCompleteListener {
        if (it.isSuccessful) {
            remoteConfig.activate()
            Logger.d(TAG, "Fetch and activate succeeded")

            checkVersion()
        } else {
            Logger.d(TAG, "Fetch failed")
        }
    }
}
</code>```

Body:
I have already set the minimum interval to be 0 when in Debug mode.
Currently what I do to fetch new data is by clearing the app storage first before launching the app.

Here is my code:

private fun initRemoteConfig() {
    remoteConfig = FirebaseRemoteConfig.getInstance()
    configSettings = FirebaseRemoteConfigSettings.Builder()
        .setMinimumFetchIntervalInSeconds(if (BuildConfig.DEBUG) 0 else 3600)
        .build()
    remoteConfig.setDefaultsAsync(R.xml.remote_config_defaults)
    fetch()
}

private fun fetch() {
    remoteConfig.fetchAndActivate()
        .addOnCompleteListener {
            if (it.isSuccessful) {
                val updated = it.result
                Logger.d(TAG, "Config params updated: $updated. Fetch and activate succeeded") // updated = false

                checkVersion()
            } else {
                Logger.d(TAG, "Fetch failed")
            }
        }

}

Body:
I changed my code from fetchAndActivate to fetch and it seems to be working as expected. I am now getting new data from the Firebase.

Here is my updated code:

private fun fetch() {
    val fetch = remoteConfig.fetch(if (BuildConfig.DEBUG) 0 else TimeUnit.HOURS.toSeconds(12))
    fetch.addOnCompleteListener {
        if (it.isSuccessful) {
            remoteConfig.activate()
            Logger.d(TAG, "Fetch and activate succeeded")

            checkVersion()
        } else {
            Logger.d(TAG, "Fetch failed")
        }
    }
}


问:
Checking a CSV for the existence of a similar value in Python
Consider the following CSV:

```<code>date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00
</code>```

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

```<code>16/02/2020,march contract,51.00
17/02/2020,april contract,240.00
</code>```

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])
```

答:
You can also use itertools.groupby and sum() for this if you don't mind outputting in sorted form.

```<code>from datetime import datetime
from itertools import groupby
import csv

with open(report_file, 'r') as f:
    reader = csv.reader(f)
    lst = list(reader)[1:]

    sorted_input = sorted(lst, key=lambda x : (x[1], datetime.strptime(x[0],'%d/%m/%Y')))  #sort by description and date
    groups = groupby(sorted_input, key=lambda x : x[1])
    for k,g in groups:
        rows = list(g)
        total = sum(float(row[2]) for row in rows)
        print(f'{rows[-1][0]},{k},{total}')  #print last date, description, total
</code>```

Output:

```<code>17/02/2020,april contract,240.0
16/02/2020,march contract,51.0
</code>```

Body:
Consider the following CSV:

date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

16/02/2020,march contract,51.00
17/02/2020,april contract,240.00

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])

Body:
You can also use itertools.groupby and sum() for this if you don't mind outputting in sorted form.

from datetime import datetime
from itertools import groupby
import csv

with open(report_file, 'r') as f:
    reader = csv.reader(f)
    lst = list(reader)[1:]

    sorted_input = sorted(lst, key=lambda x : (x[1], datetime.strptime(x[0],'%d/%m/%Y')))  #sort by description and date
    groups = groupby(sorted_input, key=lambda x : x[1])
    for k,g in groups:
        rows = list(g)
        total = sum(float(row[2]) for row in rows)
        print(f'{rows[-1][0]},{k},{total}')  #print last date, description, total

Output:

17/02/2020,april contract,240.0
16/02/2020,march contract,51.0


问:
Scaffold displaying a bar at the bottom that is not meant to be there
My Scaffold displays a bar at the bottom like this:
that I did not put there (I know that it is the scaffold because when I remove it the bar is gone. but I cant do this without scaffold) this is my code:

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Column(
        children: <Widget>[
          Center(
            child: Text('Scaffold Bar test'),
          ),
          Container(
            height: MediaQuery.of(context).size.height - 88,
            child: ListView.builder(itemBuilder: (BuildContext context,int index) {
              return Container(
                height: 40.0,
                width: MediaQuery.of(context).size.width,
                color: index % 2 == 0 ? Colors.blue : Colors.orange,
              );
            }),
          ),
        ],
      ),
    );
  }
}
</code>```

答:
Set resizeToAvoidBottomPadding: false in the Scaffold.

And use MediaQuery.removePadding with removeTop: true to remove unnecessary padding at top of the ListView.builder.

Use Expanded instead of getting height from MediaQuery.

```<code>class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: Scaffold(
        backgroundColor: Colors.red,
        resizeToAvoidBottomPadding: false,
        body: Column(
          children: <Widget>[
            Center(
              child: Text('Scaffold Bar test'),
            ),
            Expanded(
              child: ListView.builder(itemBuilder: (BuildContext context,int index) {
                return Container(
                  height: 40.0,
                  width: MediaQuery.of(context).size.width,
                  color: index % 2 == 0 ? Colors.blue : Colors.orange,
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
My Scaffold displays a bar at the bottom like this:
that I did not put there (I know that it is the scaffold because when I remove it the bar is gone. but I cant do this without scaffold) this is my code:

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Column(
        children: <Widget>[
          Center(
            child: Text('Scaffold Bar test'),
          ),
          Container(
            height: MediaQuery.of(context).size.height - 88,
            child: ListView.builder(itemBuilder: (BuildContext context,int index) {
              return Container(
                height: 40.0,
                width: MediaQuery.of(context).size.width,
                color: index % 2 == 0 ? Colors.blue : Colors.orange,
              );
            }),
          ),
        ],
      ),
    );
  }
}

Body:
Set resizeToAvoidBottomPadding: false in the Scaffold.

And use MediaQuery.removePadding with removeTop: true to remove unnecessary padding at top of the ListView.builder.

Use Expanded instead of getting height from MediaQuery.

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: Scaffold(
        backgroundColor: Colors.red,
        resizeToAvoidBottomPadding: false,
        body: Column(
          children: <Widget>[
            Center(
              child: Text('Scaffold Bar test'),
            ),
            Expanded(
              child: ListView.builder(itemBuilder: (BuildContext context,int index) {
                return Container(
                  height: 40.0,
                  width: MediaQuery.of(context).size.width,
                  color: index % 2 == 0 ? Colors.blue : Colors.orange,
                );
              }),
            ),
          ],
        ),
      ),
    );
  }
}


问:
Determine if IDP initiated or SP initiated in SP callback?
I am using passport-saml authentication module in my node application.  In the registered IDP callback function that resides in my SP I need to determine if the callback was SP initiated or IDP initiated.

Does SAML have something in the request url, headers, etc that I can use in my SP to determine who initiated the flow?

答: If SP-initiated SSO flow was used, the SAML response has an attribute InResponseTo. This must be checked against the value of the ID attribute of the related SAML AuthnRequest.


问:
Vue CLI 3 PWA deploying to Production Netlify gives Workbox Error: bad-precaching-response ..._redirects?__WB_REVISION__...404
This issue only happens in production on Netlify. It doesn't present itself in the development environment.
Usually, I lurk and search to find the answer, or put something together from related answers, but this one has me so stumped...

I've got a Vue CLI project I've had running on Netlify, set up with a PWA that has been running deployed in the past.
The service worker should be running and the app can be installed for use offline.

Now it's giving me this error in the console:

```<code>Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"https://<domain>/_redirects?__WB_REVISION__=d38a2b58df330c85e0029eecf71d7c26","status":404}]
    at l.o (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1749)
    at async Promise.all (index 0)
    at async l.install (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1221)
</code>```

So it seems to be kicking my '_redirects' file out with a 404 when workbox does it's thing.

I have tried changing the _redirects over to a netlify.toml file with the redirect content in the correct format in the .toml file and it still fails, it's the same error message just with 'netlify.toml' replacing '_redirects' in the error.

I have also tried deploying the same code base to a new Netlify build (thinking it might have been a cache issue with their resources) but the issue persists.

I' guessing that maybe it's an issue with Workbox either failing to compile the assets or giving the wrong name to the files related to redirects. But this also doesn't make sense because they should both be handled by the same code hosted on cdn when I run the build command locally and in the Netlify production environment.

here's the chunk of code that's sending the error from workbox:

```<code>    const isValidResponse = cacheWillUpdateCallback ?
      // Use a callback if provided. It returns a truthy value if valid.
      cacheWillUpdateCallback({event, request, response}) :
      // Otherwise, default to considering any response status under 400 valid.
      // This includes, by default, considering opaque responses valid.
      response.status < 400;

    // Consider this a failure, leading to the `install` handler failing, if
    // we get back an invalid response.
    if (!isValidResponse) {
      throw new WorkboxError('bad-precaching-response', {
        url,
        status: response.status,
      });
    }
</code>```

Here's my package.json:

```<code>{
  "name": "<app-name>",
  "version": "0.2.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "capacitor-copy": "vue-cli-service capacitor-copy",
    "capacitor-init": "vue-cli-service capacitor-init",
    "capacitor-open": "vue-cli-service capacitor-open",
    "capacitor-update": "vue-cli-service capacitor-update",
    "css:build": "postcss src/css/styles.css -o public/styles.css"
  },
  "dependencies": {
    "@capacitor/cli": "^1.0.0-alpha.38",
    "@capacitor/core": "^1.0.0-alpha.38",
    "@fullhuman/postcss-purgecss": "^1.3.0",
    "axios": "^0.19.1",
    "core-js": "^3.4.4",
    "moment": "^2.24.0",
    "postcss": "^7.0.26",
    "postcss-cli": "^6.1.3",
    "register-service-worker": "^1.6.2",
    "tailwindcss": "^1.1.4",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3",
    "vue-uuid": "^1.1.1",
    "vuex": "^3.1.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.2.2",
    "@vue/cli-plugin-eslint": "^4.2.2",
    "@vue/cli-plugin-pwa": "^4.2.0",
    "@vue/cli-plugin-router": "^4.2.2",
    "@vue/cli-plugin-vuex": "^4.2.2",
    "@vue/cli-service": "^4.1.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "vue-cli-plugin-pwa": "^1.0.0-alpha.1",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}
</code>```

and my manifest.json file:

```<code>{
    "short_name": "<name>",
    "name": "<name>",
    "description": "I have no idea what I'm doing with these build tools.",
    "icons": [
        {
            "src": "./img/icons/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "./img/icons/android-chrome-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        },
        {
            "src": "./img/icons/apple-touch-icon-152x152.png",
            "sizes": "152x152",
            "type": "image/png"
        },
        {
            "src": "./img/icons/favicon-16x16.png",
            "sizes": "16x16",
            "type": "image/png"
        },
        {
            "src": "./img/icons/favicon-32x32.png",
            "sizes": "32x32",
            "type": "image/png"
        },
        {
            "src": "./img/icons/msapplication-icon-144x144.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "./img/icons/safari-pinned-tab.png",
            "sizes": "144x144",
            "type": "image/png"
        }
    ],
    "start_url": ".",
    "background_color": "#2d3748",
    "display": "standalone",
    "scope": "/",
    "theme_color": "#2d3748"
}
</code>```

and the index.html file might help, too:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="theme-color" content="#2d3748"/>
    <link rel="manifest" href="manifest.json">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <link rel="stylesheet" href="<%= BASE_URL %>styles.css">
    <title>NAME</title>
  </head>
  <body>
    <noscript>
      <strong>This app doesn't work at all without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>
</code>```

I don't think it's an issue with my code base, to be honest. I think it will be an issue with configuring the workbox that generates the dynamic URLs when it's deployed to netlfiy.
As mentioned, the 'npm run build' script has no problem with the build on my local machine.
I'd love to know if anyone has come across this kind of error with netlify or workbox recently.

I'd be very grateful for any assistance.

答:
I've found the issue:
Here's my thinking as I was testing it, was posted elsewhere, too:

I need the _redirects file in the published build directory, but I want to exclude it from the generated manifest that the service worker uses to filter traffic to local or internet assets.
So I’m going to try to specify an exclusion for _redirects

Try:
Change my vue.config.js (a proxy for webpack.config in vue CLI projects) from this:

```<code>module.exports = {
    devServer: {
        host: 'lite.bdfi.test'
    },
    pwa: {
        name: 'BDFI',
        themeColor: '#2d3748',
        msTileColor: '#2d3748',
        appleMobileWebAppCapable: 'no',
        appleMobileWebAppStatusBarStyle: 'default',
        manifestPath: 'manifest.json',
        workboxPluginMode: 'GenerateSW'

    }
}
</code>```

To this:

```<code>module.exports = {
    devServer: {
        host: 'lite.bdfi.test'
    },
    pwa: {
        name: 'BDFI',
        themeColor: '#2d3748',
        msTileColor: '#2d3748',
        appleMobileWebAppCapable: 'no',
        appleMobileWebAppStatusBarStyle: 'default',
        manifestPath: 'manifest.json',
        workboxPluginMode: 'InjectManifest',
        workboxOptions: {
            // swSrc is required in InjectManifest mode.
            swSrc: 'service-worker.js',
            // ...other Workbox options...
            exclude: [/_redirects/],
        }
    }
}
</code>```

This means that I’m now specifying the input for the service worker, so I need to get a service worker from somewhere.
Here’s my service worker (it’s just a stripped-out version of the autogenerated one)

```<code>workbox.core.setCacheNameDetails({prefix: "lite-bdfi-app"});

self.addEventListener('message', (event) => {

  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
</code>```

After build it’s the same with the injected manifest and workbox scripts:

```<code>importScripts("/precache-manifest.54b556dfe16cf1359c2f3257fa76ade9.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
</code>```

And also, the local ‘dist’ directory confirms that the ‘_redirects’ file is omitted.

Now I run this build in local and fire it up in the local server, now it’s throwing different errors. in local, which has never happened before…

```<code>PrecacheController.mjs:194 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://127.0.0.1:8887/css/app.159bf243.css.map?__WB_REVISION__=b04e3357da21d1241e39","status":404}]
    at l.o (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1749)
    at async Promise.all (index 0)
    at async l.install (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1221)
n @ WorkboxError.mjs:30
o @ PrecacheController.mjs:194
</code>```

Looks familiar, and there are now 5 of them, all looking for files with a .map extension…
Now I’ll remove .map files from the manifest build and see what that does:

```<code>workboxOptions: {
            // swSrc is required in InjectManifest mode.
            swSrc: 'service-worker.js',
            // ...other Workbox options...
            exclude: [/\.map$/, /_redirects/], //this fixed it.
        }
</code>```

Run build again, check dist folder manifest, no .map files included in the manifest.
Then check the local version of the app with cleared cache and local storage. no errors there… seems promising.
Push to GitHub. Netlify build triggers, not auto-published, so visit staging link.
No more errors on page load looking for _redirects file.
Check the redirect for ‘/invalid-url’ and it diverts to the 404 pages as intended.
Publishing the deployment, I can now install the app as a PWA on my desktop.

Issue resolved for me.
I hope this helps someone with the same problem in the future.

Body:
This issue only happens in production on Netlify. It doesn't present itself in the development environment.
Usually, I lurk and search to find the answer, or put something together from related answers, but this one has me so stumped...

I've got a Vue CLI project I've had running on Netlify, set up with a PWA that has been running deployed in the past.
The service worker should be running and the app can be installed for use offline.

Now it's giving me this error in the console:

Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"https://<domain>/_redirects?__WB_REVISION__=d38a2b58df330c85e0029eecf71d7c26","status":404}]
    at l.o (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1749)
    at async Promise.all (index 0)
    at async l.install (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1221)

So it seems to be kicking my '_redirects' file out with a 404 when workbox does it's thing.

I have tried changing the _redirects over to a netlify.toml file with the redirect content in the correct format in the .toml file and it still fails, it's the same error message just with 'netlify.toml' replacing '_redirects' in the error.

I have also tried deploying the same code base to a new Netlify build (thinking it might have been a cache issue with their resources) but the issue persists.

I' guessing that maybe it's an issue with Workbox either failing to compile the assets or giving the wrong name to the files related to redirects. But this also doesn't make sense because they should both be handled by the same code hosted on cdn when I run the build command locally and in the Netlify production environment.

here's the chunk of code that's sending the error from workbox:

    const isValidResponse = cacheWillUpdateCallback ?
      // Use a callback if provided. It returns a truthy value if valid.
      cacheWillUpdateCallback({event, request, response}) :
      // Otherwise, default to considering any response status under 400 valid.
      // This includes, by default, considering opaque responses valid.
      response.status < 400;

    // Consider this a failure, leading to the `install` handler failing, if
    // we get back an invalid response.
    if (!isValidResponse) {
      throw new WorkboxError('bad-precaching-response', {
        url,
        status: response.status,
      });
    }

Here's my package.json:

{
  "name": "<app-name>",
  "version": "0.2.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "capacitor-copy": "vue-cli-service capacitor-copy",
    "capacitor-init": "vue-cli-service capacitor-init",
    "capacitor-open": "vue-cli-service capacitor-open",
    "capacitor-update": "vue-cli-service capacitor-update",
    "css:build": "postcss src/css/styles.css -o public/styles.css"
  },
  "dependencies": {
    "@capacitor/cli": "^1.0.0-alpha.38",
    "@capacitor/core": "^1.0.0-alpha.38",
    "@fullhuman/postcss-purgecss": "^1.3.0",
    "axios": "^0.19.1",
    "core-js": "^3.4.4",
    "moment": "^2.24.0",
    "postcss": "^7.0.26",
    "postcss-cli": "^6.1.3",
    "register-service-worker": "^1.6.2",
    "tailwindcss": "^1.1.4",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3",
    "vue-uuid": "^1.1.1",
    "vuex": "^3.1.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.2.2",
    "@vue/cli-plugin-eslint": "^4.2.2",
    "@vue/cli-plugin-pwa": "^4.2.0",
    "@vue/cli-plugin-router": "^4.2.2",
    "@vue/cli-plugin-vuex": "^4.2.2",
    "@vue/cli-service": "^4.1.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "vue-cli-plugin-pwa": "^1.0.0-alpha.1",
    "vue-template-compiler": "^2.6.10"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions"
  ]
}

and my manifest.json file:

{
    "short_name": "<name>",
    "name": "<name>",
    "description": "I have no idea what I'm doing with these build tools.",
    "icons": [
        {
            "src": "./img/icons/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "./img/icons/android-chrome-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        },
        {
            "src": "./img/icons/apple-touch-icon-152x152.png",
            "sizes": "152x152",
            "type": "image/png"
        },
        {
            "src": "./img/icons/favicon-16x16.png",
            "sizes": "16x16",
            "type": "image/png"
        },
        {
            "src": "./img/icons/favicon-32x32.png",
            "sizes": "32x32",
            "type": "image/png"
        },
        {
            "src": "./img/icons/msapplication-icon-144x144.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "./img/icons/safari-pinned-tab.png",
            "sizes": "144x144",
            "type": "image/png"
        }
    ],
    "start_url": ".",
    "background_color": "#2d3748",
    "display": "standalone",
    "scope": "/",
    "theme_color": "#2d3748"
}

and the index.html file might help, too:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="theme-color" content="#2d3748"/>
    <link rel="manifest" href="manifest.json">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <link rel="stylesheet" href="<%= BASE_URL %>styles.css">
    <title>NAME</title>

      This app doesn't work at all without JavaScript enabled. Please enable it to continue.

I don't think it's an issue with my code base, to be honest. I think it will be an issue with configuring the workbox that generates the dynamic URLs when it's deployed to netlfiy.
As mentioned, the 'npm run build' script has no problem with the build on my local machine.
I'd love to know if anyone has come across this kind of error with netlify or workbox recently.

I'd be very grateful for any assistance.

Body:
I've found the issue:
Here's my thinking as I was testing it, was posted elsewhere, too:

I need the _redirects file in the published build directory, but I want to exclude it from the generated manifest that the service worker uses to filter traffic to local or internet assets.
So I’m going to try to specify an exclusion for _redirects

Try:
Change my vue.config.js (a proxy for webpack.config in vue CLI projects) from this:

module.exports = {
    devServer: {
        host: 'lite.bdfi.test'
    },
    pwa: {
        name: 'BDFI',
        themeColor: '#2d3748',
        msTileColor: '#2d3748',
        appleMobileWebAppCapable: 'no',
        appleMobileWebAppStatusBarStyle: 'default',
        manifestPath: 'manifest.json',
        workboxPluginMode: 'GenerateSW'

    }
}

To this:

module.exports = {
    devServer: {
        host: 'lite.bdfi.test'
    },
    pwa: {
        name: 'BDFI',
        themeColor: '#2d3748',
        msTileColor: '#2d3748',
        appleMobileWebAppCapable: 'no',
        appleMobileWebAppStatusBarStyle: 'default',
        manifestPath: 'manifest.json',
        workboxPluginMode: 'InjectManifest',
        workboxOptions: {
            // swSrc is required in InjectManifest mode.
            swSrc: 'service-worker.js',
            // ...other Workbox options...
            exclude: [/_redirects/],
        }
    }
}

This means that I’m now specifying the input for the service worker, so I need to get a service worker from somewhere.
Here’s my service worker (it’s just a stripped-out version of the autogenerated one)

workbox.core.setCacheNameDetails({prefix: "lite-bdfi-app"});

self.addEventListener('message', (event) => {

  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

After build it’s the same with the injected manifest and workbox scripts:

importScripts("/precache-manifest.54b556dfe16cf1359c2f3257fa76ade9.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");

And also, the local ‘dist’ directory confirms that the ‘_redirects’ file is omitted.

Now I run this build in local and fire it up in the local server, now it’s throwing different errors. in local, which has never happened before…

PrecacheController.mjs:194 Uncaught (in promise) bad-precaching-response: bad-precaching-response :: [{"url":"http://127.0.0.1:8887/css/app.159bf243.css.map?__WB_REVISION__=b04e3357da21d1241e39","status":404}]
    at l.o (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1749)
    at async Promise.all (index 0)
    at async l.install (https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-precaching.prod.js:1:1221)
n @ WorkboxError.mjs:30
o @ PrecacheController.mjs:194

Looks familiar, and there are now 5 of them, all looking for files with a .map extension…
Now I’ll remove .map files from the manifest build and see what that does:

workboxOptions: {
            // swSrc is required in InjectManifest mode.
            swSrc: 'service-worker.js',
            // ...other Workbox options...
            exclude: [/\.map$/, /_redirects/], //this fixed it.
        }

Run build again, check dist folder manifest, no .map files included in the manifest.
Then check the local version of the app with cleared cache and local storage. no errors there… seems promising.
Push to GitHub. Netlify build triggers, not auto-published, so visit staging link.
No more errors on page load looking for _redirects file.
Check the redirect for ‘/invalid-url’ and it diverts to the 404 pages as intended.
Publishing the deployment, I can now install the app as a PWA on my desktop.

Issue resolved for me.
I hope this helps someone with the same problem in the future.


问:
Object object error, when trying to get a specific attribute from my Model
For each item on my database I need to show a specific property. However, when I run my project were it was supposed to show the content of said property, it shows Object object. I've already tried

```<code> console.log(ocorrencia.azimute)
</code>```

and

```<code> JSON.stringify(ocorrencia.azimute)
</code>```

Here is my code:

```<code> $.get("/api/IgnicoesAPI", function (data) {

        $.each(data, function (i, item) {

            var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                '<div id="siteNotice">' +
                '</div>' +
                '<div id="bodyContent">' +
                '<p><b>Avaliação da Ocorrência:</b></p>' +
                // iterar todas as ocorrencias para tirar delas as imagens

                $.each(item.listaOcorrencias, function (o, ocorrencia) {

                    //ERROR - Object object
                    '<p>Azimute:' + ocorrencia.azimute + '</p>'

                });

                +'<p></p>' +

            //MORE CODE
            //...

            $('#json map').append(marker);

        });
    });
</code>```

It's important to poiny out that my item.listaOcorrencias references an attrbute on my model called ListaOcorrencias, which is a list of data from another model. Here is the model:

public class Ignicoes
    {

```<code>    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();

    }

  //Other attributes

    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }

}
</code>```

答:
Here is a working demo:

1.Model:

```<code>public class Ignicoes
{
    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();
    }
    public int Id { get; set; }
    public string Ign { get; set; }
    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
public class Ocorrencias
{
    public int Id { get; set; }
    public string Azimute { get; set; }
}
</code>```

2.View:

```<code><div id="json">
</div>
@section Scripts
{
    <script>
        $.get("/api/IgnicoesAPI", function (data) {
            $.each(data, function (i, item) {
                console.log(item);
                var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<div id="bodyContent">' +
                    '<p><b>Avaliação da Ocorrência:</b></p>' +
                    '</div>' +
                    '<div id="' + i + '">' +
                    '</div>';

                $('#json').append(infowindow);

                $.each(item.listaOcorrencias, function (o, ocorrencia) {
                    console.log(ocorrencia.azimute)

                    $("#" + i).append('<p>Azimute:' + ocorrencia.azimute + '</p>');
                });
            });
        });
    </script>
}
</code>```

3.Controller:

```<code>public ActionResult<List<Ignicoes>> IgnicoesAPI()
{
    var model = new List<Ignicoes>()
    {
        new Ignicoes(){
            Id=1,Ign="I1",
            ListaOcorrencias = new List<Ocorrencias>(){
                new Ocorrencias() { Id=1,Azimute="O1" },
                new Ocorrencias() { Id=2,Azimute="O2" }
            } },
        new Ignicoes(){
            Id=1,Ign="I2",
            ListaOcorrencias = new List<Ocorrencias>(){
                new Ocorrencias() { Id=3,Azimute="O3" },
                new Ocorrencias() { Id=4,Azimute="O4" },
                new Ocorrencias() { Id=5,Azimute="O5" }
            } },
    };
    return model;
}
</code>```

4.Result:

Body:
For each item on my database I need to show a specific property. However, when I run my project were it was supposed to show the content of said property, it shows Object object. I've already tried

 console.log(ocorrencia.azimute)

and

 JSON.stringify(ocorrencia.azimute)

Here is my code:

 $.get("/api/IgnicoesAPI", function (data) {

        $.each(data, function (i, item) {

            var infowindow = '
' +
                '
' +
                '
' +
                '
' +
                '
Avaliação da Ocorrência:
' +
                // iterar todas as ocorrencias para tirar delas as imagens

                $.each(item.listaOcorrencias, function (o, ocorrencia) {

                    //ERROR - Object object
                    '
Azimute:' + ocorrencia.azimute + '
'

                });

                +'

' +

            //MORE CODE
            //...

            $('#json map').append(marker);

        });
    });

It's important to poiny out that my item.listaOcorrencias references an attrbute on my model called ListaOcorrencias, which is a list of data from another model. Here is the model:

public class Ignicoes
    {

    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();

    }

  //Other attributes

    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }

}

Body:
Here is a working demo:

1.Model:

public class Ignicoes
{
    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();
    }
    public int Id { get; set; }
    public string Ign { get; set; }
    public virtual ICollection<Ocorrencias> ListaOcorrencias { get; set; }
}
public class Ocorrencias
{
    public int Id { get; set; }
    public string Azimute { get; set; }
}

2.View:

<div id="json">
</div>
@section Scripts
{
    <script>
        $.get("/api/IgnicoesAPI", function (data) {
            $.each(data, function (i, item) {
                console.log(item);
                var infowindow = '<div id="content" style="hight:700px; width:500px">' +
                    '<div id="siteNotice">' +
                    '</div>' +
                    '<div id="bodyContent">' +
                    '<p><b>Avaliação da Ocorrência:</b></p>' +
                    '</div>' +
                    '<div id="' + i + '">' +
                    '</div>';

                $('#json').append(infowindow);

                $.each(item.listaOcorrencias, function (o, ocorrencia) {
                    console.log(ocorrencia.azimute)

                    $("#" + i).append('<p>Azimute:' + ocorrencia.azimute + '</p>');
                });
            });
        });
    </script>
}

3.Controller:

public ActionResult<List<Ignicoes>> IgnicoesAPI()
{
    var model = new List<Ignicoes>()
    {
        new Ignicoes(){
            Id=1,Ign="I1",
            ListaOcorrencias = new List<Ocorrencias>(){
                new Ocorrencias() { Id=1,Azimute="O1" },
                new Ocorrencias() { Id=2,Azimute="O2" }
            } },
        new Ignicoes(){
            Id=1,Ign="I2",
            ListaOcorrencias = new List<Ocorrencias>(){
                new Ocorrencias() { Id=3,Azimute="O3" },
                new Ocorrencias() { Id=4,Azimute="O4" },
                new Ocorrencias() { Id=5,Azimute="O5" }
            } },
    };
    return model;
}

4.Result:


问:
How to send image with text to printer using IPP protocol
I have a program where I am sending command to the printer using IPP protocol from a node.js server. I am using here

var ipAddress='127.0.0.1';
var Printer = ipp.Printer("http://".concat(ipAddress).concat("/ipp/print"));
var dt = "";
dt = dt.concat("SINCOS Vending Machine Demo.\n\r", "Contact:       ", phone, "\n\rProduct:       ", product, "\n\rQuantity:      ", quantity, "\n\rPrice:         ", price, "\n\r");
var buffer1 = new Buffer(dt, 'utf8');
var msg = {
  "operation-attributes-tag": {
  "requesting-user-name": "John Doe"
  },
  "job-attributes-tag": {
    "media": "na_letter_8.5x11in"
  },
  data: buffer1
};
Printer.execute("Print-Job", msg, function (err, suc) {
  return res.send({error: false, message: suc});
});```

Here I need to add a barcode or an image that also will be printed in the same document. How can I do it?

答:
Usually IPP only takes care of the job submission as in sending a document (in a format supported by the printer) to the printer. IPP by no means provides a rendering engine for application documents.

What document-format do you intend to use or does your printer support? It looks like simple text and graphics should to the job but could require to implement printers specific control codes. If you use PDF or Postscript you should find plenty of libraries and tools that are able to produce/render the required document format for your printer.

Example: If your printer supports postscript you could use a barcode Postscript library.

for implementation ideas see also:

https://github.com/lindell/JsBarcode

https://github.com/MrRio/jsPDF

Body:
I have a program where I am sending command to the printer using IPP protocol from a node.js server. I am using here

var ipAddress='127.0.0.1';
var Printer = ipp.Printer("http://".concat(ipAddress).concat("/ipp/print"));
var dt = "";
dt = dt.concat("SINCOS Vending Machine Demo.\n\r", "Contact:       ", phone, "\n\rProduct:       ", product, "\n\rQuantity:      ", quantity, "\n\rPrice:         ", price, "\n\r");
var buffer1 = new Buffer(dt, 'utf8');
var msg = {
  "operation-attributes-tag": {
  "requesting-user-name": "John Doe"
  },
  "job-attributes-tag": {
    "media": "na_letter_8.5x11in"
  },
  data: buffer1
};
Printer.execute("Print-Job", msg, function (err, suc) {
  return res.send({error: false, message: suc});
});

Here I need to add a barcode or an image that also will be printed in the same document. How can I do it?


问:
Separate string in cluster strings of repeated values in same order as they appear in original string
I have a string with two characters. I need to separate the string into little clusters of the characters when they are grouped together.
Let's say my string is
"xxxxxxxxyyxyxxxxyyyyyxyxxxxyyyyyyyxyyxyyyyyxyyyxxxyyyyxyyy"

I need now an array, a list, whatever that reads like:
[["xxxxxxxx"],["yy"],["x"],["y"],["xxxx"],["yyyyy"],["x"],["y"],["xxxx"],["yyyyyyy"],["x"],["yy"],["x"],["yyyyy"],["x"],["yyy"],["xxx"],["yyyy"],["x"],["yyy"]]

I need to keep the order, as I would iterate it and then make changes in the clusters accordingly. I just can't find a way to do it.

答:
You can just scan over the string with a single for loop. Just check with the previous character. If they are same, continue, else add the previous substring to result. You can make use of a pointer variable, say start which denotes from where the previous substring starts. Below code also works for any kind of chars other than just x and y.

Snippet:

```<code>import java.util.*;
public class Main{
    public static void main(String[] args) {
        String s = "xxxxxxxxyyxyxxxxyyyyyxyxxxxyyyyyyyxyyxyyyyyxyyyxxxyyyyxyyy";
        List<String> res = new ArrayList<>();
        int start = 0;
        for(int i=1;i<s.length();++i){
            if(s.charAt(i) != s.charAt(i-1)){
                res.add(s.substring(start,i));
                start = i;
            }
        }
        res.add(s.substring(start,s.length())); // to add last unadded substring of same characters
        System.out.println(res.toString());
    }
}
</code>```

Demo: https://onlinegdb.com/SkRqmAQQU

Body:
You can just scan over the string with a single for loop. Just check with the previous character. If they are same, continue, else add the previous substring to result. You can make use of a pointer variable, say start which denotes from where the previous substring starts. Below code also works for any kind of chars other than just x and y.

Snippet:

import java.util.*;
public class Main{
    public static void main(String[] args) {
        String s = "xxxxxxxxyyxyxxxxyyyyyxyxxxxyyyyyyyxyyxyyyyyxyyyxxxyyyyxyyy";
        List<String> res = new ArrayList<>();
        int start = 0;
        for(int i=1;i<s.length();++i){
            if(s.charAt(i) != s.charAt(i-1)){
                res.add(s.substring(start,i));
                start = i;
            }
        }
        res.add(s.substring(start,s.length())); // to add last unadded substring of same characters
        System.out.println(res.toString());
    }
}

Demo: https://onlinegdb.com/SkRqmAQQU


问:
Separate label from textbox
Is there a way to separate a label from a textbox?

I found that this is supposed to work :

Select the controls

Arrange tab

Remove layout

But the remove layout button is always disabled... Probably cause it's only when you use the tabular or stacked option

Is there any other way to do it, or am I doing something wrong?

Please, don't tell me that I have to copy/paste the label and delete the original one.

Thank you

答: I think I've got the right answer. Select the Label and send click "Send to back" on Arrange Tab. Label will be detached. Now move it anywhere as required.</p>

Title: Separate label from textbox


问:
How to change an instance variable in python using a method?
I'm very new to python and currently practicing OOP. One of the problems I'm facing is how to change an instance variable in python using a method.
My code:

```<code>class Monster:
   def __init__ (self, name, health):
      self.name = name
      self.health = health
   @classmethod
   def change_name (self, given_name):
      self.name = given_name
mon = Monster("Drake", 100)
print(mon.name)
mon.change_name("Derrick")
print(mon.name)
</code>```

Output:

```<code>#Expected:
Drake
Derrick
#Actual:
Drake
Drake
</code>```

Can someone tell me what the problem is and how I can solve it?

答:
It happens because the change_name method is declared as a
classmethod

Which means its self parameter is not the object (instance of the class) but the class, in fact you should rename it to cls to make it clear.

Assigning tbe variable via the class creates it in the class' namespace, not in the object's.

But when looked up via the object, python looks for it in the object's namespace and if it cannot be found,  it looks for it in the class' (and above in the superclasses' if not found yet)

Since you do not seem to need it , as the name attribute belongs to each monster instance, the solution is to make the method a plain instance one by removing the @classmethod decorator.

Body:
I'm very new to python and currently practicing OOP. One of the problems I'm facing is how to change an instance variable in python using a method.
My code:

class Monster:
   def __init__ (self, name, health):
      self.name = name
      self.health = health
   @classmethod
   def change_name (self, given_name):
      self.name = given_name
mon = Monster("Drake", 100)
print(mon.name)
mon.change_name("Derrick")
print(mon.name)

Output:

#Expected:
Drake
Derrick
#Actual:
Drake
Drake

Can someone tell me what the problem is and how I can solve it?


问:
Variable1 value exists in variable2 script
I have a table with sample1 and sample2 Columns. Some of the sample2 values exist in sample 1.
Now I want to extract a table where sample2 value is NOT available in sample1. Please see the tables below for clarification.
Thanks.

答:
You can use NOT EXISTS :

```<code>SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.sample1 = t.sample2);
</code>```

Body:
You can use NOT EXISTS :

SELECT t.*
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.sample1 = t.sample2);


问:
Is there a free GUI tool for data sync between DB in which it is possible to script rules?
What I need to do is some data between 2 databases. The source can be anything (comma separated file, xls file, any database, ...), the destination is MS SQL Server.

I do not need to sync all data, I just need to sync particular tables.

Example:

I need to sync accounting Software (runs on PostgreSQL) CUSTOMERS table with CRM (runs on SQL Server).

Some problems this tool should be able to face:

1) Accounting software customers table has 1 field that is not mapped in crm customers table. (In this way I want to map this extra field to the field CUSTOMERS_CUSTOM_DATA.EXTRA_FIELD)

2) Having some rules (like sync only customers whose code is between 10000 and 99999)

3) Allowing to perform some post insert tasks (for example I am using manually managed seuqences for the tanble IDs, so after inserting 10 records I need to add 10 to the sequence)

4) Having an exception handling mechanism so if something is wrong it can wither call a sql server stored procedure (that I already have and it will send an e-mail to me) or simply send a message to notify that something was wrong in the nightly sync.

5) Be easy to schedule when to perform data sync (hourly, daily, INCLUDING MANUAL)

6) Perform data conversion: if Surname field in source table is varchar(20) and in destination table is varchar(15)  I want to explicitly say "perform a truncation".

7) Have different rules for insert or update. For example in the source e-mail field is not present, but I want to populate it in the destination I decide to perform this operation on insert only, not on update. (for example as I insert a new customer I want to populate the e-mail field concatenating name and surname, but then I want to let the users to modify it, this first insertion is just to simplify data entry, but then this particular case will be handled manually. So I want to say (on insert populate e-mail field, on update don't do anything with email field)

8) In case of delete in the source db don't delete on the destination but only change the varchar(10) STATUS to DELETED.

Note: I know that Integration Services will be perfect for this, but I must support the Express Edition, so SSIS is not an option.

I created a bunch of scripts and scheduled stored procedure that at present do what I need, but it is very hard to maintain and the total lack of a GUI makes the work much slower. I remember having seeing TALEND time ago, maybe that tool is also the answr I need, anyway I need to provide a quick answer to management, so I have now no time to investigate all the tools on the market, and I would prefer to have a suggestion from an expert.

答: I believe SQL Server Integration Services does all that, and I believe SQL Server Management Studio allows you to create and package your SSIS jobs so that they can be deployed elsewhere.</p>

ContentLicense: CC BY-SA 2.5


问:
How to get directly to question page in questionnaire plugins
I am using the questionnaire plugin version 3.5.4 in the moodle version 3.5.10

In that when i open It showing me as links I want the question direct when i open the questionnaire and same for the response after i submit my answer it will show me the response not the thank you page then responses.In admin account it is fine but i am asking for student accounts. Any Suggestions?

答: At this point we can't bypass the links in the questionnaire plugin.</p>


问:
How to (base64) encode a protobuf as a String for REST
I want to use Protobuf objects in REST service.

I need to deserialize incoming string from base64 to a Protobuf object (IMessage)

I need to serialize outgoing Protobuf object to base64 string

What is the simplest way to do that ?

答:
Short version

Serialize:

```<code>using Google.Protobuf; // don't forget: .ToByteString() is an extension method
string encoded = proto.ToByteString().ToBase64();
// Output: ChAKDEdsb2JhbCBzdGF0ZRAB
</code>```

Deserialize:

```<code>MyProtobufClass myC = new MyProtobufClass();
myC .MergeFrom(ByteString.FromBase64(messageBase64));
</code>```

Full version: helper class

```<code>public static class ProtobufHelper
{
    /// <summary>
    /// Transform base64 string message to protobuf IMessage object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="messageBase64"></param>
    /// <returns></returns>
    public static T DeserializeProtobuf<T>(string messageBase64) where T: IMessage, new()
    {
        T result = new T();
        if (!String.IsNullOrWhiteSpace(messageBase64))
        {
            if (messageBase64.StartsWith("\"") && && messageBase64.Length > 2)
                messageBase64 = messageBase64.Substring(1, messageBase64.Length - 2);
            result.MergeFrom(ByteString.FromBase64(messageBase64));
        }
        return (result);
    }

    /// <summary>
    ///  Transform protobuf IMessage object to base64 string message
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public static string SerializeProtobuf(IMessage message)
    {
        return (message.ToByteString().ToBase64());
    }
}
</code>```

Usage in REST service

```<code>  public class MyCustomController : ApiController
  {

        /// <summary>
        /// REST Get method
        /// </summary>
        /// <param name="requestPayload">String containing a base64 serialized MyProtobufRequest object</param>
        /// <returns>String containing a base64 serialized MyProtobufReply object</returns>
        public string Get(string requestPayload)
        {
            var requestObj = ProtobufHelper.DeserializeProtobuf<MyProtobufRequest>(requestPayload);
            return (ProtobufHelper.SerializeProtobuf(GetHandler(requestObj)));
        }

        private MyProtobufReply GetHandler(MyProtobufRequestrequest request)
        {
           // Type your code here
           return new MyProtobufReply();
        }
  }
</code>```

Body:
Short version

Serialize:

using Google.Protobuf; // don't forget: .ToByteString() is an extension method
string encoded = proto.ToByteString().ToBase64();
// Output: ChAKDEdsb2JhbCBzdGF0ZRAB

Deserialize:

MyProtobufClass myC = new MyProtobufClass();
myC .MergeFrom(ByteString.FromBase64(messageBase64));

Full version: helper class

public static class ProtobufHelper
{
    /// <summary>
    /// Transform base64 string message to protobuf IMessage object
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="messageBase64"></param>
    /// <returns></returns>
    public static T DeserializeProtobuf<T>(string messageBase64) where T: IMessage, new()
    {
        T result = new T();
        if (!String.IsNullOrWhiteSpace(messageBase64))
        {
            if (messageBase64.StartsWith("\"") && && messageBase64.Length > 2)
                messageBase64 = messageBase64.Substring(1, messageBase64.Length - 2);
            result.MergeFrom(ByteString.FromBase64(messageBase64));
        }
        return (result);
    }

    /// <summary>
    ///  Transform protobuf IMessage object to base64 string message
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public static string SerializeProtobuf(IMessage message)
    {
        return (message.ToByteString().ToBase64());
    }
}

Usage in REST service

  public class MyCustomController : ApiController
  {

        /// <summary>
        /// REST Get method
        /// </summary>
        /// <param name="requestPayload">String containing a base64 serialized MyProtobufRequest object</param>
        /// <returns>String containing a base64 serialized MyProtobufReply object</returns>
        public string Get(string requestPayload)
        {
            var requestObj = ProtobufHelper.DeserializeProtobuf<MyProtobufRequest>(requestPayload);
            return (ProtobufHelper.SerializeProtobuf(GetHandler(requestObj)));
        }

        private MyProtobufReply GetHandler(MyProtobufRequestrequest request)
        {
           // Type your code here
           return new MyProtobufReply();
        }
  }


问:
How do you force a makefile to rebuild a target?
I have a makefile that builds and then calls another makefile. Since this makefile calls more makefiles that does the work it doesn't really change. Thus it keeps thinking the project is built and up to date.

```<code>dnetdev11 ~ # make
make: `release' is up to date.
</code>```

How do I force the makefile to rebuild the target?

```<code>clean = $(MAKE) -f ~/xxx/xxx_compile.workspace.mak clean

build = svn up ~/xxx                                                       \
        $(clean)                                                                \
        ~/cbp2mak/cbp2mak -C ~/xxx ~/xxx/xxx_compile.workspace        \
        $(MAKE) -f ~/xxx/xxx_compile.workspace.mak $(1)                    \

release:
        $(build )

debug:
        $(build DEBUG=1)

clean:
        $(clean)

install:
        cp ~/xxx/source/xxx_utility/release/xxx_util /usr/local/bin
        cp ~/xxx/source/xxx_utility/release/xxxcore.so /usr/local/lib
</code>```

Note: Names removed to protect the innocent

Final Fixed version:

```<code>clean = $(MAKE) -f xxx_compile.workspace.mak clean;

build = svn up;                                         \
        $(clean)                                        \
        ./cbp2mak/cbp2mak -C . xxx_compile.workspace;   \
        $(MAKE) -f xxx_compile.workspace.mak    $(1);   \

.PHONY: release debug clean install

release:
        $(call build,)

debug:
        $(call build,DEBUG=1)

clean:
        $(clean)

install:
        cp ./source/xxx_utillity/release/xxx_util /usr/bin
        cp ./dlls/Release/xxxcore.so /usr/lib
</code>```

答:
As abernier pointed out, there is a recommended solution in the GNU make manual, which uses a 'fake' target to force rebuilding of a target:

```<code>clean: FORCE
        rm $(objects)
FORCE: ;
</code>```

This will run clean, regardless of any other dependencies.

I added the semicolon to the solution from the manual, otherwise an empty line is required.

Body:
I have a makefile that builds and then calls another makefile. Since this makefile calls more makefiles that does the work it doesn't really change. Thus it keeps thinking the project is built and up to date.

dnetdev11 ~ # make
make: `release' is up to date.

How do I force the makefile to rebuild the target?

clean = $(MAKE) -f ~/xxx/xxx_compile.workspace.mak clean

build = svn up ~/xxx                                                       \
        $(clean)                                                                \
        ~/cbp2mak/cbp2mak -C ~/xxx ~/xxx/xxx_compile.workspace        \
        $(MAKE) -f ~/xxx/xxx_compile.workspace.mak $(1)                    \

release:
        $(build )

debug:
        $(build DEBUG=1)

clean:
        $(clean)

install:
        cp ~/xxx/source/xxx_utility/release/xxx_util /usr/local/bin
        cp ~/xxx/source/xxx_utility/release/xxxcore.so /usr/local/lib

Note: Names removed to protect the innocent

Final Fixed version:

clean = $(MAKE) -f xxx_compile.workspace.mak clean;

build = svn up;                                         \
        $(clean)                                        \
        ./cbp2mak/cbp2mak -C . xxx_compile.workspace;   \
        $(MAKE) -f xxx_compile.workspace.mak    $(1);   \

.PHONY: release debug clean install

release:
        $(call build,)

debug:
        $(call build,DEBUG=1)

clean:
        $(clean)

install:
        cp ./source/xxx_utillity/release/xxx_util /usr/bin
        cp ./dlls/Release/xxxcore.so /usr/lib

Body:
As abernier pointed out, there is a recommended solution in the GNU make manual, which uses a 'fake' target to force rebuilding of a target:

clean: FORCE
        rm $(objects)
FORCE: ;

This will run clean, regardless of any other dependencies.

I added the semicolon to the solution from the manual, otherwise an empty line is required.


问:
Elastic Search Get index API to get indices older than 30 days
we are using elastic-search 5 and i need to delete indices older than 30 days through API.Can any can help me out for this?</p>

答:
You can use curator to do that.

https://www.elastic.co/guide/en/elasticsearch/client/curator/5.x/delete_indices.html

```<code>curator --host <hostname> delete indices --older-than 30
</code>```

Body:
You can use curator to do that.

https://www.elastic.co/guide/en/elasticsearch/client/curator/5.x/delete_indices.html

curator --host <hostname> delete indices --older-than 30


问:
Error while using the readfromexcel component in Intellibot Studio
I am using the readfromexcel component under Data Reader category. I already installed the microsoft.ace.oledb.12.0 and re-tried. However, it gives the same error. Can someone please help me with this?</p>

答:
Please install the

AccessDatabaseEngine 32bit

Note: Before installing this download, you must first remove any previous versions of the Access Database Engine from your computer by using Uninstall a Program in the Control Panel.

Click the link below:
https://www.microsoft.com/en-us/download/details.aspx?id=13255

Select AccessDatabaseEngine.exe

For your reference


问:
Replacing multiple placeholders in a string
I have a string with 2 placeholders, that I want to replace on runtime based on value calculations. what is the best way to do this. I have used the code below for single placeholder replacement,

```<code>   String posttData = @"data = google.visualization.arrayToDataTable([
                                ['Label', 'Value'],
                                ['Result', {0}]
                                ]);
    var options = {
        width: 1200, height: 500, redFrom: 90, redTo: 100, yellowFrom: 75, yellowTo: 90, minorTicks: 5
    };
</code>```

....result calculation

```<code>var x = posttData.Replace("{0}", result.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "test", x, true);
</code>```

How do I do the same for multiple replacements? if I need to add another option,

```<code>var options = {
                   width: 1200, height: 500, redFrom: 90, redTo: 100, yellowFrom: 75, yellowTo: 90, minorTicks: 5, max: {1}
</code>```

答:
I would suggest to use string interpolation:

```<code>$"Some value {1} and some value {2}"
</code>```

where "1" and "2" can be whatever result/expression you need.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Body:
I have a string with 2 placeholders, that I want to replace on runtime based on value calculations. what is the best way to do this. I have used the code below for single placeholder replacement,

   String posttData = @"data = google.visualization.arrayToDataTable([
                                ['Label', 'Value'],
                                ['Result', {0}]
                                ]);
    var options = {
        width: 1200, height: 500, redFrom: 90, redTo: 100, yellowFrom: 75, yellowTo: 90, minorTicks: 5
    };

....result calculation

var x = posttData.Replace("{0}", result.ToString());
ScriptManager.RegisterStartupScript(this, this.GetType(), "test", x, true);

How do I do the same for multiple replacements? if I need to add another option,

var options = {
                   width: 1200, height: 500, redFrom: 90, redTo: 100, yellowFrom: 75, yellowTo: 90, minorTicks: 5, max: {1}

Body:
I would suggest to use string interpolation:

$"Some value {1} and some value {2}"

where "1" and "2" can be whatever result/expression you need.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated


问:
Vue.js: Not Getting CSS Reference of External Component datetimepicker in the dist Folder
I have used an external component datetimepicker in my component and it works fine as shown below when I run the project.

But while building for production as web component to get the min.js files inside dist directory, not getting CSS reference of that external component datetimepicker in the received js files inside the dist directory. It does not render styles of the datetimepicker field. It is displaying like below. Is there any solution for that?

I have executed below command:

```<code>$ npm install vuejs-datetimepicker
</code>```

And used below code for that

```<code><td align="left">
    <datetime format="DD-MM-YYYY h:i:s" width="280px" v-model="dateTime"></datetime>
</td>
</code>```

```<code>import datetime from 'vuejs-datetimepicker';
export default {
  components: {
      datetime
  }
}
</code>```

And I used the command npm run build to build as web component.

Attaching my package file below:

```<code>{
  "name": "ABC",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build --target wc-async --name common-apps
./src/App.vue",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.4",
    "vue": "^2.6.11",
    "vuejs-datetimepicker": "^1.1.13",
    "vuex": "^3.1.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.2.0",
    "@vue/cli-plugin-eslint": "^4.2.0",
"@vue/cli-plugin-unit-jest": "^4.2.0",
"@vue/cli-plugin-vuex": "^4.2.0",
"@vue/cli-service": "^4.2.0",
"@vue/eslint-config-prettier": "^6.0.0",
"@vue/test-utils": "1.0.0-beta.31",
"babel-eslint": "^10.0.3",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-vue": "^6.1.2",
"prettier": "^1.19.1",
"sass": "^1.25.0",
"sass-loader": "^8.0.2",
"vue-template-compiler": "^2.6.11"
  }
}
</code>```

答: I fixed this issue just by executing the command npm install style-loader css-loader --save in the terminal.

Body:
I have used an external component datetimepicker in my component and it works fine as shown below when I run the project.

But while building for production as web component to get the min.js files inside dist directory, not getting CSS reference of that external component datetimepicker in the received js files inside the dist directory. It does not render styles of the datetimepicker field. It is displaying like below. Is there any solution for that?

I have executed below command:

$ npm install vuejs-datetimepicker

And used below code for that

    <datetime format="DD-MM-YYYY h:i:s" width="280px" v-model="dateTime"></datetime>

import datetime from 'vuejs-datetimepicker';
export default {
  components: {
      datetime
  }
}

And I used the command npm run build to build as web component.

Attaching my package file below:

{
  "name": "ABC",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build --target wc-async --name common-apps
./src/App.vue",
    "test:unit": "vue-cli-service test:unit",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.4",
    "vue": "^2.6.11",
    "vuejs-datetimepicker": "^1.1.13",
    "vuex": "^3.1.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^4.2.0",
    "@vue/cli-plugin-eslint": "^4.2.0",
"@vue/cli-plugin-unit-jest": "^4.2.0",
"@vue/cli-plugin-vuex": "^4.2.0",
"@vue/cli-service": "^4.2.0",
"@vue/eslint-config-prettier": "^6.0.0",
"@vue/test-utils": "1.0.0-beta.31",
"babel-eslint": "^10.0.3",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-vue": "^6.1.2",
"prettier": "^1.19.1",
"sass": "^1.25.0",
"sass-loader": "^8.0.2",
"vue-template-compiler": "^2.6.11"
  }
}