问:
PromptDialog error occurs in Messenger bot
I'm having an issue with a PromptDialog in my messenger bot, Whenever it reaches the prompt dialog it throws a "Bot Code has an Error". I've tried moving it around the code but it still throws it no matter where I put it, I've tried to place it into its own method and simply call the method and pass the context to it but again it didn't help.

I think it may be something in the LocationReceivedAsync however I'm not sure what.

```<code>[LuisIntent("Stores")]
public async Task Stores(IDialogContext context, LuisResult result)
{
    await StoreSearch(context);
}
private async Task StoreSearch(IDialogContext context)
{
    var reply = context.MakeMessage();
    reply.ChannelData = new FacebookMessage
    (
        text: "Please share your location with me.",
        quickReplies: new List<FacebookQuickReply>
        {
            new FacebookQuickReply(
                contentType: FacebookQuickReply.ContentTypes.Location,
                title: default(string),
                payload: default(string)
            )
        }
    );
    await context.PostAsync(reply);
    context.Wait(LocationReceivedAsync);
}
public virtual async Task LocationReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    var msg = await argument;
    var location = msg.Entities?.FirstOrDefault(e => e.Type == "Place");
    if (location != null)
    {
        latitude = location.Properties["geo"]?["latitude"]?.ToString();
        longitude = location.Properties["geo"]?["longitude"]?.ToString();
        LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
        int count = StoreLocations.Length;
        for (int z = 0; z < count; z++)
        {
            CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
            images.Add(Ci);

            HeroCard hc = new HeroCard()
            {
                Title = StoreLocations[z].StoreName,
                Subtitle = StoreLocations[z].Subtitle,
                Images = new List<CardImage> { images[z] },
                Buttons = new List<CardAction>()
            };

            CardAction ca = new CardAction()
            {
                Title = "Show Me",
                Type = "openUrl",
                Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
            };
            hc.Buttons.Add(ca);
            reply.Attachments.Add(hc.ToAttachment());
        }
        await context.PostAsync(reply);
        PromptDialog.Confirm(context, promtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
    }
    context.Done(location);
}
async Task promtDecision(IDialogContext context, IAwaitable<bool> userInput)
{
    bool inputText = await userInput;
    if (inputText)
    {
        RadiusPromt(context);
    }
    else
    {
        await mainMenu(context);
    }
}
</code>```

答:
There is an error in your implementation of LocationReceivedAsync: you should not put a context.Done(location) at the end of the method when you got a location. It should be on an else statement.

This context.Done is trying to complete the current dialog whereas you are still trying to do actions (in your case asking for a radius change).

Correction:

```<code>private async Task LocationReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    var msg = await argument;
    var location = msg.Entities?.FirstOrDefault(e => e.Type == "Place");
    if (location != null)
    {
        latitude = location.Properties["geo"]?["latitude"]?.ToString();
        longitude = location.Properties["geo"]?["longitude"]?.ToString();
        LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
        int count = StoreLocations.Length;
        for (int z = 0; z < count; z++)
        {
            CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
            images.Add(Ci);

            HeroCard hc = new HeroCard()
            {
                Title = StoreLocations[z].StoreName,
                Subtitle = StoreLocations[z].Subtitle,
                Images = new List<CardImage> { images[z] },
                Buttons = new List<CardAction>()
            };

            CardAction ca = new CardAction()
            {
                Title = "Show Me",
                Type = "openUrl",
                Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
            };
            hc.Buttons.Add(ca);
            reply.Attachments.Add(hc.ToAttachment());
        }
        await context.PostAsync(reply);
        PromptDialog.Confirm(context, PromtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
    }
    // Change is here
    else
    {
        context.Done(location);
    }
}
</code>```

Edit: one more point about your implementation. I don't understand why your "search and results display" code (around LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);...) is in the callback from Facebook prompt (LocationReceivedAsync) if you want to reuse it after the RadiusPrompt (implementation not visible here but I guess it's what you would like to do no?).

Maybe you should keep latitude and longitude setup in this method, and then call a new method that can also be called from your RadiusPrompt

ContentLicense: CC BY-SA 4.0

Body:
I'm having an issue with a PromptDialog in my messenger bot, Whenever it reaches the prompt dialog it throws a "Bot Code has an Error". I've tried moving it around the code but it still throws it no matter where I put it, I've tried to place it into its own method and simply call the method and pass the context to it but again it didn't help.

I think it may be something in the LocationReceivedAsync however I'm not sure what.

[LuisIntent("Stores")]
public async Task Stores(IDialogContext context, LuisResult result)
{
    await StoreSearch(context);
}
private async Task StoreSearch(IDialogContext context)
{
    var reply = context.MakeMessage();
    reply.ChannelData = new FacebookMessage
    (
        text: "Please share your location with me.",
        quickReplies: new List<FacebookQuickReply>
        {
            new FacebookQuickReply(
                contentType: FacebookQuickReply.ContentTypes.Location,
                title: default(string),
                payload: default(string)
            )
        }
    );
    await context.PostAsync(reply);
    context.Wait(LocationReceivedAsync);
}
public virtual async Task LocationReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    var msg = await argument;
    var location = msg.Entities?.FirstOrDefault(e => e.Type == "Place");
    if (location != null)
    {
        latitude = location.Properties["geo"]?["latitude"]?.ToString();
        longitude = location.Properties["geo"]?["longitude"]?.ToString();
        LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
        int count = StoreLocations.Length;
        for (int z = 0; z < count; z++)
        {
            CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
            images.Add(Ci);

            HeroCard hc = new HeroCard()
            {
                Title = StoreLocations[z].StoreName,
                Subtitle = StoreLocations[z].Subtitle,
                Images = new List<CardImage> { images[z] },
                Buttons = new List<CardAction>()
            };

            CardAction ca = new CardAction()
            {
                Title = "Show Me",
                Type = "openUrl",
                Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
            };
            hc.Buttons.Add(ca);
            reply.Attachments.Add(hc.ToAttachment());
        }
        await context.PostAsync(reply);
        PromptDialog.Confirm(context, promtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
    }
    context.Done(location);
}
async Task promtDecision(IDialogContext context, IAwaitable<bool> userInput)
{
    bool inputText = await userInput;
    if (inputText)
    {
        RadiusPromt(context);
    }
    else
    {
        await mainMenu(context);
    }
}

Body:
There is an error in your implementation of LocationReceivedAsync: you should not put a context.Done(location) at the end of the method when you got a location. It should be on an else statement.

This context.Done is trying to complete the current dialog whereas you are still trying to do actions (in your case asking for a radius change).

Correction:

private async Task LocationReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> argument)
{
    var reply = context.MakeMessage();
    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
    reply.Attachments = new List<Attachment>();
    List<CardImage> images = new List<CardImage>();

    InfoClass IC = new InfoClass();
    var msg = await argument;
    var location = msg.Entities?.FirstOrDefault(e => e.Type == "Place");
    if (location != null)
    {
        latitude = location.Properties["geo"]?["latitude"]?.ToString();
        longitude = location.Properties["geo"]?["longitude"]?.ToString();
        LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);
        int count = StoreLocations.Length;
        for (int z = 0; z < count; z++)
        {
            CardImage Ci = new CardImage("https://maps.googleapis.com/maps/api/staticmap?size=764x400&center=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude + "&zoom=15&markers=" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude);
            images.Add(Ci);

            HeroCard hc = new HeroCard()
            {
                Title = StoreLocations[z].StoreName,
                Subtitle = StoreLocations[z].Subtitle,
                Images = new List<CardImage> { images[z] },
                Buttons = new List<CardAction>()
            };

            CardAction ca = new CardAction()
            {
                Title = "Show Me",
                Type = "openUrl",
                Value = "https://www.google.co.za/maps/search/" + StoreLocations[z].Latitude + "," + StoreLocations[z].Longitude
            };
            hc.Buttons.Add(ca);
            reply.Attachments.Add(hc.ToAttachment());
        }
        await context.PostAsync(reply);
        PromptDialog.Confirm(context, PromtDecision, "Would You Like To Change The Search Radius ?", attempts: 100);
    }
    // Change is here
    else
    {
        context.Done(location);
    }
}

Edit: one more point about your implementation. I don't understand why your "search and results display" code (around LocationObject[] StoreLocations = IC.NearBy(latitude, longitude, Radius, context);...) is in the callback from Facebook prompt (LocationReceivedAsync) if you want to reuse it after the RadiusPrompt (implementation not visible here but I guess it's what you would like to do no?).

Maybe you should keep latitude and longitude setup in this method, and then call a new method that can also be called from your RadiusPrompt


来源: stackexchange

问:
Display a message when the cursor is ON the button (and disable the click)

JavaScript

```<code>    $(function(){
        $('.select-another-button').each(function(){
          $(this).bind('click', function(e){
            $('#message').show()
            setTimeout(function(){ $('#message').hide() }, 300000);
            e.preventDefault();
            fileBrowser(this);
            return false;
          });
        });
      });
</code>```

HTML

```<code> <a href="#"
        title="{% trans "Send email - rejected file(s)" %}"
        class="btn btn-icon select-another-button"
        data-url="{% url "messaging:send" request_id=object.pk %}">
        <i class="material-icons">assignment_late</i>
         <div class='alert alert-success' id='message'>
            The message was sent to the client. Please wait 5 minutes before sending the message again.
         </div>
    </a>
</code>```

Django

```<code>app_name = 'messaging'
urlpatterns = [
    ...

    url(r'^send/(?P<request_id>[0-9]+)/$',
        send, name='send'),
]
</code>```

and

```<code>@staff_member_required
@csrf_exempt
def send(request, request_id=None):
    req= Request.objects.get(pk=request_id)
    request_folders = req.folder.all_files.all()
    context = []

    for doc in request_folders:
        if doc.meta.state == u'rejected':
            context.append(doc)

    if context:
        ctx = {'request': req}
        EmailFromTemplate('document-refusal', extra_context=ctx)\
            .send_to(req.customer.user)

    return HttpResponse('')
</code>```

The purpose of this code is to create a button which will send a email under specific conditions. My weakness is probably with the HTML and the jS part. Once a user click the button, I want a delay of five minutes before he could send the message again. Hence, I have to desactivate the button for five minute once it is use and display the message : 'The message was sent to the client. Please wait 5 minutes before sending the message again.' when the cursor is ON the button. How could I modify the JS part so that it can do what I want?

Update

```<code>      <div class="title-actions">
        {% if not object.is_readonly %}
        {# TODO: apply perms #}
        <a href="#"
          id="id_select_request_document"
          title="{% trans "Select file(s)" %}"
          class="btn btn-icon select-button"
          data-turbolinks="false"
          data-save-label="{% trans "Ok" %}"
          data-close-label="{% trans "Cancel" %}"
          data-copy-to="{{ folder.pk }}"
          data-reload="true"
          data-url="{% url "documents:ajax-select" folder_id=object.customer.folder.pk %}">
          <i class="material-icons">folder</i>
        </a>
        {# TODO: apply perms #}
        {# if permissions.has_add_children_permission and not folder.is_root #}
        <a href="#"
          id="id_upload_request_document"
          title="{% trans "Upload file(s)" %}"
          class="btn btn-icon upload-button"
          data-turbolinks="false"
          data-url="{% url "documents:ajax-upload" folder_id=folder.pk %}"
          data-complete-post="{% url "requests:validate-requirements" pk=object.pk %}"
          data-max-uploader-connections="1">
          <i class="material-icons">cloud_upload</i>
        </a>
        <div class="wrapper">
            <div id="overlay"></div>
            <a href="#"
               title="{% trans "Send email - rejected file(s)" %}"
               class="btn btn-icon select-another-button"
               data-url="{% url "messaging:send" request_id=object.pk %}">
                <i class="material-icons">assignment_late</i>
                <div class='alert alert-success' id='send-message' style="display: none;">
                    <p>
                    The message was sent to the client. Please wait 5 minutes <br> before sending the message again.
                    </p>
                </div>
            </a>
        </div>
        {% endif %}
        {% if request.user.is_superuser %}
        <a href="{{ folder.get_admin_directory_listing_url_path }}" class="btn-icon"><i class="material-icons">settings</i></a>
        {% endif %}
      </div>
</code>```

Before modifications, I got right display, but now I have wrong display.

I don't know if it is good, but I put the following block at the top of my .html file.

```<code><script type="text/css">

    .wrapper{
      position: relative;
      display: inline-block;
    }
    #overlay{
      display: none;
      position: absolute;
      top: 0;
      left: 0;
      opacity: .1;
      background-color: blue;
      height: 100%;
      width: 100%;
    }
</code>```

CSS

```<code>.title-actions {
  float: right;
  height: 50px;
  margin-top: 13px; }
  .title-actions a {
    transition: background 0.3s ease; }
    .title-actions a.btn {
      padding: 2px 14px;
      line-height: 26px;
      max-height: 28px;
      position: relative;
      top: -1px;
      margin-left: 8px; }
    .title-actions a:hover {
      background: #4382b5; }
  .title-actions span {
    color: #444;
    background: #e6e6e6;
    padding: 6px 10px;
    border-radius: 3px;
    float: none;
    position: relative;
    margin-left: 6px; }
  .title-actions .btn {
    padding: 2px 14px;
    line-height: 26px;
    max-height: 28px;
    position: relative;
    top: -1px;
    margin-left: 8px; }
  .title-actions .btn-icon {
    background: transparent;
    position: relative;
    color: #3e5366;
    text-align: center;
    display: inline-block;
    padding: 0 !important;
    transition: color 0.3s ease;
    box-shadow: none !important;
    margin-top: -16px;
    margin-left: 6px; }
    .title-actions .btn-icon i {
      font-size: 35px;
      line-height: 20px;
      position: relative;
      top: 12px; }
    .title-actions .btn-icon:hover {
      color: #4382b5;
      background: transparent; }
  .title-actions .badge .material-icons {
    font-size: 1.2em;
    line-height: 0;
    position: relative;
    top: 4px; }
</code>```

答:
You need to do a lot of changes to your code. Assuming you have only 1 element with an id="message".

Starting from your JQuery code.

```<code>$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});
</code>```

Since a disabled button cannot have hover events on it, you need to put a transparent overlay over the button & show the #message on its hover.

HTML

```<code><div class="wrapper">
  <div id="overlay"></div>
  <a href="#"
     title="{% trans "Send email - rejected file(s)" %}"
     class="btn btn-icon select-another-button"
     data-url="{% url "messaging:send" request_id=object.pk %}">
    <i class="material-icons">assignment_late</i>
    <div class='alert alert-success' id='message' style="display: none;">
    The message was sent to the client. Please wait 5 minutes before sending the message again.
    </div>
  </a>
</div>
</code>```

And ofcourse the CSS change to make sure the overlay is placed properly over the button which will be later disabled.

```<code>.wrapper{
  position: relative;
  display: inline-block;
}
#overlay{
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  opacity: .1;
  height: 100%;
  width: 100%;
}
</code>```

$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true');
      $('#overlay').show();
      setTimeout(function(){
        $(this).attr('disabled','false');
        $('#overlay').hide();
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{
  position: relative;
  display: inline-block;
}
#overlay{
   display: none;
    position: absolute;
    top: 0;
    left: 0;
    opacity: .1;
    height: 100%;
    width: 100%;
}</code>```

    assignment_late

    The message was sent to the client. Please wait 5 minutes before sending the message again.

```

ContentLicense: CC BY-SA 3.0

Body:
JavaScript

    $(function(){
        $('.select-another-button').each(function(){
          $(this).bind('click', function(e){
            $('#message').show()
            setTimeout(function(){ $('#message').hide() }, 300000);
            e.preventDefault();
            fileBrowser(this);
            return false;
          });
        });
      });

HTML

        assignment_late

            The message was sent to the client. Please wait 5 minutes before sending the message again.

Django

app_name = 'messaging'
urlpatterns = [
    ...

    url(r'^send/(?P<request_id>[0-9]+)/$',
        send, name='send'),
]

and

@staff_member_required
@csrf_exempt
def send(request, request_id=None):
    req= Request.objects.get(pk=request_id)
    request_folders = req.folder.all_files.all()
    context = []

    for doc in request_folders:
        if doc.meta.state == u'rejected':
            context.append(doc)

    if context:
        ctx = {'request': req}
        EmailFromTemplate('document-refusal', extra_context=ctx)\
            .send_to(req.customer.user)

    return HttpResponse('')

The purpose of this code is to create a button which will send a email under specific conditions. My weakness is probably with the HTML and the jS part. Once a user click the button, I want a delay of five minutes before he could send the message again. Hence, I have to desactivate the button for five minute once it is use and display the message : 'The message was sent to the client. Please wait 5 minutes before sending the message again.' when the cursor is ON the button. How could I modify the JS part so that it can do what I want?

Update

        {% if not object.is_readonly %}
        {# TODO: apply perms #}

          folder

        {# TODO: apply perms #}
        {# if permissions.has_add_children_permission and not folder.is_root #}

          cloud_upload

                assignment_late

                    The message was sent to the client. Please wait 5 minutes
 before sending the message again.

        {% endif %}
        {% if request.user.is_superuser %}
        settings
        {% endif %}

Before modifications, I got right display, but now I have wrong display.

I don't know if it is good, but I put the following block at the top of my .html file.

Body:
You need to do a lot of changes to your code. Assuming you have only 1 element with an id="message".

Starting from your JQuery code.

$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true'); //disables the button
      $('#overlay').show(); //after disabling show the overlay for hover
      setTimeout(function(){
        $(this).attr('disabled','false'); //enables after 5mins
        $('#overlay').hide(); //hide the overlay
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});

Since a disabled button cannot have hover events on it, you need to put a transparent overlay over the button & show the #message on its hover.

HTML

<div class="wrapper">
  <div id="overlay"></div>
  <a href="#"
     title="{% trans "Send email - rejected file(s)" %}"
     class="btn btn-icon select-another-button"
     data-url="{% url "messaging:send" request_id=object.pk %}">
    <i class="material-icons">assignment_late</i>
    <div class='alert alert-success' id='message' style="display: none;">
    The message was sent to the client. Please wait 5 minutes before sending the message again.
    </div>
  </a>
</div>

And ofcourse the CSS change to make sure the overlay is placed properly over the button which will be later disabled.

.wrapper{
  position: relative;
  display: inline-block;
}
#overlay{
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  opacity: .1;
  height: 100%;
  width: 100%;
}

$(function(){
  $('.select-another-button').each(function(){
    $(this).bind('click', function(e) {
      $(this).attr('disabled','true');
      $('#overlay').show();
      setTimeout(function(){
        $(this).attr('disabled','false');
        $('#overlay').hide();
      }, 300000);
      e.preventDefault();
      fileBrowser(this);
      return false;
    });
  });
});

$("#overlay").hover(function(){
    $('#message').show();
},function(){
    $('#message').hide();
});

.wrapper{
  position: relative;
  display: inline-block;
}
#overlay{
   display: none;
    position: absolute;
    top: 0;
    left: 0;
    opacity: .1;
    height: 100%;
    width: 100%;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div id="overlay"></div>
  <a href="#"
     title="{% trans "Send email - rejected file(s)" %}"
     class="btn btn-icon select-another-button"
     data-url="{% url "messaging:send" request_id=object.pk %}">
    <i class="material-icons">assignment_late</i>
    <div class='alert alert-success' id='message' style="display: none;">
    The message was sent to the client. Please wait 5 minutes before sending the message again.
    </div>
  </a>
</div>


问:
How to access data form in put request of class based views in django
I am currently having a problem with accessing my data stored in a data form. I'm passing it through ajax and its received by the put method in views.py. The problem is I only know how to access it through request.POST["item_name"] and for file request.FILES["photo"]. But apparently this doesnt work in put request. Can anyone please help?

jQuery

```<code>const form = new FormData();
const name = $('#edit-product-name-input-' + productID).val();
const quantity = $('#edit-product-quantity-input-' + productID).val();
const description = $('#edit-product-description-input-' + productID).val();
const price = $('#edit-product-price-input-' + productID).val();
const photo = $('#edit-product-photo-' + productID);

if (extractPhoto(photo)) {
    form.append('photo', extractPhoto(photo));
}
form.append('name', name);
form.append('price', price);
form.append('description', description);
form.append('quantity', quantity);
form.append('product_id', productID);

attachCSRF();
$.ajax({
    url: window.location.pathname + "products/",
    method: "PUT",
    data: form,
    contentType: false,
    processData: false,
    success: function (data) {
        alert(data["product"] + " edited");
        location.reload();
    },
    error: function (data) {
        if (data.responseJSON) {
            displayErrors(data.responseJSON);
        }
    }
</code>```

views.py

```<code>@staticmethod
def put(request, stall_id):
    dict = {
        "product_name": request.body('name'),
        "description": request.body('description'),
        "price": request.body('price'),
        "quantity": request.body('quantity')
    }
    errors = handle_errors(dict)
    print(errors)

    if not errors:
        product = Product.objects.get(id=request.POST.get("product_id"))
        product.name = dict["product_name"]
        product.description = dict["description"]
        product.price = dict["price"]
        product.quantity = dict["quantity"]
        if 'photo' in request.FILES:
            product.photo = request.FILES.get('photo')
        product.save()

        data = {
            "product": product.name
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    return HttpResponse(
        json.dumps(errors),
        content_type="application/json",
        status=400
    )
</code>```

答:
It looks like when sending data via x-www-form-urlencoded it arrives in under the request.body as bytes.

** Don't use the csrf_exempt in your code I just used that for testing purposes.**

The below works for me:

```<code>from django.http import QueryDict

class Some(View):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, *kwargs)

    def put(self, request, *args, **kwargs):
        data = QueryDict(request.body)
        print(data)
        return HttpResponse("Worked!")
</code>```

The data variable is a dict so you can do this inside your put:

```<code>form = {
    "product_name": data.get('name'),
    "description": data.get('description'),
    "price": data.get('price'),
    "quantity": data.get('quantity')
}
</code>```

Body:
I am currently having a problem with accessing my data stored in a data form. I'm passing it through ajax and its received by the put method in views.py. The problem is I only know how to access it through request.POST["item_name"] and for file request.FILES["photo"]. But apparently this doesnt work in put request. Can anyone please help?

jQuery

const form = new FormData();
const name = $('#edit-product-name-input-' + productID).val();
const quantity = $('#edit-product-quantity-input-' + productID).val();
const description = $('#edit-product-description-input-' + productID).val();
const price = $('#edit-product-price-input-' + productID).val();
const photo = $('#edit-product-photo-' + productID);

if (extractPhoto(photo)) {
    form.append('photo', extractPhoto(photo));
}
form.append('name', name);
form.append('price', price);
form.append('description', description);
form.append('quantity', quantity);
form.append('product_id', productID);

attachCSRF();
$.ajax({
    url: window.location.pathname + "products/",
    method: "PUT",
    data: form,
    contentType: false,
    processData: false,
    success: function (data) {
        alert(data["product"] + " edited");
        location.reload();
    },
    error: function (data) {
        if (data.responseJSON) {
            displayErrors(data.responseJSON);
        }
    }

views.py

@staticmethod
def put(request, stall_id):
    dict = {
        "product_name": request.body('name'),
        "description": request.body('description'),
        "price": request.body('price'),
        "quantity": request.body('quantity')
    }
    errors = handle_errors(dict)
    print(errors)

    if not errors:
        product = Product.objects.get(id=request.POST.get("product_id"))
        product.name = dict["product_name"]
        product.description = dict["description"]
        product.price = dict["price"]
        product.quantity = dict["quantity"]
        if 'photo' in request.FILES:
            product.photo = request.FILES.get('photo')
        product.save()

        data = {
            "product": product.name
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    return HttpResponse(
        json.dumps(errors),
        content_type="application/json",
        status=400
    )

Body:
It looks like when sending data via x-www-form-urlencoded it arrives in under the request.body as bytes.

** Don't use the csrf_exempt in your code I just used that for testing purposes.**

The below works for me:

from django.http import QueryDict

class Some(View):
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, *kwargs)

    def put(self, request, *args, **kwargs):
        data = QueryDict(request.body)
        print(data)
        return HttpResponse("Worked!")

The data variable is a dict so you can do this inside your put:

form = {
    "product_name": data.get('name'),
    "description": data.get('description'),
    "price": data.get('price'),
    "quantity": data.get('quantity')
}


问:
Is it possible to add a remote with GitHub API?
Is it possible to add a remote with GitHub API same as git remote add upstream <repository URL>? I have read the docs but I can not find the way.

ref

- How to update a fork from it's original via the Github API

Thanks in advance.

答:
```<code># Get original hash
curl "https://api.github.com/repos/:original/:repo/git/refs/heads/master"

# Follow upstrem change
curl -X POST \
     -H "Authorization: token <TOKEN>" \
     --data '{"base":"<fork/BRANCH>","head":"<original/HASH>"}' \
     "https://api.github.com/repos/:fork/:repo/test_project/merges"
</code>```


问:
Alembic support for multiple Postgres schemas
How can I use Alembic's --autogenerate to migrate multiple Postgres schemas that are not hard-coded in the SQL Alchemy model? (mirror question of SQLAlchemy support of Postgres Schemas, but for Alembic).

In particular, we use Postgres schemas to seperate different clients that share the same set of tables. Moreover, there is a schema with shared stuff among clients. The SQL Alchemy model has no knowledge of schemas, the schema is set at run-time using session.execute("SET search_path TO client1,shared").

The default --autogenerate is not helping at all, as it is detecting multiple schemas that do not exist in the model and ends up deleting the schemas and re-creating every table in the default schema.

I would really like to use --autogenerate though, with the proper plumbing to set the schemas correctly. Any suggestions on if/how Alembic's API can do this?

答:
from issue 409, the application to tenant-specific schemas of upgrade/downgrade operations can most easily be done using translated schema names, which is also how you would normally be doing the main application as well for multi-tenant.

Go into env.py:

```<code>def run_migrations_online():

    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    with connectable.connect() as connection:
        for tenant_schema_name in all_my_tenant_names:
             conn = connection.execution_options(schema_translate_map={None: tenant_schema_name}

            logger.info("Migrating tenant schema %s" % tenant_schema_name)
            context.configure(
                connection=conn,
                target_metadata=target_metadata
            )

            # to do each tenant in its own transaction.
            # move this up to do all tenants in one giant transaction
            with context.begin_transaction():
                context.run_migrations()
</code>```

Above will translate the "None" schema name into the given tenant name.    If the application shares tenant-based schemas with a default schema that has global tables, then you'd be using some token like "tenant_schema" as the symbol:

```<code>for tenant_schema_name in all_my_tenant_names:
     conn = connection.execution_options(schema_translate_map={"tenant_schema": tenant_schema_name}
</code>```

and in migration files refer to "tenant_schema" where the actual tenant-specific schema name goes:

```<code>def upgrade():
    op.alter_column("some_table", "some_column", <migration options>, schema="tenant_schema")
</code>```

For the "autogenerate" case, the solution @nick-retallack provides has some more of the pieces you would use on that end, namely the use of include_schemas so that autogenerate looks only at a "specimen" schema that represents the latest version of the tenant-specific schema.

In order to set up env.py to use the right system for the right command, the behaviors can be controlled using user-defined options with migration_context.get_x_argument().

Body:
from issue 409, the application to tenant-specific schemas of upgrade/downgrade operations can most easily be done using translated schema names, which is also how you would normally be doing the main application as well for multi-tenant.

Go into env.py:

def run_migrations_online():

    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix='sqlalchemy.',
        poolclass=pool.NullPool)

    with connectable.connect() as connection:
        for tenant_schema_name in all_my_tenant_names:
             conn = connection.execution_options(schema_translate_map={None: tenant_schema_name}

            logger.info("Migrating tenant schema %s" % tenant_schema_name)
            context.configure(
                connection=conn,
                target_metadata=target_metadata
            )

            # to do each tenant in its own transaction.
            # move this up to do all tenants in one giant transaction
            with context.begin_transaction():
                context.run_migrations()

Above will translate the "None" schema name into the given tenant name.    If the application shares tenant-based schemas with a default schema that has global tables, then you'd be using some token like "tenant_schema" as the symbol:

for tenant_schema_name in all_my_tenant_names:
     conn = connection.execution_options(schema_translate_map={"tenant_schema": tenant_schema_name}

and in migration files refer to "tenant_schema" where the actual tenant-specific schema name goes:

def upgrade():
    op.alter_column("some_table", "some_column", <migration options>, schema="tenant_schema")

For the "autogenerate" case, the solution @nick-retallack provides has some more of the pieces you would use on that end, namely the use of include_schemas so that autogenerate looks only at a "specimen" schema that represents the latest version of the tenant-specific schema.

In order to set up env.py to use the right system for the right command, the behaviors can be controlled using user-defined options with migration_context.get_x_argument().


问:
How to disable/hide woocommerce single product page?
I am trying to hide the single product detail page on my wordpress-woocommerce site. How can i achieve this without breaking woocommerce functionality?</p>

答:
Put it in functions.php</p>

```<code>//Removes links
add_filter( 'woocommerce_product_is_visible','product_invisible');
function product_invisible(){
    return false;
}

//Remove single page
add_filter( 'woocommerce_register_post_type_product','hide_product_page',12,1);
function hide_product_page($args){
    $args["publicly_queryable"]=false;
    $args["public"]=false;
    return $args;
}
</code>```

Body:
Put it in functions.php

//Removes links
add_filter( 'woocommerce_product_is_visible','product_invisible');
function product_invisible(){
    return false;
}

//Remove single page
add_filter( 'woocommerce_register_post_type_product','hide_product_page',12,1);
function hide_product_page($args){
    $args["publicly_queryable"]=false;
    $args["public"]=false;
    return $args;
}


问:
JVM can't find class when using JNI from C++
I'm trying to call JAVA methods from C++ by JNI. First of all, I got this example, tried it out. I changed the path of JDK and after that I could run the examples and they properly worked.

After that, I tried to import my own JAR file and use one class from it. I copied the code from the example and replaced the classpath and classname with my own:

```<code>void MyCPPClass::CallJava()
{
    JavaVM *jvm;                // Pointer to the JVM (Java Virtual Machine)
    JNIEnv *env;                // Pointer to native interface

    //==================== prepare loading of Java VM ============================

    JavaVMInitArgs vm_args;                        // Initialization arguments
    JavaVMOption* options = new JavaVMOption[ 1 ];   // JVM invocation options
    options[ 0 ].optionString = "-Djava.class.path=MyJar.jar";   // where to find java .class
    vm_args.version = JNI_VERSION_1_8;             // minimum Java version
    vm_args.nOptions = 1;                          // number of options
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;     // invalid options make the JVM init fail

    //================= load and initialize Java VM and JNI interface ===============

    jint rc = JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args );  // YES !!
    delete options;    // we then no longer need the initialisation options.

    //========================= analyse errors if any  ==============================
    // if process interuped before error is returned, it's because jvm.dll can't be
    // found, i.e.  its directory is not in the PATH.

    if( rc != JNI_OK )
    {
        exit( EXIT_FAILURE );
    }

    jclass cls1 = env->FindClass( "aaa/bbb/MyClass" );
    ...
}
</code>```

The JAR contains only one class aaa.bbb.MyClass and it's made with IntelliJ IDEA and mvn package command. I copied the JAR file next to my executable.

A value of rc is always 0 (JNI_OK), but the value of cls1 is always NULL. I think that JVM can find the JAR, because when I'm debugging I can't delete the JAR after FindClass.

The JAR file contains the MyClass.class file, I checked it.

I have checked some previous questions ( 1, 2, 3 and some others) yet, but I couldn't get where I made a mistake.

UPDATE: I tried to copy the MyClass.class file and MyJar.jar file into the directory of the example linked before, and JVM can't find MyClass. It's possible that something missing from my java source file? The package declaration is correct.

What can cause that JVM can't find MyClass?

答:
Moved solution from question to answer:

SOLUTION: I had to add the maven dependencies' JARs to the classpath. Now it works!

Body:
I'm trying to call JAVA methods from C++ by JNI. First of all, I got this example, tried it out. I changed the path of JDK and after that I could run the examples and they properly worked.

After that, I tried to import my own JAR file and use one class from it. I copied the code from the example and replaced the classpath and classname with my own:

void MyCPPClass::CallJava()
{
    JavaVM *jvm;                // Pointer to the JVM (Java Virtual Machine)
    JNIEnv *env;                // Pointer to native interface

    //==================== prepare loading of Java VM ============================

    JavaVMInitArgs vm_args;                        // Initialization arguments
    JavaVMOption* options = new JavaVMOption[ 1 ];   // JVM invocation options
    options[ 0 ].optionString = "-Djava.class.path=MyJar.jar";   // where to find java .class
    vm_args.version = JNI_VERSION_1_8;             // minimum Java version
    vm_args.nOptions = 1;                          // number of options
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;     // invalid options make the JVM init fail

    //================= load and initialize Java VM and JNI interface ===============

    jint rc = JNI_CreateJavaVM( &jvm, (void**)&env, &vm_args );  // YES !!
    delete options;    // we then no longer need the initialisation options.

    //========================= analyse errors if any  ==============================
    // if process interuped before error is returned, it's because jvm.dll can't be
    // found, i.e.  its directory is not in the PATH.

    if( rc != JNI_OK )
    {
        exit( EXIT_FAILURE );
    }

    jclass cls1 = env->FindClass( "aaa/bbb/MyClass" );
    ...
}

The JAR contains only one class aaa.bbb.MyClass and it's made with IntelliJ IDEA and mvn package command. I copied the JAR file next to my executable.

A value of rc is always 0 (JNI_OK), but the value of cls1 is always NULL. I think that JVM can find the JAR, because when I'm debugging I can't delete the JAR after FindClass.

The JAR file contains the MyClass.class file, I checked it.

I have checked some previous questions ( 1, 2, 3 and some others) yet, but I couldn't get where I made a mistake.

UPDATE: I tried to copy the MyClass.class file and MyJar.jar file into the directory of the example linked before, and JVM can't find MyClass. It's possible that something missing from my java source file? The package declaration is correct.

What can cause that JVM can't find MyClass?


问:
Test value between x and y
I have two data.frames, one with the value "size" to test and the other has the interval N1 to N2 to test. If it's the case, so it will print TRUE into a new column "test"

答:
Here is a solution using data.table's non-equi join:

```<code>library(data.table)

setDT(Df1)
setDT(Df2)

Df1[, test := FALSE]

Df1[Df2, test := TRUE, on = .(ID, size >= N1, size <= N2)]
# > Df1
#    size  ID  test
# 1:  399 ID1  TRUE
# 2:  887 ID2  TRUE
# 3:  350 ID1  TRUE
# 4: 1400 ID2 FALSE
# 5: 1455 ID2 FALSE
# 6: 1700 ID2 FALSE
# 7: 1654 ID1 FALSE
# 8:  928 ID1 FALSE
# 9: 1228 ID1  TRUE
</code>```

Title: Test value between x and y

Body:
Here is a solution using data.table's non-equi join:

library(data.table)

setDT(Df1)
setDT(Df2)

Df1[, test := FALSE]

Df1[Df2, test := TRUE, on = .(ID, size >= N1, size <= N2)]
# > Df1
#    size  ID  test
# 1:  399 ID1  TRUE
# 2:  887 ID2  TRUE
# 3:  350 ID1  TRUE
# 4: 1400 ID2 FALSE
# 5: 1455 ID2 FALSE
# 6: 1700 ID2 FALSE
# 7: 1654 ID1 FALSE
# 8:  928 ID1 FALSE
# 9: 1228 ID1  TRUE


问:
DOMContentLoaded event firing twice for a single page load
I authored a Firefox add-on several months ago that recently failed. The add-on basically looks for a particular URL and then modifies the DOM for the page.  I traced the failure to the (accidental) installation of the "AVG Safe Search" add-on.  I found that, with the AVG add-on disabled, the DOMContentLoaded event fires once for the document (behavior I originally expected), but with it enabled, the DOMContentLoaded event fires twice for the document.  My add-on inserts a column into an HTML table, so because the event fires twice, two duplicate columns are inserted rather than one.

Here's the distilled initialization code of my add-on:

```<code>var hLoadListener = function(event) { myAddon.initialize(event); }
var hContentLoadedListener = function(event) { myAddon.onContentLoaded(event); }

myAddon.initialize = function(aEvent)
{
    gBrowser.addEventListener("DOMContentLoaded", hContentLoadedListener, false);
};

myAddon.onContentLoaded = function(aEvent)
{
    if (!(aEvent.originalTarget.nodeName === "#document")) { return; }

    var doc = aEvent.target; // document that triggered "onload" event

    if (!(doc instanceof HTMLDocument)) { return; }
    if (!doc.location) { return; }

    var href = doc.location.href; // URL of current page

    if (URLRegExp.test(href))
    {
      // Modify the page's DOM
    }
};

window.addEventListener("load", hLoadListener, false);
</code>```

This issue seems easy to fix by inserting a unique DOM element and then testing for it's existence at the start. My question is whether add-on developers should expect this event behavior as normal or whether this issue is primarily a bug/side-effect in the AVG add-on?

答:
Try to read bindReady method of jquery :

https://github.com/jquery/jquery/blob/master/src/core.js

You will find:

```<code>if ( readyBound ) {
 return;
}
readyBound = true;

// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I authored a Firefox add-on several months ago that recently failed. The add-on basically looks for a particular URL and then modifies the DOM for the page.  I traced the failure to the (accidental) installation of the "AVG Safe Search" add-on.  I found that, with the AVG add-on disabled, the DOMContentLoaded event fires once for the document (behavior I originally expected), but with it enabled, the DOMContentLoaded event fires twice for the document.  My add-on inserts a column into an HTML table, so because the event fires twice, two duplicate columns are inserted rather than one.

Here's the distilled initialization code of my add-on:

var hLoadListener = function(event) { myAddon.initialize(event); }
var hContentLoadedListener = function(event) { myAddon.onContentLoaded(event); }

myAddon.initialize = function(aEvent)
{
    gBrowser.addEventListener("DOMContentLoaded", hContentLoadedListener, false);
};

myAddon.onContentLoaded = function(aEvent)
{
    if (!(aEvent.originalTarget.nodeName === "#document")) { return; }

    var doc = aEvent.target; // document that triggered "onload" event

    if (!(doc instanceof HTMLDocument)) { return; }
    if (!doc.location) { return; }

    var href = doc.location.href; // URL of current page

    if (URLRegExp.test(href))
    {
      // Modify the page's DOM
    }
};

window.addEventListener("load", hLoadListener, false);

This issue seems easy to fix by inserting a unique DOM element and then testing for it's existence at the start. My question is whether add-on developers should expect this event behavior as normal or whether this issue is primarily a bug/side-effect in the AVG add-on?

Body:
Try to read bindReady method of jquery :

https://github.com/jquery/jquery/blob/master/src/core.js

You will find:

if ( readyBound ) {
 return;
}
readyBound = true;

// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );


问:
Query String Parameter Being Lost on Request
i'm developing an MVC 4 web application.

I'm trying to make an url that changes in an authorized/unauthorized context.

I'm generating the following url for unauthorized user:

http://localhost/vendas-web/Login?ReturnUrl=%2Fvendas-web%2FClienteNovo%2FIndex%299999

The first time I've tested, it worked just fine.

But.. the second time I've tried, the query string got lost.. and the url turned into:

http://localhost/vendas-web/Login

When i test it against chrome on anonymous tab, it works FINE.
When i change the value of the last parameter, it works FINE.

There's some sort of cache related to this ?

What i'm doing wrong ?

Soo, my question is:

How do i keep my full url in any scenario ??

Ty

答:
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:

```<code>@Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })
</code>```

And any forms must include it as a hidden input:

```<code>@Html.Hidden("ReturnUrl", Request["ReturnUrl"])
</code>```

Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.

Body:
There's really not enough information here, but what you're likely talking about is that the first time a user needs to be authorized, they are automatically redirected to the first URL, which includes the ReturnUrl bit. That's built into the framework to allow the user to be redirected back to that URL after logging in. However, if you need to persist this past that initial first redirect to the login page, that's on you. Any links must manually add the query string param:

@Url.Action("SomeAction", new { ReturnUrl = Request["ReturnUrl"] })

And any forms must include it as a hidden input:

@Html.Hidden("ReturnUrl", Request["ReturnUrl"])

Otherwise, yes, it will be lost, because the literal URL you're now requesting doesn't include it. It's not just magically appended.


问:
In Django ORM, how does one get_or_create for values in JSONField?
I am having a Django model like:

```<code>class Subscription(models.Model):
    data = JSONField(default=dict)
</code>```

I want to do something like this:

```<code>data = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data__product_id=123,
data__available=False)
</code>```

I tried doing the above but it just set the field as empty dictionary.

答:
Try this:-</p>

```<code>models.py :-
class Subscription(models.Model):
    data = JSONField(db_index=True,null=True)

views.py:-
DictToStore = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data=DictToStore)
</code>```

Body:
I am having a Django model like:

class Subscription(models.Model):
    data = JSONField(default=dict)

I want to do something like this:

data = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data__product_id=123,
data__available=False)

I tried doing the above but it just set the field as empty dictionary.

Body:
Try this:-

models.py :-
class Subscription(models.Model):
    data = JSONField(db_index=True,null=True)

views.py:-
DictToStore = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data=DictToStore)


问:
Difference between [] and [[]] in numpy
Can anyone pleas tell what's difference between (if a is some numppy object, lets say:array) a[1] and a[[1]]. If I understand correctly I can edit 1 element of a with a[[1]], but not with a[1]...any other difference? Is it also something like  that with [] I just view some element(s) and with [[]] I make copy?
If it's to any importance I'm using python 3.</p>

答:
When you say a[1] you are getting the element with index 1 (the second one) from a. a[[1]], on the other hand, is not a special syntax, it just means "get the elements of a indicated by the indices in the list [1]". You can also say a[[1, 2]], or use another array as index. The practical difference is that a[1] will be a single scalar element and a[[1]] will be an array with size 1 (assuming a had one dimension).

With respect to assignment, you will find that both a[1] = 2 and a[[1]] = 2 work equally well. This is because of NumPy's broadcasting semantics, which allow you to match objects of different dimensions seamlessly. However, the actual dimensions of a[1] and a[[1]] are different, and it does matter depending on the context.

You can read more about indexing in NumPy here.

Title: Difference between [] and [[]] in numpy


问:
can i create ImageView programmatically before setcontentview android
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

```<code>MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);
</code>```

and in that class constructor i have to use that context to initialize my preference class

```<code>public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }
</code>```

Here is my logcat of error that i am facing

```<code>07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

答: Is the MyInAppPurchaseBilling object created while still executing the constructor of the MenuClass.this object? In this case (and maybe until onCreate() is called on MenuClass.this, but i'm not sure about this) the context inside the Activity object (in this case said MenuClass.this) is not set yet.

Body:
can i initialize ImageView or any other view programmatically before setContentView(R.layout.activity_main); in android??

actually i am getting an instance of a custom class (not activity)
before onCreate method globally
like this

MyInAppPurchaseBilling myInAppPurchaseBilling = new MyInAppPurchaseBilling(MenuClass.this);

and in that class constructor i have to use that context to initialize my preference class

public MyInAppPurchaseBilling(Activity launcher) {
        this.activity = launcher;
        tinyDB= new TinyDB(launcher);
    }

Here is my logcat of error that i am facing

07-05 17:22:01.852 9660-9660/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.write.urdu.poetry.urdutexteditor, PID: 9660
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.write.urdu.poetry.urdutexteditor/com.write.urdu.poetry.urdutexteditor.MenuClass}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
    at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
    at com.write.urdu.poetry.urdutexteditor.TinyDB.<init>(TinyDB.java:55)
    at com.write.urdu.poetry.urdutexteditor.inapppurchase.MyInAppPurchaseBilling.<init>(MyInAppPurchaseBilling.java:48)
    at com.write.urdu.poetry.urdutexteditor.MenuClass.<init>(MenuClass.java:38)
    at java.lang.Class.newInstance(Native Method)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
    at android.app.ActivityThread.access$900(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5551)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)


问:
How can I have infinite nested list in CSS to be uniquely styled?
For example these codes.

```<code>.sidebar-nav .metismenu ul a {
    padding: 10px 15px 10px 30px;
}
.sidebar-nav .metismenu ul ul a {
    padding: 10px 15px 10px 45px;
}
</code>```

I want for additional (any amount)
 to have additional 15px in left padding. How can I achieve this instead of manually type it?

答:
From what I understand of your question, you want each nested-list to be indented further than the parent?

Here I have placed the padding on the ul. This will indent each list 15px relative to its parent.

.sidebar-nav .metismenu {
  position: relative;
}

.sidebar-nav .metismenu ul {
  padding-left: 15px;
}

.sidebar-nav .metismenu ul a {
  padding: 10px 15px 10px 0;
  display: block;
  width: 100%;
  color: #ADB5BD;
  cursor: pointer;
}

.sidebar-nav .metismenu ul a:hover {
  color: #F8F9FA;
}

.sidebar-nav .metismenu ul a:before {
  content: "";
  opacity: 0;
  transition: 0.3s opacity ease-out;
}

.sidebar-nav .metismenu ul a:hover:before {
  position: absolute;
  left: 0;
  width: 100%;
  background: #0B7285;
  height: 3em;
  z-index: -1;
  opacity: 1;
  transition: 0.3s opacity ease-out, 0.3s color ease-out;
  transform: translateY(-1em);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar-nav">
  <div class="metismenu">
    <ul>
      <li><a>Item 1</a>
        <ul>
          <li><a>Sub-item</a></li>
        </ul>
      </li>
      <li><a>Item 2</a></li>
      <li><a>Item 3</a>
        <ul>
          <li><a>Sub-item</a></li>
          <li><a>Sub-item</a>
            <ul>
              <li><a>Sub-subitem</a></li>
              <li><a>Sub-subitem</a></li>
              <li><a>Sub-subitem</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div></code>```

Body:
For example these codes.

.sidebar-nav .metismenu ul a {
    padding: 10px 15px 10px 30px;
}
.sidebar-nav .metismenu ul ul a {
    padding: 10px 15px 10px 45px;
}

I want for additional (any amount)
 to have additional 15px in left padding. How can I achieve this instead of manually type it?

Body:
From what I understand of your question, you want each nested-list to be indented further than the parent?

Here I have placed the padding on the ul. This will indent each list 15px relative to its parent.

.sidebar-nav .metismenu {
  position: relative;
}

.sidebar-nav .metismenu ul {
  padding-left: 15px;
}

.sidebar-nav .metismenu ul a {
  padding: 10px 15px 10px 0;
  display: block;
  width: 100%;
  color: #ADB5BD;
  cursor: pointer;
}

.sidebar-nav .metismenu ul a:hover {
  color: #F8F9FA;
}

.sidebar-nav .metismenu ul a:before {
  content: "";
  opacity: 0;
  transition: 0.3s opacity ease-out;
}

.sidebar-nav .metismenu ul a:hover:before {
  position: absolute;
  left: 0;
  width: 100%;
  background: #0B7285;
  height: 3em;
  z-index: -1;
  opacity: 1;
  transition: 0.3s opacity ease-out, 0.3s color ease-out;
  transform: translateY(-1em);
}

<div class="sidebar-nav">
  <div class="metismenu">
    <ul>
      <li><a>Item 1</a>
        <ul>
          <li><a>Sub-item</a></li>
        </ul>
      </li>
      <li><a>Item 2</a></li>
      <li><a>Item 3</a>
        <ul>
          <li><a>Sub-item</a></li>
          <li><a>Sub-item</a>
            <ul>
              <li><a>Sub-subitem</a></li>
              <li><a>Sub-subitem</a></li>
              <li><a>Sub-subitem</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>


问:
In Tizen Studio Unexpected error `Installing the package...` Web application (for watch)
I am very new to Tizen development. I was trying to run a web application (default BasicUI) in tizen watch gear s3. But getting the following error:

Installing the package... > Fail
Unexpected error occurred at the below step.
 Installing the package...
Please try again later.

Though I when I tried the native app default template and it was okay. I am getting this problem only for web application.

Here I have also given the screenshot from the console.

I am using version 3 and my operation system is windwos 10. Tried both certificate Tizen and samsung.

答:
Just because your Gear S3 is on Tizen version 2.3.2 ?

Look at : Gear info -> About device -> Tizen version

But I don't understand why the native wearable app 3.0 works in my Gear S3 (2.3.2).


问:
In HTML5, is it better to use
 and
 instead of
–
?
In studying up on HTML5's new section tag, I'm wondering about the handling of h1, h2, h3, h4, h5, and h6 tags...

The HTML5 specification says that "[h1, h2, etc.] elements represent headings for their sections" (http://www.w3.org/TR/html5/sections.html#the-h1-h2-h3-h4-h5-and-h6-elements). Further in the spec's "4.4.11 Headings and sections" section, there are currently three examples of structuring a document about apples.

If we follow the first specification, which states that heading elements "should represent headings for their sections," it seems the third apple example is the most correct structure (i.e., using h1 tags for the heading in each section and subsection). Using this logic it seems that the h2, h3, h4, h5, and h6 tags would be used rarely, if at all.

This is what I'm wondering: should h2, h3, h4, h5, or h6 tags really be used if, in reality, they are basically marking up subsections? Does it not make more sense to use section tags to separate sections, each with their own header, rather than relying on h2, h3, etc. to start implicit sections? (The "Headers and sections" section also talks about the sections implied by using h2, h3, etc.)

Perhaps it's my relational database knowledge causing a bias, but creating multiple header tags with numbers (h 1, h 2, h 3) seems like bad practice, when technically they are each heading their own section or subsection.

What are your thoughts?

答:
There is an implied hierarchy when you use these tags.  h2 sections are below h1; h3 is below h2, etc.  They are sub-sections sub-sections.  I'm not sure why this causes a disconnect.  If you only ever have one level of sub-sections then you would only ever use h1.

I think what you are objecting to is the
 tag can provide similar hierarchical functionality, but the
 tag is new to HTML and (as is often the case) just because there is another way to do it does not mean the specification changes to break the old ways.

Title: In HTML5, is it better to use <section> and <h1> instead of <h2>–<h6>?

Body:
There is an implied hierarchy when you use these tags.  h2 sections are below h1; h3 is below h2, etc.  They are sub-sections sub-sections.  I'm not sure why this causes a disconnect.  If you only ever have one level of sub-sections then you would only ever use h1.

I think what you are objecting to is the <section> tag can provide similar hierarchical functionality, but the <section> tag is new to HTML and (as is often the case) just because there is another way to do it does not mean the specification changes to break the old ways.


问:
Why -NotMatch is not working while using within a PowerShell script?
I have one XML file. I want to search for a string and then delete that line from the file.

Now the problem is that when I run following code from PS console, it works fine - deletes the line which contains "test3". But when I put the same code inside a PS script and run it, it is NOT deleting the intended line. Can you please let me know if I am missing something?

test.txt:

```<code>test1
test2
test3
test4
test5
test6
</code>```

Code:

```<code>$loc = "D:\test.txt"
$msg = "test3"
$newF = Get-Content -Path $loc | where {$_ -notmatch $msg}
$newF
</code>```

I am using PSVersion: 5.1.14393.1358.

答:
Works absolutely fine. See the picture below.

Works fine from the console also.

Body:
I have one XML file. I want to search for a string and then delete that line from the file.

Now the problem is that when I run following code from PS console, it works fine - deletes the line which contains "test3". But when I put the same code inside a PS script and run it, it is NOT deleting the intended line. Can you please let me know if I am missing something?

test.txt:

test1
test2
test3
test4
test5
test6

Code:

$loc = "D:\test.txt"
$msg = "test3"
$newF = Get-Content -Path $loc | where {$_ -notmatch $msg}
$newF

I am using PSVersion: 5.1.14393.1358.


问:
Parsing chess notation string in R to find last move number
Have a list of strings ChessNotation like this:

"26. Qb7 Qc6 0-1"

"31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2"

"36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0"

"34. b4 Ra8 35. Ng5 Rxa3 36. Nf3 Rb3 37. Kg3 Rxb4 38. h4 Kf6 39. Ng1 Kf5 0-1"
"25. Rad1 Qc6 26. Qb8 1-0"

I want to parse out the last move number from each.
So results from above would be: 26, 35, 40, 39, 26

Original plan was to str_split with space and then figure out if I need the 3rd last or the 4th last entry in the resulting list.

Problem is: I can't figure out how to get the length from a vector of string of string. If I do:

length(str_split(ChessNotation,' '))

I get 5, the number of entries in the ChessNotation list. I need to get back a vector with the number of entries in each str_split list.

I'd appreciate any help with getting the length of each list or with how to parse out the move number I need in general.

I should note I have no idea how to do regular expressions, but if anyone can point out how to do them for this instance that would be perfect too.

Thanks!

答:
The package stringr will be useful to you, especially since you do not already know regular expressions. The vignettes can walk you through a lot of examples.

Here is a solution using str_extract_all from that package.

```<code>library(stringr)
x <- list("26. Qb7 Qc6 0-1",
          "31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2",
          "36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0",
          "34. b4 Ra8 35. Ng5 Rxa3 36. Nf3 Rb3 37. Kg3 Rxb4 38. h4 Kf6 39. Ng1 Kf5 0-1",
          "25. Rad1 Qc6 26. Qb8 1-0")

extract_func <- function(x) {
  x2 <- unlist(str_extract_all(x, "\\d*\\."))
  as.numeric(x2[length(x2)])
}

unlist(lapply(x, extract_func))

[1] 26 35 40 39 26
</code>```

Body:
The package stringr will be useful to you, especially since you do not already know regular expressions. The vignettes can walk you through a lot of examples.

Here is a solution using str_extract_all from that package.

library(stringr)
x <- list("26. Qb7 Qc6 0-1",
          "31. g3 Rh2 32. a4 Rxh3 33. Kg2 Rh5 34. a5 Rg5 35. Ra8 Rg4 1/2-1/2",
          "36. Bd4 Bxb3 37. Rxc7+ Bxc7 38. axb3 a6 39. h3 Ke6 40. g4 1-0",
          "34. b4 Ra8 35. Ng5 Rxa3 36. Nf3 Rb3 37. Kg3 Rxb4 38. h4 Kf6 39. Ng1 Kf5 0-1",
          "25. Rad1 Qc6 26. Qb8 1-0")

extract_func <- function(x) {
  x2 <- unlist(str_extract_all(x, "\\d*\\."))
  as.numeric(x2[length(x2)])
}

unlist(lapply(x, extract_func))

[1] 26 35 40 39 26


问:
Getting results where no association between database tables are found using hibernate criteria
I want to find the applications that has no documents and I want to do it using hibernate criteria. Once I use createAlias in criteria, I only find the tables with associations. Does anyone have idea how can I do so or is it even possible?

Application.java

```<code>private int appId;

private String lname;

private String fname;

//getters setter generated
</code>```

Document.java

```<code>private int appId;

private int docId;
//getters setters generated
</code>```

Here is what my criteria looks like

```<code>Criteria criteria = session.createCriteria(Application.class, "application");
 criteria.createAlias("application.appId","document");

 if (looking for no association)
 {
 criteria.add(Restrictions.isNull("document.appId"));
 }
</code>```

Basically with the way I am setting criteria, I am creating inner join so the restriction condition is not working.

答:
Specifying join type helped me resolve the issue</p>

```<code>Criteria criteria = session.createCriteria(Application.class);
    criteria.createAlias("document",Criteria.LEFT_JOIN);
    if (looking for no association) {
        criteria.add(Restrictions.isNull("document.appId"));
    }
</code>```

Body:
I want to find the applications that has no documents and I want to do it using hibernate criteria. Once I use createAlias in criteria, I only find the tables with associations. Does anyone have idea how can I do so or is it even possible?

Application.java

private int appId;

private String lname;

private String fname;

//getters setter generated

Document.java

private int appId;

private int docId;
//getters setters generated

Here is what my criteria looks like

Criteria criteria = session.createCriteria(Application.class, "application");
 criteria.createAlias("application.appId","document");

 if (looking for no association)
 {
 criteria.add(Restrictions.isNull("document.appId"));
 }

Basically with the way I am setting criteria, I am creating inner join so the restriction condition is not working.

Body:
Specifying join type helped me resolve the issue

Criteria criteria = session.createCriteria(Application.class);
    criteria.createAlias("document",Criteria.LEFT_JOIN);
    if (looking for no association) {
        criteria.add(Restrictions.isNull("document.appId"));
    }


问:
how to update to a specific commit in git?
I am new to git and I would like to know if I can update my local repository to a specific commit.
Is this possible using checkout?

```<code>git checkout <commitId>
</code>```

exp

```<code>git checkout 55215860452c5c6fb11eac6f51d63abb187e7
</code>```

Thanks in advance!

答:
It depends on what you mean by "update my local repository". If you want to remain on your current branch, you can reset your branch to a prior commit with:

```<code>git reset --hard <SHA1>
</code>```

This will put the state of your branch to that of SHA1. The command git checkout changes the branch you are working on, so it will also change the state of the local repository, but the branch will no longer be the same.

Body:
I am new to git and I would like to know if I can update my local repository to a specific commit.
Is this possible using checkout?

git checkout <commitId>

exp

git checkout 55215860452c5c6fb11eac6f51d63abb187e7

Thanks in advance!

Body:
It depends on what you mean by "update my local repository". If you want to remain on your current branch, you can reset your branch to a prior commit with:

git reset --hard <SHA1>

This will put the state of your branch to that of SHA1. The command git checkout changes the branch you are working on, so it will also change the state of the local repository, but the branch will no longer be the same.


问:
Macro Code to Number Lines based on if there is Data
I am newish at VBA but I cannot figure out how to make this work. I am copying a ton of data from a another Excel sheet and then deleting the unneeded rows. The problem is that I need my data numbered in column A and when I delete the row it skips numbers. I want a macro that will number my data after I delete the unneeded lines. I do need it to stop when my data stops but the number of lines will be different each time. Any tips? Thank you.</p>

答:
You may try something like this...

After deleting rows, run the following code which will add the sequence number in column A starting from row2.

```<code>Sub SqNumber()
Dim lr As Long
lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With Range("A2:A" & lr)
    .Formula = "=Row()-1"
    .Value = .Value
End With
End Sub
</code>```

Body:
You may try something like this...

After deleting rows, run the following code which will add the sequence number in column A starting from row2.

Sub SqNumber()
Dim lr As Long
lr = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
With Range("A2:A" & lr)
    .Formula = "=Row()-1"
    .Value = .Value
End With
End Sub


问:
VS Code: running ASP.NET SPA with Angular 4 and using NodeServices options Launch With Debugging
I have tried to launch in VS Code my SPA project (Angular 4 + ASP.NET) and I am getting errors. This errors are cause by:

```<code> // Add JavaScript services.
            services.AddNodeServices(options => {
                // https://github.com/aspnet/JavaScriptServices/tree/dev/src/Microsoft.AspNetCore.SpaServices#debugging-your-javascripttypescript-code-when-it-runs-on-the-server
                options.LaunchWithDebugging = true;
                options.DebuggingPort = 9229;
            });
</code>```

This options should enable debugging my javascript/typscript code while it is prerendered on the server. But the problem is that this configuration is deprecated.

It means that I should use node --inspect instead of node --debug But how can I achieve this in VS Code, or ASP.NET Core project to force that dotnet run command will start appropriate node debugging mode.

答:
This issue is caused by change in Node.js between versions 4.x and later. The required changes or modifications to fix this issue are already done for NodeServices package which is compatible with .Net Core 2.0 (Fix is not available for .Net Core 1.0)

So following are the available options

Downgrade to Node 4.x which doesn't exhibit this problem Or

upgrade to ASP.NET Core 2.0 Preview 2, which includes the latest version of NodeServices in which this issue is fixed.

Thanks to Steve for clarifying in below thread
https://github.com/aspnet/JavaScriptServices/issues/1084#issuecomment-313083926

Body:
I have tried to launch in VS Code my SPA project (Angular 4 + ASP.NET) and I am getting errors. This errors are cause by:

 // Add JavaScript services.
            services.AddNodeServices(options => {
                // https://github.com/aspnet/JavaScriptServices/tree/dev/src/Microsoft.AspNetCore.SpaServices#debugging-your-javascripttypescript-code-when-it-runs-on-the-server
                options.LaunchWithDebugging = true;
                options.DebuggingPort = 9229;
            });

This options should enable debugging my javascript/typscript code while it is prerendered on the server. But the problem is that this configuration is deprecated.

It means that I should use node --inspect instead of node --debug But how can I achieve this in VS Code, or ASP.NET Core project to force that dotnet run command will start appropriate node debugging mode.


答: I agree with @Robert. It sounds to me like a case for an "h" tag for use within sections, or h1..n tags for implied sections. Allowing hn in a section is just redundant. </p>

Body:
In studying up on HTML5's new section tag, I'm wondering about the handling of h1, h2, h3, h4, h5, and h6 tags...

The HTML5 specification says that "[h1, h2, etc.] elements represent headings for their sections" (http://www.w3.org/TR/html5/sections.html#the-h1-h2-h3-h4-h5-and-h6-elements). Further in the spec's "4.4.11 Headings and sections" section, there are currently three examples of structuring a document about apples.

If we follow the first specification, which states that heading elements "should represent headings for their sections," it seems the third apple example is the most correct structure (i.e., using h1 tags for the heading in each section and subsection). Using this logic it seems that the h2, h3, h4, h5, and h6 tags would be used rarely, if at all.

This is what I'm wondering: should h2, h3, h4, h5, or h6 tags really be used if, in reality, they are basically marking up subsections? Does it not make more sense to use section tags to separate sections, each with their own header, rather than relying on h2, h3, etc. to start implicit sections? (The "Headers and sections" section also talks about the sections implied by using h2, h3, etc.)

Perhaps it's my relational database knowledge causing a bias, but creating multiple header tags with numbers (h 1, h 2, h 3) seems like bad practice, when technically they are each heading their own section or subsection.

What are your thoughts?


问:
How to relocate MyLocationView in Mapbox Android SDK?
I want to change the location of MyLocationView in MapView of Mapbox. I don't want to use a custom marker. Because calculating bearing and adding this to a marker (like in navigation apps) is difficult for me(Sensor Fusion & GPS bearing should be done) and also MyLocationView is smoother than a marker in relocating and changing bearing operations. I'm continuing with Mapbox MyLocationView. I have done bearing tracking integration and showing location on the MapView. What i have done is:

```<code>mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {
        map = mapboxMap;

        map.setMyLocationEnabled(true);
        map.getTrackingSettings().setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
        map.getTrackingSettings().setMyBearingTrackingMode(MyBearingTracking.COMPASS);
        map.getTrackingSettings().setDismissBearingTrackingOnGesture(false);
        map.getMyLocationViewSettings().setForegroundDrawable(iconDrawable, iconDrawable);
        map.getMyLocationViewSettings().setBackgroundTintColor(Color.parseColor("#56B881"));
        map.getMyLocationViewSettings().setForegroundTintColor(Color.parseColor("#FFFFFF"));
        map.getMyLocationViewSettings().setAccuracyTintColor(Color.parseColor("#56B881"));
    }
});
</code>```

My View:

So i want to ask is it possible to update MyLocationView's Location in Mapbox Android SDK? I do lots of search but i can not figure out that. Maybe there is a trick about this.

答:
Firstly, you should implement ProgressChangeListener in your Activity from this package
com.mapbox.services.android.navigation.v5.listeners.ProgressChangeListener

After that in the next overrided method you can update your location

```<code>@Override
public void onProgressChange(Location location, RouteProgress
routeProgress) {
    Log.e(TAG, "onProgressChange" + location);
    Log.d(TAG, "onProgressChange: fraction of route traveled: %f"
    + routeProgress.getFractionTraveled());
    if(mapboxMap.getMyLocation()!=null){
         mapboxMap.getMyLocation().setLatitude(location.getLatitude());
         mapboxMap.getMyLocation().setLongitude(location.getLongitude());
    }
}
</code>```

And for userOffRoute method from implemented OffRouteListener you can do the same.

Also I'd like to notice that in build.gradle I have next dependencies

```<code>compile('com.mapbox.mapboxsdk:mapbox-android-sdk:5.1.0@aar') {
    transitive = true
}
compile 'com.mapbox.mapboxsdk:mapbox-android-ui:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-telemetry:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.3.1'
compile 'com.mapbox.mapboxsdk:mapbox-java-core:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-geojson:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services-rx:2.1.3'
</code>```

Body:
I want to change the location of MyLocationView in MapView of Mapbox. I don't want to use a custom marker. Because calculating bearing and adding this to a marker (like in navigation apps) is difficult for me(Sensor Fusion & GPS bearing should be done) and also MyLocationView is smoother than a marker in relocating and changing bearing operations. I'm continuing with Mapbox MyLocationView. I have done bearing tracking integration and showing location on the MapView. What i have done is:

mapView.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(MapboxMap mapboxMap) {
        map = mapboxMap;

        map.setMyLocationEnabled(true);
        map.getTrackingSettings().setMyLocationTrackingMode(MyLocationTracking.TRACKING_FOLLOW);
        map.getTrackingSettings().setMyBearingTrackingMode(MyBearingTracking.COMPASS);
        map.getTrackingSettings().setDismissBearingTrackingOnGesture(false);
        map.getMyLocationViewSettings().setForegroundDrawable(iconDrawable, iconDrawable);
        map.getMyLocationViewSettings().setBackgroundTintColor(Color.parseColor("#56B881"));
        map.getMyLocationViewSettings().setForegroundTintColor(Color.parseColor("#FFFFFF"));
        map.getMyLocationViewSettings().setAccuracyTintColor(Color.parseColor("#56B881"));
    }
});

My View:

So i want to ask is it possible to update MyLocationView's Location in Mapbox Android SDK? I do lots of search but i can not figure out that. Maybe there is a trick about this.

Body:
Firstly, you should implement ProgressChangeListener in your Activity from this package
com.mapbox.services.android.navigation.v5.listeners.ProgressChangeListener

After that in the next overrided method you can update your location

@Override
public void onProgressChange(Location location, RouteProgress
routeProgress) {
    Log.e(TAG, "onProgressChange" + location);
    Log.d(TAG, "onProgressChange: fraction of route traveled: %f"
    + routeProgress.getFractionTraveled());
    if(mapboxMap.getMyLocation()!=null){
         mapboxMap.getMyLocation().setLatitude(location.getLatitude());
         mapboxMap.getMyLocation().setLongitude(location.getLongitude());
    }
}

And for userOffRoute method from implemented OffRouteListener you can do the same.

Also I'd like to notice that in build.gradle I have next dependencies

compile('com.mapbox.mapboxsdk:mapbox-android-sdk:5.1.0@aar') {
    transitive = true
}
compile 'com.mapbox.mapboxsdk:mapbox-android-ui:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-telemetry:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.3.1'
compile 'com.mapbox.mapboxsdk:mapbox-java-core:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-geojson:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services:2.1.3'
compile 'com.mapbox.mapboxsdk:mapbox-java-services-rx:2.1.3'


问:
How does firepath finds unique xpath on click
I am very curious to know how does firepath finds a unique xpath locator with in seconds as soon as we click on element. I know how to query xpath using firepath, but what I want to know that which language or technology has been used to developed such tools and what if I have to develop similar kind of tool. I have seen many automation tool have develop with such tools where when we click on page it will generate unique xpath locator, it makes me to curious and I want to know in depth how does things works in back end.

When I open DOM in developer tool it was so confusing.

How they identify element on click?

Is it rocket science?

Do they user JavaScript, JQuery or any other programing language?

Do we have any apis which can be use?

答:
type this in console and click somewhere) so it's the answer</p>

```<code>document.addEventListener('click', function(event){console.log(event.target)});
</code>```

Body:
type this in console and click somewhere) so it's the answer

document.addEventListener('click', function(event){console.log(event.target)});


问:
Is there a way to change desktop screen color with ElectronJS
I have a simple Electronjs app and I wanted to change the desktop screen color somehow, but I can't find a way to access the VGA or Monitor settings, so I was wondering is this posible and how?</p>

答: You can't do it directly with Electron. But it's possible to execute other commands that can do this for you. Since you can use npm packages you can also use a package like https://www.npmjs.com/package/wallpaper-cli to set the background image.</p>


问:
AR Drone Wifi Hotspot Doesn't Appear
I am working with the Parrot AR Drone V1.0, and even after rebooting my laptop and the drone, reseting the drone, and turning wifi on and off, the drone's wifi still does not appear in the listings for available networks? How can I fix this issue as I need to connect to the drone to stream video. I am working with ROS to program the drone so it can fly autonomously. I am also using Ubuntu 16.04 via Oracle Virtualbox on a MacBook Air 13.3". </p>

答:
https://www.ifixit.com/Answers/View/248770/Why+is+my+drone+is+not+creating+wifi+hotspot+to+connect

Try to connect to it with your phone to see if it may be an issue only with your laptop, but check this link out for a useful answer

Title: AR Drone Wifi Hotspot Doesn't Appear


问:
How to make a copy of a swift array of class objects
In code below, list1 is original Array.
when i copy list1 in list2, it passes "allCardList" array as reference but i want to create copy of list1 so when i change in list2 it shouldn't change original Array (list1)

```<code>class Card {
    var availableBalance        = "5"
}
class DataCacheManager: NSObject {
    var allCardList             = [Card]()
}
var card = Card()
card.availableBalance = "10"

var list1 = DataCacheManager()
list1.allCardList.append(card)

var list2 = DataCacheManager()

for item in list1.allCardList {
    list2.allCardList.append(item)
}

list2.allCardList[0].availableBalance = "20"

print(list1.allCardList[0].availableBalance) // print 20 but should return 10
</code>```

Any help you that?

答:
Please read these references
How do I make a exact duplicate copy of an array?1
and deep copy array In you case there other ways to achive your requirement without copying the whole array. For a example you could have an readonly original value as a object in Card and have another variable for the new value and so on. </p>

Body:
In code below, list1 is original Array.
when i copy list1 in list2, it passes "allCardList" array as reference but i want to create copy of list1 so when i change in list2 it shouldn't change original Array (list1)

class Card {
    var availableBalance        = "5"
}
class DataCacheManager: NSObject {
    var allCardList             = [Card]()
}
var card = Card()
card.availableBalance = "10"

var list1 = DataCacheManager()
list1.allCardList.append(card)

var list2 = DataCacheManager()

for item in list1.allCardList {
    list2.allCardList.append(item)
}

list2.allCardList[0].availableBalance = "20"

print(list1.allCardList[0].availableBalance) // print 20 but should return 10

Any help you that?