问:
willTransition is getting called twice
Goal: prevent transitioning to another route if the current route's model has been changed (i.e. user has updated some fields but not saved, i.e. isDirty === true.

Setup: I'm using pretty much this exact code from EmberJS.com's Routing guide.

```<code>export default Ember.Route.extend({
  actions: {
    willTransition(transition) {
      if (this.controller.get('userHasEnteredData') &&
          !confirm("Are you sure you want to abandon progress?")) {
        transition.abort();
      } else {
        // Bubble the `willTransition` action so that
        // parent routes can decide whether or not to abort.
        return true;
      }
    }
  }
});
</code>```

In my controller, userHasEnteredData is just a computed property that watches the model's isDirty property.

Issue: When I choose to cancel from the confirm box (i.e. "Cancel transitioning so I can finish editing"), then the confirm box pops up again. Canceling again makes it go away for good, but I don't know why it's getting hit twice. If I instead say "ok" in the confirm the first time, it goes ahead and transitions, without popping up the confirm again. It's only when canceling the first time that it pops up immediately again.

I tried to replicate on ember-twiddle.com, but it worked fine there, calling willTransition only once. If it's indeed being called twice in my code, I can't figure out why, since I've checked and double-checked, and there's nothing I can see that's different that would cause the hook to be called again after transition.abort() runs.

Any clues?

EDIT I simplified willTransition even more, to just this, and it still runs twice. It appears that transition.abort() calls willTransition() although that makes no sense!

```<code>actions: {
    willTransition: function(transition) {
      console.log('trying to transition');
      transition.abort();
    }
  }
}
//logs 'trying to transition' to the console twice!
</code>```

答:
For anybody who might be having a similar issue:

I ran into the problem of willTransition being fired twice when calling transition.abort() (in an attempt to handle unsaved changes).

In my case, the issue turned out to be related to the fact that I was returning true from willTransition in either case (whether I was handing unsaved changes, or not). I mistakenly thought that transition.abort() would be enough.

Once I moved the return true; into the else condition for my hasChanges if statement, the problem was solved.

```<code>willTransition(transition) {
    if (this.controller.get(model.hasDirtyAttributes)) {
        // Handle unsaved changes...
        // ...then `transition.retry()`
    } else {
        return true; // <-- this worked
    }

    // return true; <-- this fired `willTransition` twice
}
</code>```

Title: willTransition is getting called twice

Body:
Goal: prevent transitioning to another route if the current route's model has been changed (i.e. user has updated some fields but not saved, i.e. isDirty === true.

Setup: I'm using pretty much this exact code from EmberJS.com's Routing guide.

export default Ember.Route.extend({
  actions: {
    willTransition(transition) {
      if (this.controller.get('userHasEnteredData') &&
          !confirm("Are you sure you want to abandon progress?")) {
        transition.abort();
      } else {
        // Bubble the `willTransition` action so that
        // parent routes can decide whether or not to abort.
        return true;
      }
    }
  }
});

In my controller, userHasEnteredData is just a computed property that watches the model's isDirty property.

Issue: When I choose to cancel from the confirm box (i.e. "Cancel transitioning so I can finish editing"), then the confirm box pops up again. Canceling again makes it go away for good, but I don't know why it's getting hit twice. If I instead say "ok" in the confirm the first time, it goes ahead and transitions, without popping up the confirm again. It's only when canceling the first time that it pops up immediately again.

I tried to replicate on ember-twiddle.com, but it worked fine there, calling willTransition only once. If it's indeed being called twice in my code, I can't figure out why, since I've checked and double-checked, and there's nothing I can see that's different that would cause the hook to be called again after transition.abort() runs.

Any clues?

EDIT I simplified willTransition even more, to just this, and it still runs twice. It appears that transition.abort() calls willTransition() although that makes no sense!

actions: {
    willTransition: function(transition) {
      console.log('trying to transition');
      transition.abort();
    }
  }
}
//logs 'trying to transition' to the console twice!

Body:
For anybody who might be having a similar issue:

I ran into the problem of willTransition being fired twice when calling transition.abort() (in an attempt to handle unsaved changes).

In my case, the issue turned out to be related to the fact that I was returning true from willTransition in either case (whether I was handing unsaved changes, or not). I mistakenly thought that transition.abort() would be enough.

Once I moved the return true; into the else condition for my hasChanges if statement, the problem was solved.

willTransition(transition) {
    if (this.controller.get(model.hasDirtyAttributes)) {
        // Handle unsaved changes...
        // ...then `transition.retry()`
    } else {
        return true; // <-- this worked
    }

    // return true; <-- this fired `willTransition` twice
}


来源: stackexchange

问:
crontab not executing perl script
I'm having issues scheduling a crontab task; I have googled and read tons of pages but can't understand if the solutions given are example specific and they don't seem to fix my issue.

I'm trying to run a basic perl script called perl_speedtest.pl which lives in the /home/pi/Documents/Projects directory on my raspberry pi. When I run the script manually by command: perl perl_speedtest.pl from the above directory it works perfect.

I have scheduled the task to run every 20 minutes with the following crontab job by using the 'crontab -e' command in the terminal:

```<code>*/20 * * * * perl /home/pi/Documents/Projects/perl_speedtest.pl
</code>```

for some reason this doesn't execute.. any ideas? Happy to share more details if needed.

答:
Set your environment in cron correctly as the commenters above point out. Otherise, cron uses a pretty minimal environment (including PATH, PERL5LIB, etc). Your crontab should look something like this, depending on your actual environment as you use it in your interactive shell:

HOME=/home/pi
SHELL=/bin/bash
MAIL=/usr/bin/mail

06 */1 * * * source ~/.bashrc &> /dev/null ; perl /home/pi/Documents/Projects/perl_speedtest.pl

# or this (find the perl path by executing "which perl"):

06 */1 * * * /usr/bin/perl /home/pi/Documents/Projects/perl_speedtest.pl
```

ContentLicense: CC BY-SA 4.0

Title: crontab not executing perl script

Body:
I'm having issues scheduling a crontab task; I have googled and read tons of pages but can't understand if the solutions given are example specific and they don't seem to fix my issue.

I'm trying to run a basic perl script called perl_speedtest.pl which lives in the /home/pi/Documents/Projects directory on my raspberry pi. When I run the script manually by command: perl perl_speedtest.pl from the above directory it works perfect.

I have scheduled the task to run every 20 minutes with the following crontab job by using the 'crontab -e' command in the terminal:

*/20 * * * * perl /home/pi/Documents/Projects/perl_speedtest.pl

for some reason this doesn't execute.. any ideas? Happy to share more details if needed.


问:
glide does'nt load the picture from storage firebase
Glide doesn't load the picture from storage firebase.

Here are the dependencies that I added.

```<code>implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.google.firebase:firebase-storage:16.0.4'
</code>```

And here's the function that I use.

```<code>private void getUserInfo(){
    mCustomerDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("name")!=null){
                    mName = map.get("name").toString();
                    mNameField.setText(mName);
                }
                if(map.get("phone")!=null){
                    mPhone = map.get("phone").toString();
                    mPhoneField.setText(mPhone);
                }
                if(map.get("profileImageUrl")!=null){
                    mProfileImageUrl = map.get("profileImageUrl").toString();
                    Glide.with(getApplication()).load(mProfileImageUrl).into(mProfileImage);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
</code>```

NB: it was work perfectly before I upgrade the Gradle list to androidx

Before registration

After registration

答:
I am not sure if you could actually download the profile image before updating it to androidx. Looks like the image that you have is the default image for that ImageView.

I would actually suggest the following.

Check if you have the INTERNET permission in your AndroidManifest.xml.

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Use the following to add a placeholder image while you are trying to load the images using Glide.

```<code>Glide.with(getApplication())
     .load(mProfileImageUrl)
     .apply(new RequestOptions()
         .placeholder(R.drawable.default_person)
         .fitCenter())
     .into(mProfileImage);
</code>```

Body:
Glide doesn't load the picture from storage firebase.

Here are the dependencies that I added.

implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.google.firebase:firebase-storage:16.0.4'

And here's the function that I use.

private void getUserInfo(){
    mCustomerDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists() && dataSnapshot.getChildrenCount()>0){
                Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
                if(map.get("name")!=null){
                    mName = map.get("name").toString();
                    mNameField.setText(mName);
                }
                if(map.get("phone")!=null){
                    mPhone = map.get("phone").toString();
                    mPhoneField.setText(mPhone);
                }
                if(map.get("profileImageUrl")!=null){
                    mProfileImageUrl = map.get("profileImageUrl").toString();
                    Glide.with(getApplication()).load(mProfileImageUrl).into(mProfileImage);
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

NB: it was work perfectly before I upgrade the Gradle list to androidx

Before registration

After registration

Body:
I am not sure if you could actually download the profile image before updating it to androidx. Looks like the image that you have is the default image for that ImageView.

I would actually suggest the following.

Check if you have the INTERNET permission in your AndroidManifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

Use the following to add a placeholder image while you are trying to load the images using Glide.

Glide.with(getApplication())
     .load(mProfileImageUrl)
     .apply(new RequestOptions()
         .placeholder(R.drawable.default_person)
         .fitCenter())
     .into(mProfileImage);


问:
MassTransit: Additional error raised when consumer has an exception. "The IErrorTransport was not available on the ReceiveContext."
I have some consumers that runs in an Azure Function that has been upgraded to MT 6.0.2 and Azure Functions 3 and core 3. When an error is encountered in the consumer the message is not sent to the error queue and the following error is logged.

The IErrorTransport was not available on the ReceiveContext.

This is my function method. Am I missing something on configuring the receiver?

```<code>        public async Task ExecuteMessageConsumerAsync(
            [ServiceBusTrigger(CoreEndpoint.InputQueue)] Microsoft.Azure.ServiceBus.Message message,
            IBinder binder,
            ILogger log,
            CancellationToken cancellationToken)
        {
            LogContext.ConfigureCurrentLogContext(log);

            LogContext.Info?.Log("Creating brokered message receiver");

            await ContainerContext.ExecuteAsync(scope =>
            {
                var handler = Bus.Factory.CreateBrokeredMessageReceiver(binder, cfg =>
                {
                    cfg.CancellationToken = cancellationToken;
                    cfg.InputAddress = _endpoint.InputQueueAddress;

                    cfg.UseInMemoryOutbox();
                    cfg.UseServiceBusMessageScheduler();
                    cfg.UseMessageRetry(r  =>
                    {
                        r.Intervals(10, 100, 500, 1000);
                        r.Ignore<ApplicationException>();
                    });

                    cfg.ConfigureSend(x => x.UseTenantContext<int>(scope));
                    cfg.ConfigurePublish(x => x.UseTenantContext<int>(scope));

                    // Command consumers
                    cfg.Consumer<EmailCallbackConsumer>(scope, "message", (c, consume) => c.UseTenantContext<int>(consume));
                });

                return handler.Handle(message);
            });
        }
</code>```

After upgrading to 6.1.

```<code> ---> MassTransit.TransportException: sb://no-host-configured/no-queue-specified => The IErrorTransport was not available on the ReceiveContext.
   at MassTransit.Pipeline.Filters.ErrorTransportFilter.GreenPipes.IFilter<MassTransit.ExceptionReceiveContext>.Send(ExceptionReceiveContext context, IPipe`1 next)
   at MassTransit.Pipeline.Filters.GenerateFaultFilter.GreenPipes.IFilter<MassTransit.ExceptionReceiveContext>.Send(ExceptionReceiveContext context, IPipe`1 next)
   at GreenPipes.Filters.RescueFilter`2.GreenPipes.IFilter<TContext>.Send(TContext context, IPipe`1 next)
   at MassTransit.Pipeline.Filters.DeadLetterFilter.GreenPipes.IFilter<MassTransit.ReceiveContext>.Send(ReceiveContext context, IPipe`1 next)
   at MassTransit.Azure.ServiceBus.Core.Transport.BrokeredMessageReceiver.MassTransit.Azure.ServiceBus.Core.Transport.IBrokeredMessageReceiver.Handle(Message message, Action`1 contextCallback)
   at MassTransit.Azure.ServiceBus.Core.Transport.BrokeredMessageReceiver.MassTransit.Azure.ServiceBus.Core.Transport.IBrokeredMessageReceiver.Handle(Message message, Action`1 contextCallback)
   at Symend.Core.App.AzureFunctions.Functions.ExecuteMessageConsumerAsync(Message message, IBinder binder, ILogger log, CancellationToken cancellationToken) in D:\a\1\s\src\Core\Symend.Core.App.AzureFunctions\Functions.cs:line 53
   at Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync(TReflected instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\VoidTaskMethodInvoker.cs:line 20
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 585
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 532
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, IFunctionOutputDefinition outputDefinition, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 468
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 278
   --- End of inner exception stack trace ---
   at Microsoft.Azure.WebJobs.ServiceBus.MessageProcessor.CompleteProcessingMessageAsync(Message message, FunctionResult result, CancellationToken cancellationToken)
   at Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener.ProcessMessageAsync(Message message, CancellationToken cancellationToken)
   at Microsoft.Azure.ServiceBus.MessageReceivePump.MessageDispatchTask(Message message)```
```

答:
When using an Azure Function with the latest -develop packages (which will be released as 6.1), messages that fault will not be moved to an _error queue, and will instead throw an exception so that Azure can move that message to the dead letter queue. There was an issue in 6.0.1, and a subsequent issue in 6.0.2 (related to IDeadLetterTransport).

Try the latest packages (-develop) and let me know if that fixes the issue. Otherwise, there may be yet another bug hiding in there.

Body:
I have some consumers that runs in an Azure Function that has been upgraded to MT 6.0.2 and Azure Functions 3 and core 3. When an error is encountered in the consumer the message is not sent to the error queue and the following error is logged.

The IErrorTransport was not available on the ReceiveContext.

This is my function method. Am I missing something on configuring the receiver?

        public async Task ExecuteMessageConsumerAsync(
            [ServiceBusTrigger(CoreEndpoint.InputQueue)] Microsoft.Azure.ServiceBus.Message message,
            IBinder binder,
            ILogger log,
            CancellationToken cancellationToken)
        {
            LogContext.ConfigureCurrentLogContext(log);

            LogContext.Info?.Log("Creating brokered message receiver");

            await ContainerContext.ExecuteAsync(scope =>
            {
                var handler = Bus.Factory.CreateBrokeredMessageReceiver(binder, cfg =>
                {
                    cfg.CancellationToken = cancellationToken;
                    cfg.InputAddress = _endpoint.InputQueueAddress;

                    cfg.UseInMemoryOutbox();
                    cfg.UseServiceBusMessageScheduler();
                    cfg.UseMessageRetry(r  =>
                    {
                        r.Intervals(10, 100, 500, 1000);
                        r.Ignore<ApplicationException>();
                    });

                    cfg.ConfigureSend(x => x.UseTenantContext<int>(scope));
                    cfg.ConfigurePublish(x => x.UseTenantContext<int>(scope));

                    // Command consumers
                    cfg.Consumer<EmailCallbackConsumer>(scope, "message", (c, consume) => c.UseTenantContext<int>(consume));
                });

                return handler.Handle(message);
            });
        }

After upgrading to 6.1.

 ---> MassTransit.TransportException: sb://no-host-configured/no-queue-specified => The IErrorTransport was not available on the ReceiveContext.
   at MassTransit.Pipeline.Filters.ErrorTransportFilter.GreenPipes.IFilter<MassTransit.ExceptionReceiveContext>.Send(ExceptionReceiveContext context, IPipe`1 next)
   at MassTransit.Pipeline.Filters.GenerateFaultFilter.GreenPipes.IFilter<MassTransit.ExceptionReceiveContext>.Send(ExceptionReceiveContext context, IPipe`1 next)
   at GreenPipes.Filters.RescueFilter`2.GreenPipes.IFilter<TContext>.Send(TContext context, IPipe`1 next)
   at MassTransit.Pipeline.Filters.DeadLetterFilter.GreenPipes.IFilter<MassTransit.ReceiveContext>.Send(ReceiveContext context, IPipe`1 next)
   at MassTransit.Azure.ServiceBus.Core.Transport.BrokeredMessageReceiver.MassTransit.Azure.ServiceBus.Core.Transport.IBrokeredMessageReceiver.Handle(Message message, Action`1 contextCallback)
   at MassTransit.Azure.ServiceBus.Core.Transport.BrokeredMessageReceiver.MassTransit.Azure.ServiceBus.Core.Transport.IBrokeredMessageReceiver.Handle(Message message, Action`1 contextCallback)
   at Symend.Core.App.AzureFunctions.Functions.ExecuteMessageConsumerAsync(Message message, IBinder binder, ILogger log, CancellationToken cancellationToken) in D:\a\1\s\src\Core\Symend.Core.App.AzureFunctions\Functions.cs:line 53
   at Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker`2.InvokeAsync(TReflected instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\VoidTaskMethodInvoker.cs:line 20
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 585
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 532
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, IFunctionOutputDefinition outputDefinition, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 468
   at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 278
   --- End of inner exception stack trace ---
   at Microsoft.Azure.WebJobs.ServiceBus.MessageProcessor.CompleteProcessingMessageAsync(Message message, FunctionResult result, CancellationToken cancellationToken)
   at Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener.ProcessMessageAsync(Message message, CancellationToken cancellationToken)
   at Microsoft.Azure.ServiceBus.MessageReceivePump.MessageDispatchTask(Message message)```


问:
Attempting to save todo list items to local storage
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>

    <html lang="en">

    <head>
      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
    </head>

    <body>
      <h1 id="header">TO DO LIST</h1>
      <div class="main">
        <form class="container" class="needs-validation" novalidate>
          <div class="input-group-prepend">
            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />
          </div>
        </form>
        <div class="todo-container">
          <h4 id="display" class="list-group">TODOS</h4>
        </div>
      </div>
      <script src="scripts.js"></script>
    </body>

</html></code>```

答:
When ever you in your code step, you ready to store/update data to the local storage, just call

```<code>localStorage.setItem("toItem", todoitem);
</code>```

And when you want to read the stored item you can call the below method to get data

```<code>localStorage.getItem("todoItem");
</code>```

Here is the document that that document

Body:
I have a pretty simple to do app that creates to dos and displays them to the screen. However, I wan't to save these to local storage so if someone leaves the page and returns, reloads the page, etc. the to do items remain.

I'm having trouble wrapping my head around how to use local storage though. I know relatively what I need to do, represented in pseudo code in my JavaScript document, but I can't seem to make it work. Any guidance would be greatly appreciated.

https://codepen.io/constequalsexcel/pen/GRJpzoE

function addTodo() {
  let todoItem = document.createElement('li');
  todoItem.setAttribute('class', 'list-item');
  let text = document.getElementById('todo-input').value;
  if (text.length < 1) return;
  let textnode = document.createElement('span');
  textnode.innerText = text;
  // Create delete todo button
  let deleteButton = document.createElement('button');
  let deleteButtonX = document.createTextNode('X');
  deleteButton.appendChild(deleteButtonX);
  deleteButton.addEventListener('click', removeNode);
  // Create strike through radio input
  let StrikeThroughRadio = document.createElement('input');
  StrikeThroughRadio.setAttribute('id', 'checkbox-styles');
  StrikeThroughRadio.setAttribute('type', 'checkbox');
  StrikeThroughRadio.addEventListener('click', function(e) {
    StrikeThroughRadio.checked ?
      e.target.nextElementSibling.classList.add('strike-text') :
      e.target.nextElementSibling.classList.remove('strike-text');
  });

  todoItem.appendChild(StrikeThroughRadio);
  todoItem.appendChild(textnode);
  todoItem.appendChild(deleteButton);
  enter code here

  document.getElementById('display').appendChild(todoItem);

// get saved todos from local storage and save it in a variable
// if saved todos variable is null then re-assign saved todoso variable equal to an empty array
// add current todo text to the saved todos array variable
// re-save saved todos into local storage (using the setItem() method)
    }
    function removeNode(e) {
      e.target.parentElement.remove();
    }
    `enter code here`

    function ClearInputOnSubmit() {
      document.getElementById('todo-input').value = '';
    }

    <!DOCTYPE html>

      <meta charset="utf-8" />

      <title>To-Do App</title>

      <link rel="stylesheet" href="styles.css" />
      <link href="https://fonts.googleapis.com/css?family=Roboto+Mono&display=swap" rel="stylesheet" />
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />

TO DO LIST

        <form class="container" class="needs-validation" novalidate>

            <input type="text" id="todo-input" class="form-control input-group shadow-lg" aria-describedby="button-addon2" required />
            <input type="button" value="Add ToDo" id="todo-button" id="button-addon2" class="btn btn-info btn-sm" onclick="addTodo(); ClearInputOnSubmit()" />

        </form>

TODOS

Body:
When ever you in your code step, you ready to store/update data to the local storage, just call

localStorage.setItem("toItem", todoitem);

And when you want to read the stored item you can call the below method to get data

localStorage.getItem("todoItem");

Here is the document that that document


问:
Add rounded corners in border in Maps Fragment and remove the Fragment background
I have added a border in Maps fragment. The corners are rounded too. But the problem is that the fragment background is still appearing in the corners. It just makes the whole design look odd. Can this be overcome? I am also attaching a screenshot of my problem that is occurring in my App. So I would appreciate any kind of help in this regard.

Here is the map code which I have used to implement the design explained in my question, so that the problem can be well understood.

```<code>**activity_maps.xml:**

<RelativeLayout
        android:layout_weight=".5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/map_border_2"
            android:orientation="vertical">
        </LinearLayout>

</RelativeLayout>
</code>```

```<code>Code for implementing the borders is given Below.

**map_border_2.xml (Drawable file):**

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:gradientRadius="2dp" />
            <stroke
                android:color="@color/glass"
                android:width="10dp" />
            <corners
                android:radius="10dp" />
        </shape>
    </item>
</selector>

In the above code, I need to remove the map fragment background from the four corners. I have added some buttons on the map but I have no issue in that!
</code>```

The Above image is the output of my code. In the above image, need to remove the places with circles.

答:
try add this line to RelativeLayout or fragment

android:background="@drawable/map_border_2"

I hope it will work with you

Body:
I have added a border in Maps fragment. The corners are rounded too. But the problem is that the fragment background is still appearing in the corners. It just makes the whole design look odd. Can this be overcome? I am also attaching a screenshot of my problem that is occurring in my App. So I would appreciate any kind of help in this regard.

Here is the map code which I have used to implement the design explained in my question, so that the problem can be well understood.

**activity_maps.xml:**

<RelativeLayout
        android:layout_weight=".5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">

        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:map="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentTop="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/map_border_2"
            android:orientation="vertical">
        </LinearLayout>

</RelativeLayout>

Code for implementing the borders is given Below.

**map_border_2.xml (Drawable file):**

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <gradient
                android:gradientRadius="2dp" />
            <stroke
                android:color="@color/glass"
                android:width="10dp" />
            <corners
                android:radius="10dp" />
        </shape>
    </item>
</selector>

In the above code, I need to remove the map fragment background from the four corners. I have added some buttons on the map but I have no issue in that!

The Above image is the output of my code. In the above image, need to remove the places with circles.


问:
React-admin JWT authentication refresh token problem
I want to implement my own authProvider for react-admin but I'm stuck.

I use a Django-Rest-Framework backend and a JWT token authentication system.

I want to refresh the JWT token if it's almost expired before every request. According to the documentation the authProvider's checkAuth function gets called before every API call, which is true. My problem is that with my code it doesn't wait for the promise to finish and it uses the old access token which results in a 401 and I get redirected to the login page. Any guidance what am I missing?

import jwt from 'jsonwebtoken';

export default {
    login: async ({ username, password }) => {
        const request = new Request('http://localhost:8000/api/token/', {
            method: 'POST',
            body: JSON.stringify({ username, password }),
            headers: new Headers({ 'Content-Type': 'application/json' }),
        });

        const response = await fetch(request);
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        const { refresh, access } = await response.json();
        localStorage.setItem("refreshToken", refresh);
        localStorage.setItem("accessToken", access);
    },

    logout: params => {
        console.log("logout");
        localStorage.setItem('accessToken', "");
        localStorage.setItem('refreshToken', "");

        return Promise.resolve();
    },

    checkAuth: (params) => {
        const accessToken = localStorage.getItem('accessToken');
        const refreshToken = localStorage.getItem('refreshToken');

        if (accessToken && refreshToken) {
            console.log(accessToken);
            const { exp } = jwt.decode(accessToken);
            if (exp > (new Date().getTime() / 1000) - 10) {
                return Promise.resolve();
            } else {
                const request = new Request('http://localhost:8000/api/token/refresh/', {
                    method: 'POST',
                    body: JSON.stringify({ "refresh": refreshToken }),
                    headers: new Headers({ 'Content-Type': 'application/json' }),
                });

                const response = fetch(request)
                .then(response => {
                    if (response.status !== 200) {
                        throw new Error(response.statusText);
                    }
                    return response.json();
                })
                .then(({ token }) => {
                    localStorage.setItem('accessToken', token);
                    return Promise.resolve();
                });

                return response;
            }
        }
        return Promise.reject();
    },

    checkError: error => {
        if (error.status === 401 || error.status === 403) {
            return Promise.reject();
        }
        return Promise.resolve();
    },
    getPermissions: params => Promise.resolve(),
}
```

答:
Can you try something like that

```<code>checkAuth: async (params) =>
</code>```

And

```<code>  const request = new Request(...);

  let data;
  const response = await fetch(request);
  if (response.ok) data = await response.json()
  else throw new Error(response.statusText);

  if (data && data.token) {
      localStorage.setItem('accessToken', data.token);
      console.log(data.token);
      return Promise.resolve();
  } else return Promise.reject();
</code>```

Body:
Can you try something like that

checkAuth: async (params) =>

And

  const request = new Request(...);

  let data;
  const response = await fetch(request);
  if (response.ok) data = await response.json()
  else throw new Error(response.statusText);

  if (data && data.token) {
      localStorage.setItem('accessToken', data.token);
      console.log(data.token);
      return Promise.resolve();
  } else return Promise.reject();


问:
Can't seem to simulate a keypress in Javascript that 'unlocks' & clicks the Reddit 'Post' button?
I've tried the following & they do not work:

```<code>document.querySelector("[placeholder=Title]").dispatchEvent(new KeyboardEvent('keypress',{'key':'70'}));

document.querySelector("[placeholder=Title]")..dispatchEvent(new KeyboardEvent('keyup',{'key':'70'}));

document.querySelector("[placeholder=Title]").value = 'titleTextProgramaticallyInput'[![jav][1]][1]
</code>```

The title element is preventing me from programatically clicking 'Post'

URL:
https://www.reddit.com/user/yourUsername/submit

答:
Reddit is using react, so these input fields are hidden behind layers of complexity. See this SO post.

Using the instructions from there you can light up the post button by triggering it's actual set method from the textArea prototype:

```<code>
var titleElement = document.querySelector("[placeholder=Title]");
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
nativeInputValueSetter.call(titleElement, 'react 16 value');

var triggerUpdateEvent = new Event('input', { bubbles: true});
titleElement.dispatchEvent(triggerUpdateEvent);

</code>```

Body:
I've tried the following & they do not work:

document.querySelector("[placeholder=Title]").dispatchEvent(new KeyboardEvent('keypress',{'key':'70'}));

document.querySelector("[placeholder=Title]")..dispatchEvent(new KeyboardEvent('keyup',{'key':'70'}));

document.querySelector("[placeholder=Title]").value = 'titleTextProgramaticallyInput'[![jav][1]][1]

The title element is preventing me from programatically clicking 'Post'

URL:
https://www.reddit.com/user/yourUsername/submit

Body:
Reddit is using react, so these input fields are hidden behind layers of complexity. See this SO post.

Using the instructions from there you can light up the post button by triggering it's actual set method from the textArea prototype:

var titleElement = document.querySelector("[placeholder=Title]");
var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
nativeInputValueSetter.call(titleElement, 'react 16 value');

var triggerUpdateEvent = new Event('input', { bubbles: true});
titleElement.dispatchEvent(triggerUpdateEvent);


问:
c# AutoML Regression training wont show Rsquared or MeanAbsoluteError
I am using c# AutoML to train a model for Regression and i cant see the Rsquared or MeanError for any of the algorithms

```<code>        //loading train data through Text Loader
        var trainData = loader.Load(_filePath);
        Console.WriteLine("created train data");

        var settings = new RegressionExperimentSettings
        {
            MaxExperimentTimeInSeconds = 10,
            //OptimizingMetric = RegressionMetric.MeanAbsoluteError
        };

        var progress = new Progress<RunDetail<RegressionMetrics>>(p =>
        {
            if (p.ValidationMetrics != null)
            {
                Console.WriteLine($"Current Result - {p.TrainerName}, {p.ValidationMetrics.RSquared}, {p.ValidationMetrics.MeanAbsoluteError}");
            }
        });

        var experiment = context.Auto().CreateRegressionExperiment(settings);
        //find best model

        var labelColumnInfo = new ColumnInformation()
        {
            LabelColumnName = "median_house_value"
        };

        var result = experiment.Execute(trainData, labelColumnInfo, progressHandler: progress);
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Best run:");
        Console.WriteLine($"Trainer name - {result.BestRun.TrainerName}");
        Console.WriteLine($"RSquared - {result.BestRun.ValidationMetrics.RSquared}");
        Console.WriteLine($"MAE - {result.BestRun.ValidationMetrics.MeanAbsoluteError}");
        Console.ReadLine();
</code>```

When i run the console application the outputs i get are 0  -infinite or not a number

答:
I've gotten similar results when my dataset has been too small.

AutoML is using 10 fold cross validation if I recall correctly. This can lead to the test data set being too small to get any usable metrics out of it.

So if your dataset is small, you could try with a bigger one and see if it gets better metrics, at least to rule out that case.

Body:
I am using c# AutoML to train a model for Regression and i cant see the Rsquared or MeanError for any of the algorithms

        //loading train data through Text Loader
        var trainData = loader.Load(_filePath);
        Console.WriteLine("created train data");

        var settings = new RegressionExperimentSettings
        {
            MaxExperimentTimeInSeconds = 10,
            //OptimizingMetric = RegressionMetric.MeanAbsoluteError
        };

        var progress = new Progress<RunDetail<RegressionMetrics>>(p =>
        {
            if (p.ValidationMetrics != null)
            {
                Console.WriteLine($"Current Result - {p.TrainerName}, {p.ValidationMetrics.RSquared}, {p.ValidationMetrics.MeanAbsoluteError}");
            }
        });

        var experiment = context.Auto().CreateRegressionExperiment(settings);
        //find best model

        var labelColumnInfo = new ColumnInformation()
        {
            LabelColumnName = "median_house_value"
        };

        var result = experiment.Execute(trainData, labelColumnInfo, progressHandler: progress);
        Console.WriteLine(Environment.NewLine);
        Console.WriteLine("Best run:");
        Console.WriteLine($"Trainer name - {result.BestRun.TrainerName}");
        Console.WriteLine($"RSquared - {result.BestRun.ValidationMetrics.RSquared}");
        Console.WriteLine($"MAE - {result.BestRun.ValidationMetrics.MeanAbsoluteError}");
        Console.ReadLine();

When i run the console application the outputs i get are 0  -infinite or not a number


问:
How to iterate through a JSON file with Javascript
I have the following Javascript file:

```<code>var request = new XMLHttpRequest()

request.open('GET', 'http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=USERNAMEHERE&api_key=APIKEYHERE=json', true)
request.onload = function() {
  // Begin accessing JSON data here
  let data = JSON.parse(this.response);

  if(request.status == 200){

    for(let artist in data){
      console.log(artist.name);
    }

  } else {
    console.log('Failure to connect. Please verify username and try again.');
  }

}

request.send()
</code>```

That code prints out 'undefined' in the console when I really want it to print out each artists name.

Here is an example of the JSON file:

```<code>{
  "topalbums": {
    "album": [
      {
        "artist": {
          "url": "https://www.last.fm/music/City+and+Colour",
          "name": "City and Colour",
          "mbid": ""
        },
        "@attr": {
          "rank": "1"
        },
        "image": [
          {
            "size": "small",
            "#text": "https://lastfm.freetls.fastly.net/i/u/34s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "medium",
            "#text": "https://lastfm.freetls.fastly.net/i/u/64s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "large",
            "#text": "https://lastfm.freetls.fastly.net/i/u/174s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "extralarge",
            "#text": "https://lastfm.freetls.fastly.net/i/u/300x300/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          }
        ],
        "playcount": "69",
        "url": "https://www.last.fm/music/City+and+Colour/Little+Hell+(Deluxe)",
        "name": "Little Hell (Deluxe)",
        "mbid": ""
      },
      {
        "artist": {
          "url": "https://www.last.fm/music/Various+Artists",
          "name": "Various Artists",
          "mbid": "4e46dd54-81a6-4a75-a666-d0e447861e3f"
        },
        "@attr": {
          "rank": "2"
        },
        "image": [
          {
            "size": "small",
            "#text": "https://lastfm.freetls.fastly.net/i/u/34s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "medium",
            "#text": "https://lastfm.freetls.fastly.net/i/u/64s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "large",
            "#text": "https://lastfm.freetls.fastly.net/i/u/174s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "extralarge",
            "#text": "https://lastfm.freetls.fastly.net/i/u/300x300/d1ce625570a8d54f2af4da3decbf901c.jpg"
          }
        ],
        "playcount": "46",
        "url": "https://www.last.fm/music/Various+Artists/1+Am.+Study+Session",
        "name": "1 Am. Study Session",
        "mbid": ""
      },
</code>```

What I want to happen is to have the name of each artist printed in the console. Any suggestions as to what I am doing wrong? Thank you for your time and if there is anything I can add for clarity, please don't hesitate.

Thank you.

答:
Take a look at the JSON file you gave. This entire object is what you have in data. It's as if you wrote this directly:

```<code>let data = { "topalbums": { ... } };
</code>```

If you had this kind of object, you can't skip directly to the array three levels deep. JavaScript doesn't know you want to go down a few levels, iterate over album, and pull only each artist object from each element in the array. You need to write all these things explicitly. You also want to use for..of to iterate over array values, as for..in will only get you keys (like 0, 1, 2, etc). Here's an example:

let data = {"topalbums":{"album":[{"artist":{"url":"https://www.last.fm/music/City+and+Colour","name":"City and Colour","mbid":""},"@attr":{"rank":"1"},"image":[{"size":"small","#text":"https://lastfm.freetls.fastly.net/i/u/34s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"medium","#text":"https://lastfm.freetls.fastly.net/i/u/64s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"large","#text":"https://lastfm.freetls.fastly.net/i/u/174s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"extralarge","#text":"https://lastfm.freetls.fastly.net/i/u/300x300/dc4fdb888cf796679cfe421ca9bc5317.jpg"}],"playcount":"69","url":"https://www.last.fm/music/City+and+Colour/Little+Hell+(Deluxe)","name":"Little Hell (Deluxe)","mbid":""},{"artist":{"url":"https://www.last.fm/music/Various+Artists","name":"Various Artists","mbid":"4e46dd54-81a6-4a75-a666-d0e447861e3f"},"@attr":{"rank":"2"},"image":[{"size":"small","#text":"https://lastfm.freetls.fastly.net/i/u/34s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"medium","#text":"https://lastfm.freetls.fastly.net/i/u/64s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"large","#text":"https://lastfm.freetls.fastly.net/i/u/174s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"extralarge","#text":"https://lastfm.freetls.fastly.net/i/u/300x300/d1ce625570a8d54f2af4da3decbf901c.jpg"}],"playcount":"46","url":"https://www.last.fm/music/Various+Artists/1+Am.+Study+Session","name":"1 Am. Study Session","mbid":""}]}};

for(let album of data.topalbums.album){
  console.log(album.artist.name);
}```

Body:
I have the following Javascript file:

var request = new XMLHttpRequest()

request.open('GET', 'http://ws.audioscrobbler.com/2.0/?method=user.gettopartists&user=USERNAMEHERE&api_key=APIKEYHERE=json', true)
request.onload = function() {
  // Begin accessing JSON data here
  let data = JSON.parse(this.response);

  if(request.status == 200){

    for(let artist in data){
      console.log(artist.name);
    }

  } else {
    console.log('Failure to connect. Please verify username and try again.');
  }

}

request.send()

That code prints out 'undefined' in the console when I really want it to print out each artists name.

Here is an example of the JSON file:

{
  "topalbums": {
    "album": [
      {
        "artist": {
          "url": "https://www.last.fm/music/City+and+Colour",
          "name": "City and Colour",
          "mbid": ""
        },
        "@attr": {
          "rank": "1"
        },
        "image": [
          {
            "size": "small",
            "#text": "https://lastfm.freetls.fastly.net/i/u/34s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "medium",
            "#text": "https://lastfm.freetls.fastly.net/i/u/64s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "large",
            "#text": "https://lastfm.freetls.fastly.net/i/u/174s/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          },
          {
            "size": "extralarge",
            "#text": "https://lastfm.freetls.fastly.net/i/u/300x300/dc4fdb888cf796679cfe421ca9bc5317.jpg"
          }
        ],
        "playcount": "69",
        "url": "https://www.last.fm/music/City+and+Colour/Little+Hell+(Deluxe)",
        "name": "Little Hell (Deluxe)",
        "mbid": ""
      },
      {
        "artist": {
          "url": "https://www.last.fm/music/Various+Artists",
          "name": "Various Artists",
          "mbid": "4e46dd54-81a6-4a75-a666-d0e447861e3f"
        },
        "@attr": {
          "rank": "2"
        },
        "image": [
          {
            "size": "small",
            "#text": "https://lastfm.freetls.fastly.net/i/u/34s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "medium",
            "#text": "https://lastfm.freetls.fastly.net/i/u/64s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "large",
            "#text": "https://lastfm.freetls.fastly.net/i/u/174s/d1ce625570a8d54f2af4da3decbf901c.jpg"
          },
          {
            "size": "extralarge",
            "#text": "https://lastfm.freetls.fastly.net/i/u/300x300/d1ce625570a8d54f2af4da3decbf901c.jpg"
          }
        ],
        "playcount": "46",
        "url": "https://www.last.fm/music/Various+Artists/1+Am.+Study+Session",
        "name": "1 Am. Study Session",
        "mbid": ""
      },

What I want to happen is to have the name of each artist printed in the console. Any suggestions as to what I am doing wrong? Thank you for your time and if there is anything I can add for clarity, please don't hesitate.

Thank you.

Body:
Take a look at the JSON file you gave. This entire object is what you have in data. It's as if you wrote this directly:

let data = { "topalbums": { ... } };

If you had this kind of object, you can't skip directly to the array three levels deep. JavaScript doesn't know you want to go down a few levels, iterate over album, and pull only each artist object from each element in the array. You need to write all these things explicitly. You also want to use for..of to iterate over array values, as for..in will only get you keys (like 0, 1, 2, etc). Here's an example:

let data = {"topalbums":{"album":[{"artist":{"url":"https://www.last.fm/music/City+and+Colour","name":"City and Colour","mbid":""},"@attr":{"rank":"1"},"image":[{"size":"small","#text":"https://lastfm.freetls.fastly.net/i/u/34s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"medium","#text":"https://lastfm.freetls.fastly.net/i/u/64s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"large","#text":"https://lastfm.freetls.fastly.net/i/u/174s/dc4fdb888cf796679cfe421ca9bc5317.jpg"},{"size":"extralarge","#text":"https://lastfm.freetls.fastly.net/i/u/300x300/dc4fdb888cf796679cfe421ca9bc5317.jpg"}],"playcount":"69","url":"https://www.last.fm/music/City+and+Colour/Little+Hell+(Deluxe)","name":"Little Hell (Deluxe)","mbid":""},{"artist":{"url":"https://www.last.fm/music/Various+Artists","name":"Various Artists","mbid":"4e46dd54-81a6-4a75-a666-d0e447861e3f"},"@attr":{"rank":"2"},"image":[{"size":"small","#text":"https://lastfm.freetls.fastly.net/i/u/34s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"medium","#text":"https://lastfm.freetls.fastly.net/i/u/64s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"large","#text":"https://lastfm.freetls.fastly.net/i/u/174s/d1ce625570a8d54f2af4da3decbf901c.jpg"},{"size":"extralarge","#text":"https://lastfm.freetls.fastly.net/i/u/300x300/d1ce625570a8d54f2af4da3decbf901c.jpg"}],"playcount":"46","url":"https://www.last.fm/music/Various+Artists/1+Am.+Study+Session","name":"1 Am. Study Session","mbid":""}]}};

for(let album of data.topalbums.album){
  console.log(album.artist.name);
}


问:
Having trouble using .h files to export functions
I have a .c file which has code for functions, and a .h file that sets up the function prototypes so they can be accessed from other files, but they are in conflict.

Here is the error I get:

```<code>file.c:111: error: ‘Function’ redeclared as different kind of symbol
file.h:16: error: previous declaration of ‘Function’ was here
</code>```

In file.c:

```<code>#include "file.h"
...

void *Function(const char *filename) {
    ...
}
</code>```

In file.h:

```<code>typedef void (*Function)(const char *filename);
</code>```

Thanks in advance!

答:
You're creating typedef of a function pointer instead of a prototype. Your declaration says that variable of type Function is a pointer to a function returning nothing and accepting a const char*.

I think what you really want in the .h file is this:

```<code>void *Function(const char *filename);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a .c file which has code for functions, and a .h file that sets up the function prototypes so they can be accessed from other files, but they are in conflict.

Here is the error I get:

file.c:111: error: ‘Function’ redeclared as different kind of symbol
file.h:16: error: previous declaration of ‘Function’ was here

In file.c:

#include "file.h"
...

void *Function(const char *filename) {
    ...
}

In file.h:

typedef void (*Function)(const char *filename);

Thanks in advance!

Body:
You're creating typedef of a function pointer instead of a prototype. Your declaration says that variable of type Function is a pointer to a function returning nothing and accepting a const char*.

I think what you really want in the .h file is this:

void *Function(const char *filename);


问:
How do I compress my GIF image to improve my Website?
I'm working on optimizing my website speed so that it is a lot faster. I have already compressed my image files, but one GIF that I have on my site is slowing everything down. The file size of it is 4.73 MB

I believe that's way too big for my site and is causing it to take a while to load. Anyone know how I can make the GIF compressed without losing quality of the image?

答:
yes over 4MB is to big for everyone and everything. On this website you can find an comparison table for "gif size reducer" tools.

https://gifcop.com/best-tools-compress-gif-images/

You should think about your gif-file.
Is the gif-file really useful for your users?


答:
You could save each item to localStorage (not sessionStorage!!!) or you could batch them into a JSON object then store the entire thing as a string by first converting to as string JSON.stringify(your_json_object).

Scenario 1. save each item to local storage. one after another.

```<code>localStorage.setItem('item1', 'value1')
</code>```

or

Scenario 2. build a JSON object first and save everything.

```<code>your_json_object = {item1: 'value1', item2: 'value2' ...};
localStorage.setItem(all_info: JSON.stringify(your_json_object));
</code>```

Title: Attempting to save todo list items to local storage

Body:
You could save each item to localStorage (not sessionStorage!!!) or you could batch them into a JSON object then store the entire thing as a string by first converting to as string JSON.stringify(your_json_object).

Scenario 1. save each item to local storage. one after another.

localStorage.setItem('item1', 'value1')

or

Scenario 2. build a JSON object first and save everything.

your_json_object = {item1: 'value1', item2: 'value2' ...};
localStorage.setItem(all_info: JSON.stringify(your_json_object));


问:
(C#) BackgroundWorker() ProgressChanged not working
I have a WPF application that consist of two threads simulating an enterprise producting and selling items in 52 weeks (only one transaction is allowed per week). I need to use a background worker as well so that I can display the data in a listview. As of right now, my UI freezes when clicking on simulate but I can see that the output is still working in the debugging terminal. I have tried everything that I can think of and to be honest, I have had the help of my teacher and even he couldn't find a working solution.

What is freezing my UI when I call Simulate() ?

When my code is different and my UI isn't freezing, my listview never updates because it seems that DataProgress() doesn't work — e.UserStart is never iterating.

Simulate button calls :

private void Simulate(object sender, RoutedEventArgs e)
{
    // Declare BackgroundWorker
    Data = new ObservableCollection<Operations>();
    worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerAsync(52);

    worker.DoWork += ShowData;
    worker.ProgressChanged += DataProgress;
    worker.RunWorkerCompleted += DataToDB;

    Production = new Production(qtyProduction, timeExecProd);
    Sales = new Sales(qtySales, timeExecSales);

    Thread prod = new Thread(Production.Product);
    prod.Start();

    Thread.Sleep(100);

    Thread sales = new Thread(Sales.Sell);
    sales.Start();
}
```

<p><strong>DoWork : ShowData() :</strong></p>

<pre class="lang-cs prettyprint-override"><code>Console.WriteLine("Simulation started | Initial stock : 500");

Production = new Production(qtyProduction, timeExecProd);
Sales = new Sales(qtySales, timeExecSales);

while (Factory.Week < max) // max = 52
{
    if (worker.CancellationPending) // also this isn't reacting to worker.CancelAsync();
        e.Cancel = true;

   // My teacher tried to call my threads from here, but it breaks the purpose of having
   // two threads as he was just calling 52 times two functions back to back and therefore
   // wasn't "randomizing" the transactions.

    int progressPercentage = Convert.ToInt32(((double)(Factory.Week) / max) * 100);
    (sender as BackgroundWorker).ReportProgress(progressPercentage, Factory.Week);
}
</code>```

ProgressChanged : DataProgress() :

if (e.UserState != null) // While using debugger, it looks like this is called over & over
{
    Data.Add(new Operations()
    {
        id = rnd.Next(1,999),
        name = Factory.name,
        qtyStock = Factory.Stock,
        averageStock = Factory.AverageStock,
        week = Factory.Week
    });
    listview.ItemsSource = Data;
}
```

<p><strong>RunWorkerCompleted : DataToDB() :</strong></p>

<pre class="lang-cs prettyprint-override"><code>    // Outputs "Work done" for now.
</code>```

In case you want to know what happens when I call my threads, it looks like this :

Sell() :

while (Factory.Week <= 52)
{
    lock (obj)
    {
        // some math function callings¸
        Factory.Week++;
    }
    Thread.Sleep(timeExecSales);
}
```

Should I use a third thread just for updating my listview? I don't see how as I need it to be synced with my static variables. This is my first project for learning multithreading... I'm kind of clueless and flabbergasted that even my teacher can't help.

答:
On the one hand, there isnt enough context in the code posted to get a full picture to answer your questions accurately. We can, however, deduce what is going wrong just from the code you have posted.

First, lets try to answer your two questions. We can likely infer the following:

This code here:

```<code>if (e.UserState != null)
{
    Data.Add(new Operations()
    {
        id = rnd.Next(1,999),
        name = Factory.name,
        qtyStock = Factory.Stock,
        averageStock = Factory.AverageStock,
        week = Factory.Week
    });
    listview.ItemsSource = Data;
}
</code>```

You are using a Windows Forms background thread object to try and update a WPF GUI object which should only be done on the main GUI thread. There is also the obvious no-no of never updating GUI objects from non-UI threads. Using BackgroundWorker also has its own issues with threading (foreground/background), contexts and execution, as it relies on the Dispatcher and SynchronizationContexts to get the job done.

Then there is the curiosity of setting the binding over and over in this line:

listview.ItemsSource = Data;

Let's put a pin in that for a moment...

There is, as the other commenter pointer out already, no exit strategy in your while loop:

```<code>while (Factory.Week < max) // max = 52
{
    if (worker.CancellationPending) // also this isn't reacting to worker.CancelAsync();
        e.Cancel = true;

   // My teacher tried to call my threads from here, but it breaks the purpose of having
   // two threads as he was just calling 52 times two functions back to back and therefore
   // wasn't "randomizing" the transactions.

    int progressPercentage = Convert.ToInt32(((double)(Factory.Week) / max) * 100);
    (sender as BackgroundWorker).ReportProgress(progressPercentage, Factory.Week);
}
</code>```

But thats not the bigger problem... in addition to the misuse/misunderstanding of when/how many/how to use threading, there doesnt seem to be any kind of thread synchronization of any kind. There is no way to predict or track thread execution of lifetime in this way.

At this point the question is technically more or less answered, but I feel like this will just leave you more frustrated and no better off than you started. So maybe a quick crash course in basic design might help straighten out this mess, something your teacher should have done.

Assuming you are pursuing software development, and since you have chosen WPF here as your "breadboard" so to speak, you will likely come across terms such as MVC (model view controller) or MVVM (model view view-model). You will also likely come across design principles such as SOLID, separation of concerns, and grouping things into services.

Your code here is a perfect example of why all of these frameworks and principles exist. Lets look at some of the problems you have encountered and how to fix them:

You have threading code (logic and services - controller [loosely speaking]) mixed in with presentation code (listview update - view) and collection update (your observable collection - model). Thats one reason (of many) you are having such a difficult time coding, fixing and maintaining the problem at hand. To clean it up, separate it out (separation of concerns). You might even move each operation into its own class with an interface/API to that class (service/ micro-service).

Not everything needs to be solved with threads. But for now, lets learn to crawl, then walk before we run. Before you start learning about async/await or the TPL (task parallel library) lets go old school. Get a good book... something even from 20 years ago is find... go old school, and learn how to use the ThreadPool and kernel synchronization objects such as mutexes, events, etc and how to signal between threads. Once you master that, then learn about TPL and async/await.

Dont cross the streams. Dont mix WinForms, WPF and I even saw Console.WriteLine.

Learn about Data Binding, and in particular how it works in WPF. ObservableCollection is your friend, bind your ItemsSource to it once, then update the ObservableCollection and leave the GUI object alone.

Hopefully this will help you straighten out the code and get things running.

Good luck!

Body:
I have a WPF application that consist of two threads simulating an enterprise producting and selling items in 52 weeks (only one transaction is allowed per week). I need to use a background worker as well so that I can display the data in a listview. As of right now, my UI freezes when clicking on simulate but I can see that the output is still working in the debugging terminal. I have tried everything that I can think of and to be honest, I have had the help of my teacher and even he couldn't find a working solution.

What is freezing my UI when I call Simulate() ?

When my code is different and my UI isn't freezing, my listview never updates because it seems that DataProgress() doesn't work — e.UserStart is never iterating.

Simulate button calls :

private void Simulate(object sender, RoutedEventArgs e)
{
    // Declare BackgroundWorker
    Data = new ObservableCollection<Operations>();
    worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.RunWorkerAsync(52);

    worker.DoWork += ShowData;
    worker.ProgressChanged += DataProgress;
    worker.RunWorkerCompleted += DataToDB;

    Production = new Production(qtyProduction, timeExecProd);
    Sales = new Sales(qtySales, timeExecSales);

    Thread prod = new Thread(Production.Product);
    prod.Start();

    Thread.Sleep(100);

    Thread sales = new Thread(Sales.Sell);
    sales.Start();
}

DoWork : ShowData() :

Console.WriteLine("Simulation started | Initial stock : 500");

Production = new Production(qtyProduction, timeExecProd);
Sales = new Sales(qtySales, timeExecSales);

while (Factory.Week < max) // max = 52
{
    if (worker.CancellationPending) // also this isn't reacting to worker.CancelAsync();
        e.Cancel = true;

   // My teacher tried to call my threads from here, but it breaks the purpose of having
   // two threads as he was just calling 52 times two functions back to back and therefore
   // wasn't "randomizing" the transactions.

    int progressPercentage = Convert.ToInt32(((double)(Factory.Week) / max) * 100);
    (sender as BackgroundWorker).ReportProgress(progressPercentage, Factory.Week);
}

ProgressChanged : DataProgress() :

if (e.UserState != null) // While using debugger, it looks like this is called over & over
{
    Data.Add(new Operations()
    {
        id = rnd.Next(1,999),
        name = Factory.name,
        qtyStock = Factory.Stock,
        averageStock = Factory.AverageStock,
        week = Factory.Week
    });
    listview.ItemsSource = Data;
}

RunWorkerCompleted : DataToDB() :

    // Outputs "Work done" for now.

In case you want to know what happens when I call my threads, it looks like this :

Sell() :

while (Factory.Week <= 52)
{
    lock (obj)
    {
        // some math function callings¸
        Factory.Week++;
    }
    Thread.Sleep(timeExecSales);
}

Should I use a third thread just for updating my listview? I don't see how as I need it to be synced with my static variables. This is my first project for learning multithreading... I'm kind of clueless and flabbergasted that even my teacher can't help.

Body:
On the one hand, there isnt enough context in the code posted to get a full picture to answer your questions accurately. We can, however, deduce what is going wrong just from the code you have posted.

First, lets try to answer your two questions. We can likely infer the following:

This code here:

if (e.UserState != null)
{
    Data.Add(new Operations()
    {
        id = rnd.Next(1,999),
        name = Factory.name,
        qtyStock = Factory.Stock,
        averageStock = Factory.AverageStock,
        week = Factory.Week
    });
    listview.ItemsSource = Data;
}

You are using a Windows Forms background thread object to try and update a WPF GUI object which should only be done on the main GUI thread. There is also the obvious no-no of never updating GUI objects from non-UI threads. Using BackgroundWorker also has its own issues with threading (foreground/background), contexts and execution, as it relies on the Dispatcher and SynchronizationContexts to get the job done.

Then there is the curiosity of setting the binding over and over in this line:

listview.ItemsSource = Data;

Let's put a pin in that for a moment...

There is, as the other commenter pointer out already, no exit strategy in your while loop:

while (Factory.Week < max) // max = 52
{
    if (worker.CancellationPending) // also this isn't reacting to worker.CancelAsync();
        e.Cancel = true;

   // My teacher tried to call my threads from here, but it breaks the purpose of having
   // two threads as he was just calling 52 times two functions back to back and therefore
   // wasn't "randomizing" the transactions.

    int progressPercentage = Convert.ToInt32(((double)(Factory.Week) / max) * 100);
    (sender as BackgroundWorker).ReportProgress(progressPercentage, Factory.Week);
}

But thats not the bigger problem... in addition to the misuse/misunderstanding of when/how many/how to use threading, there doesnt seem to be any kind of thread synchronization of any kind. There is no way to predict or track thread execution of lifetime in this way.

At this point the question is technically more or less answered, but I feel like this will just leave you more frustrated and no better off than you started. So maybe a quick crash course in basic design might help straighten out this mess, something your teacher should have done.

Assuming you are pursuing software development, and since you have chosen WPF here as your "breadboard" so to speak, you will likely come across terms such as MVC (model view controller) or MVVM (model view view-model). You will also likely come across design principles such as SOLID, separation of concerns, and grouping things into services.

Your code here is a perfect example of why all of these frameworks and principles exist. Lets look at some of the problems you have encountered and how to fix them:

You have threading code (logic and services - controller [loosely speaking]) mixed in with presentation code (listview update - view) and collection update (your observable collection - model). Thats one reason (of many) you are having such a difficult time coding, fixing and maintaining the problem at hand. To clean it up, separate it out (separation of concerns). You might even move each operation into its own class with an interface/API to that class (service/ micro-service).

Not everything needs to be solved with threads. But for now, lets learn to crawl, then walk before we run. Before you start learning about async/await or the TPL (task parallel library) lets go old school. Get a good book... something even from 20 years ago is find... go old school, and learn how to use the ThreadPool and kernel synchronization objects such as mutexes, events, etc and how to signal between threads. Once you master that, then learn about TPL and async/await.

Dont cross the streams. Dont mix WinForms, WPF and I even saw Console.WriteLine.

Learn about Data Binding, and in particular how it works in WPF. ObservableCollection is your friend, bind your ItemsSource to it once, then update the ObservableCollection and leave the GUI object alone.

Hopefully this will help you straighten out the code and get things running.

Good luck!


问:
What would be the best language/library choice for writing a scalable webservice server?
I've been engaged in a project to write a game dissemination and service platform, which would enable game developers to easily outsource game distribution and updates as well as offering certain parts of multiplayer/community such as achievements, rankings, friends and such as a webservice in form of either SOAP or REST API.

I'm not sure how viable it is in terms of attaining market share, but none the less the application should be written as to scale horizontally well in order to absorb any quantity of possible users. Since the project is still in it's early stages I have some degree of influence regarding the language and technologies to be used.

So far my research has narrowed the choice down to either Erlang or a JVM based language.

Erlang is widely known for it's focus on scalable and fault-tolerant distributed applications and proven track record, but on the other hand it's library ecosystem is nowhere as rich as JVM's.
JVM languages on the other hand enjoy a big community with a multitude libraries, many of which strive to provide for distributed and reliable services, such as Terracota or Akka (which seems to be inspired by Erlang, though I'm not sure how much of it's strength it approaches and would like to hear about it).

Since language productivity is of equal importance as platform strength and reliability I would lean towards Scala or Clojure over Java if I were to use JVM.
Of course if you think there is another language (JVM or non-) better suited to such a task I'm interested to hear about it.

I wouldn't like to read a bulletpoint list of language's cool features as that's what I can google by myself, I'd rather be interested in your own experiences with writing such an application (a bit in the vein of those blogposts - link), though not only concerning raw performance but also language and library issues.

I would like to hear what your (or your company's) language and technology choices for such a type of project were, what motivated such a choice, what your experiences using the chosen platform were and did it ultimately deliver.

All insight will be greatly appreciated ; )

答:
Given your initial interest in Erlang, I'd have to say Scala.

Scala actors were directly inspired by Erlang, and Akka started (long ago now) as a port of Erlang's OTP to the Scala language.

Both Scala and Akka are robust solutions used in commercial settings, and are well supported by the recently formed "Typesafe" company.  Plus, you get all your stated advantages of running on the JVM platform.


问:
How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?
I have the following element:

```<code><button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
</code>```

I want to use jquery (or just javascript would work) to alter the aria-expanded field to toggle it between true and false.

How would I go about this?

Thanks!

答:
Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button[aria-expanded="true"] {
  color: red;
}</code>```

<button type="button" aria-expanded="false">Click me!</button>```

Body:
I have the following element:

<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">

I want to use jquery (or just javascript would work) to alter the aria-expanded field to toggle it between true and false.

How would I go about this?

Thanks!

Body:
Since the question asked for either jQuery or vanilla JS, here's an answer with vanilla JS.

I've added some CSS to the demo below to change the button's font color to red when its aria-expanded is set to true

const button = document.querySelector('button');

button.addEventListener('click', () => {
  button.ariaExpanded = !JSON.parse(button.ariaExpanded);
})

button[aria-expanded="true"] {
  color: red;
}

<button type="button" aria-expanded="false">Click me!</button>


问:
How do I modify/subset a wget script to specify a date range to only download certain years into different scripts?
I am trying to download a lot of data for some research from the CMIP6 website (https://esgf-node.llnl.gov/search/cmip6/) that provides wget scripts for each model.

The scripts are for every 6 hours or month from 1850 to 2014. The date format looks like this (1st script): 185001010600-185101010000 or (for 2nd script) 195001010600-195002010000, 195002010600-195003010000

My goal is to turn one giant script into several smaller ones with five years each for 1980 to 2015

As an example, I would want to subset the main script into different scripts with 5 year intervals ("19800101-19841231" then "19850101-19901231", etc.) with each named wget-1980_1985.sh, wget-1985_1990.sh, respectively

For an example date range for the 2nd script, I would need:
197912010600 through 198601010000, then every 5 years after that

I'm a beginner so please help if you can!

Part of the wget script format for each file looks like this (it won't let me copy and paste the whole thing since there are too many links [see below to find the file yourself]):

1.) #These are the embedded files to be downloaded download_files="$(cat <185001010600-185101010000.nc' 'http://esgf-data2.diasjp.net/thredds/fileServer/esg_dataroot/CMIP6/CMIP/MIROC/MIROC6/historical/r1i1p1f1/6hrPlevPt/hus/gn/v20191204/hus_6hrPlevPt_MIROC6_historical_r1i1p1f1_gn_185001010600-185101010000.nc' 'SHA256'
  'fa9ac4149cc700876cb10c4e681173bcc0040ea03b9a439d1c66ef47b0253c5a'
  'hus_6hrPlevPt_MIROC6_historical_r1i1p1f1_gn_185101010600-185201010000.nc' 'http://esgf-data2.diasjp.net/thredds/fileServer/esg_dataroot/CMIP6/CMIP/MIROC/MIROC6/historical/r1i1p1f1/6hrPlevPt/hus/gn/v20191204/hus_6hrPlevPt_MIROC6_historical_r1i1p1f1_gn_185101010600-185201010000.nc' 'SHA256'
  '4ef4f99aa34aae6dfdafaa4aab206344125abe7808df675d688890825db53047'

2.) For the second script, the dates look like this: 'ps_6hrLev_MIROC6_historical_r1i1p1f1_gn_195001010600-195002010000.nc'

To run it, you just download the script from the website (see below)

or downloading from this link should work:
1.) https://esgf-node.llnl.gov/esg-search/wget/?distrib=false&dataset_id=CMIP6.CMIP.MIROC.MIROC6.historical.r1i1p1f1.6hrPlevPt.hus.gn.v20191204|esgf-data2.diasjp.net

2.) A similar script can be seen here (the dates are different but I need this one too):
https://esgf-node.llnl.gov/esg-search/wget/?distrib=false&dataset_id=CMIP6.CMIP.MIROC.MIROC6.historical.r1i1p1f1.6hrLev.ps.gn.v20191114|esgf-data2.diasjp.net

to run the script in the terminal, this is the command i use

bash wget* -H

and it will download each file.

I can vi the script and delete each file (by using "dd") I don't need but this will be extremely time consuming.

To find this data and get the wget script from the website, go to: https://esgf-node.llnl.gov/search/cmip6/

and select the variables on the left side of the page as follows:
Source ID: MIROC6,
Experiment ID: Historical,
Variant Label: r1i1p1f1,
Table ID: 6hrPlevPt,
and Variable: hus
it will look like this

*If these files are too big, you can also select Frequency:monthly instead for a much smaller file. I just want you to see the date format since monthly is just the month and year

Then hit search and it will give you one model to download. it will look like thisOn the bottom, with the links, it will say "wget script." Click that and it will download.

You can

vi wget*

to view and/or edit it or

bash wget* -H

to run/download each file.
It might ask you to log in but I've found typing in nonsense to the username and password still starts the download.

Please help! This will be the next 6 months of my life and I really don't want to "dd" every file I don't need for all of these!

答:
A bash for loop can generate relevant date ranges and output filename.

A simple sed script can delete relevant lines if they appear in order.

For example:

```<code>#!/bin/bash

in=esgf_script

for y in $(seq 1979 5 2014); do
    out="wget_{$y}-$((y+4)).sh"
    sed '/_gn_/{               # if some kind of url:
        /_gn_'$((y+5))'/,$  d; #   delete if year >= y+5
        /_gn_2015/,$        d; #   delete if year >= 2015
        /_gn_'$y'/,$       !d; #   delete if year < y
    }' <"$in" >"$out"
done
</code>```

The seq command generates every fifth year starting from 1979 up to 2014.

The sed script:

looks for lines containing urls: /_gn_/

deletes if year is too big

otherwise, doesn't delete if year is big enough

This code assumes that:

no lines except urls contain the first regex (/_gn_/)

the urls appear in ascending year order (eg. urls containing 1994 cannot appear before ones containing 1993)

Body:
A bash for loop can generate relevant date ranges and output filename.

A simple sed script can delete relevant lines if they appear in order.

For example:

#!/bin/bash

in=esgf_script

for y in $(seq 1979 5 2014); do
    out="wget_{$y}-$((y+4)).sh"
    sed '/_gn_/{               # if some kind of url:
        /_gn_'$((y+5))'/,$  d; #   delete if year >= y+5
        /_gn_2015/,$        d; #   delete if year >= 2015
        /_gn_'$y'/,$       !d; #   delete if year < y
    }' <"$in" >"$out"
done

The seq command generates every fifth year starting from 1979 up to 2014.

The sed script:

looks for lines containing urls: /_gn_/

deletes if year is too big

otherwise, doesn't delete if year is big enough

This code assumes that:

no lines except urls contain the first regex (/_gn_/)

the urls appear in ascending year order (eg. urls containing 1994 cannot appear before ones containing 1993)


问:
Error loading image png file to react app
getting a Error: Cannot find module 'schema-utils'
when trying to import image, seems a bit strange, I tried to import from the public directory aswell as directly within the Header component folder and get the same error. Here is my code

```<code>import React from "react";
import "../styles/Header.css";
import title from "./insta-title.png";

export default function Header() {
  return (
    <div className="head">
      <header>
        <img src={title}></img>
      </header>
    </div>
  );
}

</code>```

答:
img tag in react written like this  so edit your code to be like this :

```<code>import React from "react";
import "../styles/Header.css";
import title from "./insta-title.png";
export default function Header() { return ( <div className="head"> <header> <img src={title}/></header> </div> );
</code>```

Body:
getting a Error: Cannot find module 'schema-utils'
when trying to import image, seems a bit strange, I tried to import from the public directory aswell as directly within the Header component folder and get the same error. Here is my code

import React from "react";
import "../styles/Header.css";
import title from "./insta-title.png";

export default function Header() {
  return (

  );
}

Body:
img tag in react written like this  so edit your code to be like this :

import React from "react";
import "../styles/Header.css";
import title from "./insta-title.png";
export default function Header() { return ( <div className="head"> <header> <img src={title}/></header> </div> );


问:
Appending a function return value to a string variable in Powershell
Assuming the following Powershell script...

```<code>function Process-Folder {
    [cmdletbinding()]
    param ([string]$Path)
    Process {
        $returnvalue = ""
        # code here that reads all of the .txt files in $path
        # and concatenates their contents to $returnvalue
    return $returnvalue
    }
}
</code>```

I'd like to add lines to this script which call this function a couple of times to process several folders.  I would write that code as follows:

```<code>$allFileContent = ""
$firstFolder = Process-Folder -Path "c:\foo"
$allFileContent = $allFileContent + $firstFolder

$secondFolder = Process-Folder -Path "c:\bar"
$allFileContent = $allFileContent + $secondFolder
</code>```

This code works but seems inelegant and doesn't seem like "the Powershell way".  I tried:

```<code>$filecontent = ""
$filecontent = $filecontent + Process-Folder -Path "C:\foo"
$filecontent = $filecontent + Process-Folder -Path "C:\bar"
</code>```

But ISE gave me "unexpected token 'Process-Folder' in expression or statement.  I also tried:

```<code>$filecontent = ""
$filecontent | Process-Folder -Path "C:\foo"
$filecontent | Process-Folder -Path "C:\bar"
</code>```

Which returned...

```<code>The input object cannot be bound to any parameters for the command either because the
command does not take pipeline input or the input and its properties do not match any
of the parameters that take pipeline input.
</code>```

How can I accomplish what the first snippet does in a more elegant/"Powershell-like" way?

答:
Looks like you need to put parens around your commands to get them to execute first.  Also don't forget that $x += 'a' is the same as $x = $x + 'a', and you can assign the first value, and add the second without having to assign the empty string first, so try this:

```<code>$filecontent = Process-Folder -Path "C:\foo"
$filecontent += Process-Folder -Path "C:\bar"
</code>```

EDIT: I realized after I got done rewriting the code, that I had put it in a form where you no longer need the parens, so I removed them.  But doing that completely lost the example I was using to show you how to fix the lines that were a problem for you before (duh).

So...the parens are needed when combining some data with the result of a function.  You have to force the function to run first.  So in your original format, you would need parens like so:

```<code>$filecontent = ""
$filecontent = $filecontent + (Process-Folder -Path "C:\foo")
$filecontent + $filecontent + (Process-Folder -Path "C:\bar")
</code>```

You can read all about it in this article

For the pipe, you need to set up a variable in your function which can accept input from the pipeline. I think this article does a really good job of explaining how to use the pipeline if you decide to take that route.

Hope this helps!

Body:
Assuming the following Powershell script...

function Process-Folder {
    [cmdletbinding()]
    param ([string]$Path)
    Process {
        $returnvalue = ""
        # code here that reads all of the .txt files in $path
        # and concatenates their contents to $returnvalue
    return $returnvalue
    }
}

I'd like to add lines to this script which call this function a couple of times to process several folders.  I would write that code as follows:

$allFileContent = ""
$firstFolder = Process-Folder -Path "c:\foo"
$allFileContent = $allFileContent + $firstFolder

$secondFolder = Process-Folder -Path "c:\bar"
$allFileContent = $allFileContent + $secondFolder

This code works but seems inelegant and doesn't seem like "the Powershell way".  I tried:

$filecontent = ""
$filecontent = $filecontent + Process-Folder -Path "C:\foo"
$filecontent = $filecontent + Process-Folder -Path "C:\bar"

But ISE gave me "unexpected token 'Process-Folder' in expression or statement.  I also tried:

$filecontent = ""
$filecontent | Process-Folder -Path "C:\foo"
$filecontent | Process-Folder -Path "C:\bar"

Which returned...

The input object cannot be bound to any parameters for the command either because the
command does not take pipeline input or the input and its properties do not match any
of the parameters that take pipeline input.

How can I accomplish what the first snippet does in a more elegant/"Powershell-like" way?

Body:
Looks like you need to put parens around your commands to get them to execute first.  Also don't forget that $x += 'a' is the same as $x = $x + 'a', and you can assign the first value, and add the second without having to assign the empty string first, so try this:

$filecontent = Process-Folder -Path "C:\foo"
$filecontent += Process-Folder -Path "C:\bar"

EDIT: I realized after I got done rewriting the code, that I had put it in a form where you no longer need the parens, so I removed them.  But doing that completely lost the example I was using to show you how to fix the lines that were a problem for you before (duh).

So...the parens are needed when combining some data with the result of a function.  You have to force the function to run first.  So in your original format, you would need parens like so:

$filecontent = ""
$filecontent = $filecontent + (Process-Folder -Path "C:\foo")
$filecontent + $filecontent + (Process-Folder -Path "C:\bar")

You can read all about it in this article

For the pipe, you need to set up a variable in your function which can accept input from the pipeline. I think this article does a really good job of explaining how to use the pipeline if you decide to take that route.

Hope this helps!


问:
How to set the value of a field when inserting the results of a MySQL query into a table
I have the following query that will insert its results into a table:

```<code>INSERT INTO search_results (rec_type, id, name)
SELECT user_id AS id, name
FROM organizations
WHERE name LIKE '%Smith%'
GROUP BY user_id
ORDER BY name
</code>```

How would I set the value of rec_type for all the records found, 'rec_type = "personel"', in this query or would I have to do a second query and use UPDATE to set the value of rec_type?

答:
Put the string in the SELECT list.

```<code>INSERT INTO search_results (rec_type, id, name)
SELECT 'personel' AS rec_type, user_id AS id, name
FROM organizations
WHERE name LIKE '%Smith%'
ORDER BY name
</code>```

There's no point in using GROUP BY when you're not using any aggregation functions (e.g. MAX(), COUNT(), SUM()). If there are duplicate results, use SELECT DISTINCT to suppress them.

Body:
I have the following query that will insert its results into a table:

INSERT INTO search_results (rec_type, id, name)
SELECT user_id AS id, name
FROM organizations
WHERE name LIKE '%Smith%'
GROUP BY user_id
ORDER BY name

How would I set the value of rec_type for all the records found, 'rec_type = "personel"', in this query or would I have to do a second query and use UPDATE to set the value of rec_type?

Body:
Put the string in the SELECT list.

INSERT INTO search_results (rec_type, id, name)
SELECT 'personel' AS rec_type, user_id AS id, name
FROM organizations
WHERE name LIKE '%Smith%'
ORDER BY name

There's no point in using GROUP BY when you're not using any aggregation functions (e.g. MAX(), COUNT(), SUM()). If there are duplicate results, use SELECT DISTINCT to suppress them.


问:
Slack Markdown for Links Are Not Resolving
What am I doing wrong? None of the example Markdown links work so far in my Slack app.

I pasted in the example below in a chat in my Slack app. I got this example from slack markdown syntax and it still treats it as literal text in the Slack App:

```<code>[like this](http://someurl)
</code>```

so I end up seeing that instead of just "like this" as a link in Slack chat.

Or maybe the above is wrong, in which case my question would then be how do you do explicitly create links in Slack? I want some text that I specify to be clickable to a specific URL (hyperlink).

答:
As of today, 2020.02.14, in one of the Slack instances I'm a member in, I can create/paste hyperlinks!

Example pasting hyperlink from copy Teams meeting info into Slack:

Slack has updated their documentation.  Still no markdown way of doing it though , i.e.  [blah](https://stackoverflow.com) doesn't work.

Neat feature, select some text and CTRL + V when a URL is on the clipboard and it creates a hyperlink

Through some reverse engineering I was able to put text on the Windows Clipboard via C# and get it to paste into Slack:

var textToDisplay = "Test";
var url = "https://stackoverflow.com";
var arbitraryText = "Mike D.";
var dataObject = new DataObject();
//to my surprise, the Fragment comments ARE required
dataObject.SetData(DataFormats.Html, @$"

    {textToDisplay}

    ");
//have to set the Text format too otherwise it won't work
dataObject.SetData(DataFormats.Text, arbitraryText);
Clipboard.SetDataObject(dataObject);
```

Body:
What am I doing wrong? None of the example Markdown links work so far in my Slack app.

I pasted in the example below in a chat in my Slack app. I got this example from slack markdown syntax and it still treats it as literal text in the Slack App:

[like this](http://someurl)

so I end up seeing that instead of just "like this" as a link in Slack chat.

Or maybe the above is wrong, in which case my question would then be how do you do explicitly create links in Slack? I want some text that I specify to be clickable to a specific URL (hyperlink).

Body:
As of today, 2020.02.14, in one of the Slack instances I'm a member in, I can create/paste hyperlinks!

Example pasting hyperlink from copy Teams meeting info into Slack:

Slack has updated their documentation.  Still no markdown way of doing it though , i.e.  [blah](https://stackoverflow.com) doesn't work.

Neat feature, select some text and CTRL + V when a URL is on the clipboard and it creates a hyperlink

Through some reverse engineering I was able to put text on the Windows Clipboard via C# and get it to paste into Slack:

var textToDisplay = "Test";
var url = "https://stackoverflow.com";
var arbitraryText = "Mike D.";
var dataObject = new DataObject();
//to my surprise, the Fragment comments ARE required
dataObject.SetData(DataFormats.Html, @$"<html><body>
    <!--StartFragment-->
    <a href=""{url}"">{textToDisplay}</a>
    <!--EndFragment-->
    </body></html>");
//have to set the Text format too otherwise it won't work
dataObject.SetData(DataFormats.Text, arbitraryText);
Clipboard.SetDataObject(dataObject);


问:
How to change color of pagination in bootstrap-vue?
I tried to change it with bootstrap examples but failed.</p>

```<code>        <b-pagination
            v-model="currentPage"
            :total-rows="users.length"
            :per-page="perPage"
            align="fill"
            size='lg'
            first-number
            last-number
            class="my-0"
        ></b-pagination>
</code>```

答:
Bootstrap-vue indeed is not so flexible when it comes to change to the default theme colors, but it is possible.

You first have to create a custom.scss file, where you can add new color themes to your bootstrap-vue.

On src/assets/styles/custom.scss:

```<code>// Override / set color variables
$myCustom: rgba(64, 206, 148, 1);
$primary: $myCustom;
</code>```

Note that on the example above all bootstrap elements - including pagination - without a variant set, will get the $myCustom color.

Then you have to import this file and the original scss bootstrap file on your root vue component:

```<code><style lang="scss">
 @import "./assets/styles/custom.scss";
 @import "../node_modules/bootstrap/scss/bootstrap.scss";
</style>
</code>```

On your code example, you pass the variant accordingly:

```<code><b-pagination
    v-model="currentPage"
    :total-rows="users.length"
    :per-page="perPage"
    align="fill"
    size='lg'
    first-number
    last-number
    class="my-0"
    variant="primary"
></b-pagination>
</code>```

In case you don't want to modify the default primary color, you can create a new variant on you custom.scss:

```<code>$theme-colors: ( "newVariant": rgba(0, 152, 152, 1));
</code>```

Hope it suits you well

Body:
Bootstrap-vue indeed is not so flexible when it comes to change to the default theme colors, but it is possible.

You first have to create a custom.scss file, where you can add new color themes to your bootstrap-vue.

On src/assets/styles/custom.scss:

// Override / set color variables
$myCustom: rgba(64, 206, 148, 1);
$primary: $myCustom;

Note that on the example above all bootstrap elements - including pagination - without a variant set, will get the $myCustom color.

Then you have to import this file and the original scss bootstrap file on your root vue component:

<style lang="scss">
 @import "./assets/styles/custom.scss";
 @import "../node_modules/bootstrap/scss/bootstrap.scss";
</style>

On your code example, you pass the variant accordingly:

<b-pagination
    v-model="currentPage"
    :total-rows="users.length"
    :per-page="perPage"
    align="fill"
    size='lg'
    first-number
    last-number
    class="my-0"
    variant="primary"
></b-pagination>

In case you don't want to modify the default primary color, you can create a new variant on you custom.scss:

$theme-colors: ( "newVariant": rgba(0, 152, 152, 1));

Hope it suits you well


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答: Ctrl+Click in IDE (NetBeans, PhpStorm) at function's name</p>