问:
Is there a way to filter data when passing it in ModelForm and how can we edit them?
I'm creating a site to register students. So basically it is divided into 3 parts

```<code>1. A student register model which take the name, fathername, etc of student.
2. A student fee model which use foreignkey to get register student.
3. ModelForm for showing student fee model to enter data.
</code>```

Now the problem if I want to fill a student fee of class 1 it shows all the student of other classes, but I want the student filter according to their classes and their name show and in front of them editable fee and pending fee form.

By some reach I got to know about ModelForm instance I wrote code for automatically add register students to student fee.

```<code>def student_fee(request):
    # add a selection field to a variable for filtering student_class below this.
    students = StudentRegister.objects.filter(student_class="1")
    ....
    for x in students:
        if not  StudentFee.objects.filter(student=x):
            StudentFee.objects.create(student=x, fee=0, pending_fee=0)
</code>```

But for instance I have to know primary key of every student I can loop through them but it only get the last element.

models.py

```<code>class StudentRegister(models.Model):
    student_image    =      models.ImageField(upload_to="register_student", blank=True)
    student_class    =      models.CharField(max_length=2, choices=STUDENT_CLASS, default="1")
    mobile_number    =      models.CharField(max_length=50)
    student_name     =      models.CharField(max_length=50)
    father_name      =      models.CharField(max_length=50)
    mother_name      =      models.CharField(max_length=50)
    address          =      models.CharField(max_length=200)
    student_fee      =      models.CharField(max_length=10, default="0")
    Date_Of_Birth    =      models.DateField(auto_now=False)
    admission_fee    =      models.CharField(max_length=10)
    Admission_date   =      models.DateField(auto_now=False)
    adhaar_no        =      models.CharField(max_length=100)

    def __str__(self):
        return "%s  class: %s" % (self.student_name, self.student_class)

class StudentFee(models.Model):
    student = models.ForeignKey(StudentRegister, on_delete=models.CASCADE)
    fee = models.CharField(max_length=20)
    pending_fee = models.CharField(max_length=20)

    def __str__(self):
        return "%s " % (self.student)

</code>```

forms.py

```<code>class StudentFeeForm(forms.ModelForm):
    class Meta:
        model = StudentFee
        fields = '__all__'
</code>```

views.py(its messy sorry)

```<code>def student_fee(request):
    # add a selection field to a variable for filtering student_class below this.
    students = StudentRegister.objects.filter(student_class="1")
    real = StudentFee.objects.all()
    # student_form = StudentFeeForm(request.POST or None)
    student_form = StudentFeeForm(request.POST)#, instance=students)
    # print(dir(students))
    q = (students.get(pk=1))
    global list_student_pk
    list_student_pk = []
    for x in students:
        list_student_pk.append(x.pk)
    student_get_instance = StudentFeeForm(instance=q)
    # print(student_get_instance)

    # This thing done don't touch----------------------------------
    for x in students:
        if not StudentFee.objects.filter(student=x):
            StudentFee.objects.create(student=x, fee=0, pending_fee=0)

    if request.method == "POST":
        if student_form.is_valid():
            pass # this thing will done after the form problem solved.
    # till here ==========================================================

    return render(request, "student_fee_home.html", {"students": students, "real":real, "student_form":student_form, "list_student_pk":list_student_pk, "student_get_instance":student_get_instance})
</code>```

I want that modelforms filter according to class.
Then the student fee model which already having register student(student name, fee, pending fee) can edit. So that it shows the student name and right in front of him a editable fee form and a pending fee form.

It is working right now like this showing all student of all classes, but I want that students name will show instead of selection field. In my knowledge only option to display names of student display names direct from models then use a form to take input of fee and pending fee then create it in models.

答:
djang0-filter will help you for filtering

```<code>pip install django-filter
</code>```

Model.py

```<code>    class Dispatcher(models.Model):
        _safedelete_policy = SOFT_DELETE

        Individual = 'Individual'
        Company = 'Company'

        TYPES = [
            (Individual, 'Individual'),
            (Company, 'Company')
        ]
    type = models.CharField(max_length=255,
                                choices=TYPES,
                                default=Individual)
</code>```

Views.py

```<code>class DispatcherViewSet(viewsets.ModelViewSet):
    queryset = Dispatcher.objects.all()
    serializer_class = DispatcherSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_fields = ['type']
</code>```

Body:
I'm creating a site to register students. So basically it is divided into 3 parts

1. A student register model which take the name, fathername, etc of student.
2. A student fee model which use foreignkey to get register student.
3. ModelForm for showing student fee model to enter data.

Now the problem if I want to fill a student fee of class 1 it shows all the student of other classes, but I want the student filter according to their classes and their name show and in front of them editable fee and pending fee form.

By some reach I got to know about ModelForm instance I wrote code for automatically add register students to student fee.

def student_fee(request):
    # add a selection field to a variable for filtering student_class below this.
    students = StudentRegister.objects.filter(student_class="1")
    ....
    for x in students:
        if not  StudentFee.objects.filter(student=x):
            StudentFee.objects.create(student=x, fee=0, pending_fee=0)

But for instance I have to know primary key of every student I can loop through them but it only get the last element.

models.py

class StudentRegister(models.Model):
    student_image    =      models.ImageField(upload_to="register_student", blank=True)
    student_class    =      models.CharField(max_length=2, choices=STUDENT_CLASS, default="1")
    mobile_number    =      models.CharField(max_length=50)
    student_name     =      models.CharField(max_length=50)
    father_name      =      models.CharField(max_length=50)
    mother_name      =      models.CharField(max_length=50)
    address          =      models.CharField(max_length=200)
    student_fee      =      models.CharField(max_length=10, default="0")
    Date_Of_Birth    =      models.DateField(auto_now=False)
    admission_fee    =      models.CharField(max_length=10)
    Admission_date   =      models.DateField(auto_now=False)
    adhaar_no        =      models.CharField(max_length=100)

    def __str__(self):
        return "%s  class: %s" % (self.student_name, self.student_class)

class StudentFee(models.Model):
    student = models.ForeignKey(StudentRegister, on_delete=models.CASCADE)
    fee = models.CharField(max_length=20)
    pending_fee = models.CharField(max_length=20)

    def __str__(self):
        return "%s " % (self.student)

forms.py

class StudentFeeForm(forms.ModelForm):
    class Meta:
        model = StudentFee
        fields = '__all__'

views.py(its messy sorry)

def student_fee(request):
    # add a selection field to a variable for filtering student_class below this.
    students = StudentRegister.objects.filter(student_class="1")
    real = StudentFee.objects.all()
    # student_form = StudentFeeForm(request.POST or None)
    student_form = StudentFeeForm(request.POST)#, instance=students)
    # print(dir(students))
    q = (students.get(pk=1))
    global list_student_pk
    list_student_pk = []
    for x in students:
        list_student_pk.append(x.pk)
    student_get_instance = StudentFeeForm(instance=q)
    # print(student_get_instance)

    # This thing done don't touch----------------------------------
    for x in students:
        if not StudentFee.objects.filter(student=x):
            StudentFee.objects.create(student=x, fee=0, pending_fee=0)

    if request.method == "POST":
        if student_form.is_valid():
            pass # this thing will done after the form problem solved.
    # till here ==========================================================

    return render(request, "student_fee_home.html", {"students": students, "real":real, "student_form":student_form, "list_student_pk":list_student_pk, "student_get_instance":student_get_instance})

I want that modelforms filter according to class.
Then the student fee model which already having register student(student name, fee, pending fee) can edit. So that it shows the student name and right in front of him a editable fee form and a pending fee form.

It is working right now like this showing all student of all classes, but I want that students name will show instead of selection field. In my knowledge only option to display names of student display names direct from models then use a form to take input of fee and pending fee then create it in models.

Body:
djang0-filter will help you for filtering

pip install django-filter

Model.py

    class Dispatcher(models.Model):
        _safedelete_policy = SOFT_DELETE

        Individual = 'Individual'
        Company = 'Company'

        TYPES = [
            (Individual, 'Individual'),
            (Company, 'Company')
        ]
    type = models.CharField(max_length=255,
                                choices=TYPES,
                                default=Individual)

Views.py

class DispatcherViewSet(viewsets.ModelViewSet):
    queryset = Dispatcher.objects.all()
    serializer_class = DispatcherSerializer
    filter_backends = (DjangoFilterBackend,)
    filterset_fields = ['type']


来源: stackexchange

问:
Why is this regex expression returning 'true'?
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

```<code>var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();
</code>```

答:
You have to use ^ and $ to force the whole string to match the regex pattern

^[0-9]+$

^ matches the beginning, $ the end of the string

In C# Write the expression like below format:

```<code>var x = Regex.IsMatch("1234", @"^[0-9]+$").ToString();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using this exact regex in a RegularExpressionValidator and it works fine. However this code in c# is returning true. Can you please let me know what I am doing wrong?

I am checking for numbers only regex

var x = Regex.IsMatch("1234asdf", @"[0-9]+").ToString();

Body:
You have to use ^ and $ to force the whole string to match the regex pattern

^[0-9]+$

^ matches the beginning, $ the end of the string

In C# Write the expression like below format:

var x = Regex.IsMatch("1234", @"^[0-9]+$").ToString();


问:
How to bind class to more than two options in Vue.js?
I have the following Vue.js bound HTML:

```<code><span :class="[obj.status === 'Online' ? 'badge-success' : 'badge-danger', 'badge badge-pill']">{{obj.status}}</span>
</code>```

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

答:
One way would be to shift your class assignment to a method:

new Vue({
  el: "#app",
  data: {
   myValues: [
       {status: 'Online'},
          {status: 'Updating'}
    ]
  },
  methods: {
  assignedClasses(status) {
      var classToAssign;
      if(status === 'Online'){
       classToAssign = 'badge-success';
      }
      else if(status === 'Updating') {
       classToAssign = 'badge-warning';
      }
      else {
       classToAssign = 'badge-danger';
      }

      return classToAssign;
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://unpkg.com/bootstrap@4.1.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(obj, index) in myValues" :key="index">
    <span class="badge badge-pill" :class="assignedClasses(obj.status)">{{obj.status}}</span>
  </div>
</div></code>```

Body:
I have the following Vue.js bound HTML:

{{obj.status}}

I want to add another variant:

if obj.status === 'Updating' then the class should be badge-warning.

What is the best way to achieve this efficiently? I think I can add another ternary in the existing one but it will look messy.

Body:
One way would be to shift your class assignment to a method:

new Vue({
  el: "#app",
  data: {
   myValues: [
       {status: 'Online'},
          {status: 'Updating'}
    ]
  },
  methods: {
  assignedClasses(status) {
      var classToAssign;
      if(status === 'Online'){
       classToAssign = 'badge-success';
      }
      else if(status === 'Updating') {
       classToAssign = 'badge-warning';
      }
      else {
       classToAssign = 'badge-danger';
      }

      return classToAssign;
    }
  }
})

<link href="https://unpkg.com/bootstrap@4.1.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(obj, index) in myValues" :key="index">
    <span class="badge badge-pill" :class="assignedClasses(obj.status)">{{obj.status}}</span>
  </div>
</div>


问:
Create dynamic links with JQuery - individual post id
There are quotes in a forum. I have to place a "quote-back-link" via JQuery or Javascript to the original post.

Inside of each blockquote is span tag with the class name "post_id". The ID of that span tag contains always the ID of the original post. In the example the span tag is at the end of each blockquote, but its also possible to place it on a different position.

```<code><blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote>
</code>```

Is there any way that I can rewrite the Poster-Name that is always between

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

with a link to the original ID? The examples have to look like:

```<code><blockquote>
  <cite><a href="/post-123.html">Testuser said:</a></cite>
   <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite><a href="/post-1234.html">Testuser2 said:</a></cite>
 <div>This is a test</div>
 <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite><a href="/post-12345.html">Testuser3 said:</a></cite>
 <div>This is a test</div>
 <span class="post_id" id="12345"></span>
</blockquote>
</code>```

Thank you very much.

答:
Using jQuery, you can simply acquire, for each blockquote, its child cite and its post-id value. Then, just replace the html with the desired one.

Side (but relevant) notes:

You should always check whether a  element exists.

You should always check that there is at least one child element with .post_id class. If there is none, you should abort the override. If there is more than one, you should handle the case.

I'm using some ES6 syntax below (mostly, I'm using the ticks to parse strings). Some browsers may not support it, so you may want to convert the code to make it compliant to the targeted javascript version.

Of course, none of the above happens in the sample, but it's worth mentioning that you should take care of that as well.

$('blockquote').each(function(blockquote){
  // Find the  element.
  var _cite = $(this).find('cite');
  // get the first .post_id's id attribute value.
  var _postId = $(this).find('.post_id').first().attr('id');
  console.log(_postId); // <-- just a side note. This will be a string. If you need to use such id, remember to make it numeric if you need to use it as a number. You can do that by doing Number(_postId) or, simply, +_postId.
  // Generate the new html by generating a new anchor with the desired link.
  var newHtml = `${_cite.html()}`;
  // Override the  html.
  _cite.html(newHtml);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote></code>```

Body:
There are quotes in a forum. I have to place a "quote-back-link" via JQuery or Javascript to the original post.

Inside of each blockquote is span tag with the class name "post_id". The ID of that span tag contains always the ID of the original post. In the example the span tag is at the end of each blockquote, but its also possible to place it on a different position.

  Testuser said:

This is a test

 Testuser2 said:

This is a test

 Testuser3 said:

This is a test

Is there any way that I can rewrite the Poster-Name that is always between

with a link to the original ID? The examples have to look like:

  Testuser said:

This is a test

 Testuser2 said:

This is a test

 Testuser3 said:

This is a test

Thank you very much.

Body:
Using jQuery, you can simply acquire, for each blockquote, its child cite and its post-id value. Then, just replace the html with the desired one.

Side (but relevant) notes:

You should always check whether a <cite> element exists.

You should always check that there is at least one child element with .post_id class. If there is none, you should abort the override. If there is more than one, you should handle the case.

I'm using some ES6 syntax below (mostly, I'm using the ticks to parse strings). Some browsers may not support it, so you may want to convert the code to make it compliant to the targeted javascript version.

Of course, none of the above happens in the sample, but it's worth mentioning that you should take care of that as well.

$('blockquote').each(function(blockquote){
  // Find the <cite> element.
  var _cite = $(this).find('cite');
  // get the first .post_id's id attribute value.
  var _postId = $(this).find('.post_id').first().attr('id');
  console.log(_postId); // <-- just a side note. This will be a string. If you need to use such id, remember to make it numeric if you need to use it as a number. You can do that by doing Number(_postId) or, simply, +_postId.
  // Generate the new html by generating a new anchor with the desired link.
  var newHtml = `<a href="/post-${_postId}.html">${_cite.html()}</a>`;
  // Override the <cite> html.
  _cite.html(newHtml);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<blockquote>
  <cite>Testuser said:</cite>
    <div>This is a test</div>
    <span class="post_id" id="123"></span>
</blockquote>

<blockquote>
 <cite>Testuser2 said:</cite>
  <div>This is a test</div>
  <span class="post_id" id="1234"></span>
</blockquote>

<blockquote>
 <cite>Testuser3 said:</cite>
   <div>This is a test</div>
   <span class="post_id" id="12345"></span>
</blockquote>


问:
Setting NVRAM variable using WinAPI
I'm trying to setup my own NVRAM variable (nv+rt+bs) using WinAPI (SetFirmwareEnvironmentVariable). It fails with my variable and successfully completed with BootOrder. What do I do wrong? Is it possible to setup my own variable using WinAPI?

I'm trying to setup my variable using this code

```<code>void setMyNVRAM()
{
    // here I setup SE_SYSTEM_ENVIRONMENT_NAME privilege

    uint16_t value = 0x5aa5;

    if (!SetFirmwareEnvironmentVariable(L"MY_VARIABLE",
       L"{12345678-1234-1234-1234-123456789012}", &value, sizeof (value)))
    {
        std::cout << "error while settin up MY_VARIABLE. Error code: "
                  << GetLastError() << std::endl;
    }
    else
    {
        std::cout << "success" << std::endl;
    }
}
</code>```

SetFirmwareEnvironmentVariable returns 0 and GetLastError() returns 5 (access denied). I also tried to write into BootOrder variable and it was successfully completed.

答:
According to the instructions on the MSDN.

To write a firmware environment variable, the user account that the
  app is running under must have the SE_SYSTEM_ENVIRONMENT_NAME
  privilege. A Universal Windows app must be run from an administrator
  account and follow the requirements outlined in Access UEFI firmware
  variables from a Universal Windows App.

Customizing user privileges for an account in Windows

A similar discussion: How i can set firmware environment variable in UEFI driver

Title: Setting NVRAM variable using WinAPI

Body:
I'm trying to setup my own NVRAM variable (nv+rt+bs) using WinAPI (SetFirmwareEnvironmentVariable). It fails with my variable and successfully completed with BootOrder. What do I do wrong? Is it possible to setup my own variable using WinAPI?

I'm trying to setup my variable using this code

void setMyNVRAM()
{
    // here I setup SE_SYSTEM_ENVIRONMENT_NAME privilege

    uint16_t value = 0x5aa5;

    if (!SetFirmwareEnvironmentVariable(L"MY_VARIABLE",
       L"{12345678-1234-1234-1234-123456789012}", &value, sizeof (value)))
    {
        std::cout << "error while settin up MY_VARIABLE. Error code: "
                  << GetLastError() << std::endl;
    }
    else
    {
        std::cout << "success" << std::endl;
    }
}

SetFirmwareEnvironmentVariable returns 0 and GetLastError() returns 5 (access denied). I also tried to write into BootOrder variable and it was successfully completed.


问:
Adding a DOM element by changing innerHtml of a div prevents it to be found later with getElementById?
I have a div and I'm using javascript to add a new element inside it

Original Div:

```<code><div id="foo"></div>
</code>```

JavaScript:

```<code>document.getElementById('foo').innerHTML ="<div id='bar'></div>";
</code>```

Result

```<code><div id="foo">
  <div id="bar"></div>
</div>
</code>```

But after executing this code I try to retrieve the element (in order to focus on it) doing

```<code> document.getElementById('bar')
</code>```

But this returns an empty object.

So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?

答:
It works perfectly - make sure you're running it in the correct order:

document.getElementById('foo').innerHTML ="
Bar
";
console.log(document.getElementById("bar"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo">Foo</div></code>```

Body:
I have a div and I'm using javascript to add a new element inside it

Original Div:

JavaScript:

document.getElementById('foo').innerHTML ="

";

Result

But after executing this code I try to retrieve the element (in order to focus on it) doing

 document.getElementById('bar')

But this returns an empty object.

So does adding an element using innerHtml not really add the element to the DOM? And what is the right way to add an element that could be retrieved later by getElementById?

Body:
It works perfectly - make sure you're running it in the correct order:

document.getElementById('foo').innerHTML ="<div id='bar'>Bar</div>";
console.log(document.getElementById("bar"));

<div id="foo">Foo</div>


问:
How to use document.onload Properly
I am currently learning window.onload and document.onload as attributes on html. But i fail to use them properly. In my code i want to focus a specific text area named "emri", using the document.onload but without success. Some would say to use it as a script or smth, but i want to use it as an attribute inside the tag. What am i doing wrong?

```<code> <!doctype html>
  <html lang="en">

  <head>
     <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
    crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
    crossorigin="anonymous">

   </head>

   <body onload="document.my-form1.emri.focus();" >

  <main class="my-form">
      <div class="container">
          <div class="row justify-content-flex-start">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Apliko</div>
                    <div class="card-body">
                        <form name="my-form1" onsubmit=" return formValidation();">
                            <div class="form-group row">
                                <label for="emri" class="col-md-3 col-form-label text-md-right">Emri juaj:</label>
                                <div class="col-md-6">
                                    <input type="text"  class="form-control" name="emri">
                                </div>
                            </div>
</code>```

答:
Here your updated html :

<!doctype html>

<meta charset="utf-8">
<meta name="viewport"
 content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
 integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
 crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet"
 href="https://use.fontawesome.com/releases/v5.2.0/css/all.css"
 integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
 crossorigin="anonymous">

Apliko

      <form name="my-form1" onsubmit=" return formValidation();">

        Emri
         juaj:

         <input type="text" class="form-control" name="emri" id="emri"/>

      </form>

```

Title: How to use document.onload Properly

Body:
I am currently learning window.onload and document.onload as attributes on html. But i fail to use them properly. In my code i want to focus a specific text area named "emri", using the document.onload but without success. Some would say to use it as a script or smth, but i want to use it as an attribute inside the tag. What am i doing wrong?

 <!doctype html>

     <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
    crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
    crossorigin="anonymous">

Apliko

                        <form name="my-form1" onsubmit=" return formValidation();">

                                Emri juaj:

                                    <input type="text"  class="form-control" name="emri">

Body:
Here your updated html :

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport"
 content="width=device-width, initial-scale=1,
  shrink-to-fit=no">

<link rel="stylesheet"
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"
 integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB"
 crossorigin="anonymous">

<link rel="stylesheet" href="App.css">

<link rel="stylesheet"
 href="https://use.fontawesome.com/releases/v5.2.0/css/all.css"
 integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
 crossorigin="anonymous">

</head>

<body onload="document.getElementById('emri').focus();">
 <main class="my-form">
 <div class="container">
  <div class="row justify-content-flex-start">
   <div class="col-md-6">
    <div class="card">
     <div class="card-header">Apliko</div>
     <div class="card-body">
      <form name="my-form1" onsubmit=" return formValidation();">
       <div class="form-group row">
        <label for="emri" class="col-md-3 col-form-label text-md-right">Emri
         juaj:</label>
        <div class="col-md-6">
         <input type="text" class="form-control" name="emri" id="emri"/>
        </div>
       </div>
      </form>
     </div>
    </div>
   </div>
  </div>
 </div>
 </main>
</body>
</html>


问:
How to map silk 4j script to the test case in Silk Central
Please suggest on how to map/link silk 4j script to the manual test case written in Silk Central.

Like for 4Test script we select .t file and then the testcase under silk test classic properties in silk central for each test case.

答: If your Silk4J tests are in JUnit format, you need to change the manual test case in Silk Central to JUnit type instead of manual. Then specify the fully qualified name (including package) of your JUnit test as Test class. In the classpath you need to specify all jar files that are needed for executing the test.</p>


问:
Replacing a 'NULL' value in a CSV file with the date of today - Python
I am currently working on a Python project, that imports a data text file (CSV in my case) and then outputs the employees who have worked the most time together in a common project. First, this is the code and the data file:

```<code>from collections import defaultdict
from itertools import combinations
from datetime import datetime
import csv

d = defaultdict(list)

with open("data.csv") as f:
    next(f) # skip header
    r = csv.reader(f)
    # unpack use height as key and  append name age and position
    for EmpID, ProjectID, FromDate, ToDate in r:
        d[int(ProjectID)].append((EmpID, FromDate, ToDate))

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('Employees with EmpID:', ref[0][0], 'and', ref[1][0],
                      'worked together on a common project (Project ID:', job, ') for a total of', dd, 'days')
</code>```

And this is the data file, I am importing:

```<code>EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09
</code>```

Now, I have a task that if there is a value 'NULL' in the 'DateTo' column, I have to make it equal today. I am thinking that there should be an automatic python function that gives the current date, and then do an if statement inside the CSV code block to replace 'NULL' with today's date (but it is only open in read mode as far as I know?). I would very much appreciate it if anyone can give me any tips! Thanks.

EDIT:
PANDAS PREVIOUS ATTEMPT FOR SOLUTION: (50% done)

```<code># Load the Pandas libraries with alias 'pd'
import pandas as pd
import datetime as dt
import numpy as np
# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)
</code>```

答:
In your code is possible use if-else with condition for test empty values string values and replace by today datetime without times:

```<code>import pandas as pd

end = min(map(lambda x: x[2], ref))
end = datetime.strptime(end, '%Y-%m-%d') if end != '' else pd.Timestamp("today").floor('d')
delta = end - datetime.strptime(begin, '%Y-%m-%d')
</code>```

Body:
I am currently working on a Python project, that imports a data text file (CSV in my case) and then outputs the employees who have worked the most time together in a common project. First, this is the code and the data file:

from collections import defaultdict
from itertools import combinations
from datetime import datetime
import csv

d = defaultdict(list)

with open("data.csv") as f:
    next(f) # skip header
    r = csv.reader(f)
    # unpack use height as key and  append name age and position
    for EmpID, ProjectID, FromDate, ToDate in r:
        d[int(ProjectID)].append((EmpID, FromDate, ToDate))

for job, aref in d.items():
    if len(aref) >= 2:
        for ref in combinations(aref, 2):
            begin = max(map(lambda x: x[1], ref))
            end = min(map(lambda x: x[2], ref))
            delta = datetime.strptime(end, '%Y-%m-%d') \
                    - datetime.strptime(begin, '%Y-%m-%d')
            dd = delta.days
            if dd > 0:
                print('Employees with EmpID:', ref[0][0], 'and', ref[1][0],
                      'worked together on a common project (Project ID:', job, ') for a total of', dd, 'days')

And this is the data file, I am importing:

EmpID,ProjectID,DateFrom,DateTo
1,100,2014-11-01,2015-05-01
2,101,2013-12-06,2014-10-06
3,102,2015-06-04,2017-09-04
5,103,2014-10-01,2015-12-01
2,100,2013-03-07,2015-11-07
2,103,2015-07-09,2019-01-19
4,102,2013-11-13,2014-03-13
4,103,2016-02-14,2017-03-15
5,104,2014-03-15,2015-11-09

Now, I have a task that if there is a value 'NULL' in the 'DateTo' column, I have to make it equal today. I am thinking that there should be an automatic python function that gives the current date, and then do an if statement inside the CSV code block to replace 'NULL' with today's date (but it is only open in read mode as far as I know?). I would very much appreciate it if anyone can give me any tips! Thanks.

EDIT:
PANDAS PREVIOUS ATTEMPT FOR SOLUTION: (50% done)

# Load the Pandas libraries with alias 'pd'
import pandas as pd
import datetime as dt
import numpy as np
# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
date_parser = lambda c: pd.to_datetime(c, format='%Y/%m/%d', errors='coerce')
df = pd.read_csv('data.csv', delimiter = ',', parse_dates=[2,3], date_parser=date_parser)
df.set_index("EmpID", inplace = True)
df.sort_values(['ProjectID'], inplace=True)
df['Days Worked'] = (df['DateTo'] - df['DateFrom']).dt.days
cutdown_projecs = df.groupby('ProjectID').filter(lambda x: len(x) >= 2)

print(cutdown_projecs)

Body:
In your code is possible use if-else with condition for test empty values string values and replace by today datetime without times:

import pandas as pd

end = min(map(lambda x: x[2], ref))
end = datetime.strptime(end, '%Y-%m-%d') if end != '' else pd.Timestamp("today").floor('d')
delta = end - datetime.strptime(begin, '%Y-%m-%d')


问:
Clear cell content based on another cell for each row
How to clear a cell based on a change of other cell but for every row separately?
Say, I change AI5 and it clears AQ5, I change AI17 it clears AQ17?

I've got this code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("AI5")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Range("AQ5").ClearContents
Application.EnableEvents = True
End Sub
</code>```

And it works only for the cells in the code.
If I change both to a range of the column, it clears all column AQ, which is not what I need.

Thanks

答:
Like this:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("AI" & Target.Row)) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    Range("AQ" & Target.Row).ClearContents
    Application.EnableEvents = True

End Sub
</code>```

You need to tell excel which row, and the row will be the same as the Target.Row so you can use that.

Body:
How to clear a cell based on a change of other cell but for every row separately?
Say, I change AI5 and it clears AQ5, I change AI17 it clears AQ17?

I've got this code:

Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("AI5")) Is Nothing Then Exit Sub
Application.EnableEvents = False
Range("AQ5").ClearContents
Application.EnableEvents = True
End Sub

And it works only for the cells in the code.
If I change both to a range of the column, it clears all column AQ, which is not what I need.

Thanks

Body:
Like this:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("AI" & Target.Row)) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    Range("AQ" & Target.Row).ClearContents
    Application.EnableEvents = True

End Sub

You need to tell excel which row, and the row will be the same as the Target.Row so you can use that.


答:
There is nothing wrong how you use `window.onload´. It is the name of the form. Since there is a "-" character in the name, you should use it like this:

```

see: Example

Title: How to use document.onload Properly

Body:
There is nothing wrong how you use `window.onload´. It is the name of the form. Since there is a "-" character in the name, you should use it like this:

<body onload="document['my-form1'].elements.emri.focus();">

see: Example


问:
Grafana: global variables to access [from,to] values of the time range
I am doing some tests with a MySQL data-source and make use of the timefilter inside the SQL query:

```<code>// my query goes here...
WHERE $__timeFilter(time_start);
</code>```

which generates something like the following:

```<code>WHERE time_start >= FROM_UNIXTIME(1505207821) AND time_start <= FROM_UNIXTIME(1505229421);
</code>```

Are there any variables that can give me access to the 2 timestamps that define the time range?

For instance, at the example above:

```<code>from = 1505207821
to = 1505229421
</code>```

答:
Generated Query, Doesn't fit inside the grafana time range. So you can simply change the time range.

Query From and To Fit inside the time range of the query.

I have added the time range of 100y (100 years) it fit's into my query. so you can adjust your time range accordingly,

ContentLicense: CC BY-SA 3.0

Body:
I am doing some tests with a MySQL data-source and make use of the timefilter inside the SQL query:

// my query goes here...
WHERE $__timeFilter(time_start);

which generates something like the following:

WHERE time_start >= FROM_UNIXTIME(1505207821) AND time_start <= FROM_UNIXTIME(1505229421);

Are there any variables that can give me access to the 2 timestamps that define the time range?

For instance, at the example above:

from = 1505207821
to = 1505229421


问:
pandas to_excel() ignore/allow duplicate column names
Is there way to ignore duplicate column names after using to_excel() function of pandas?

Say, I have old_wb.xlsx:

```<code>>> df1 = pd.read_excel('wb1.xlsx')
        ---------------------merged header--------------------
        col1    col2   col3   col1   col4   col1   col2   col5
        test    test   test   test   test   test   test   test
</code>```

and say I did some processing to my Excel file, for example, remove the merged header and save it to another Excel file:

```<code>>> df1.to_excel('new_wb.xlsx', 'Sheet1', merged_cells=False, header=None, index=False)
</code>```

The column names of new_wb.xlsx looks like this:

```<code>        col1    col2   col3   col1.1   col4   col1.2   col2.1   col5
        test    test   test   test     test   test     test     test
</code>```

It added .1 to the duplicate column names and it also increments as the duplicate column name goes.

I tried renaming the column name before using to_excel() but it didn't work. It seems the renaming of duplicates happens in to_excel().

```<code>>> df1.rename(columns=lambda x: x.replace('.1',''))
</code>```

Upon searching, I found an argument for to_excel() which is mangle_dupe_cols=False, unfortunately it returned:

```<code>ValueError: Setting mangle_dupe_cols=False is not supported yet
</code>```

Any help on how to ignore duplicate column names in saving `to_excel()'

答:
@Ricky Aguilar has a great solution. I took his solution and just made it more dynamic.

Now you can rename all your duplicate headers, without even knowing what their values are

```<code>def dataframe_allowing_duplicate_headers():
    # To Hold All The Possible Duplicate Tags ['.1', '.2', '.3', ...]
    dup_id_range = []

    # Load Your Excel File Using Pandas
    dataframe = pandas.read_excel("path_to_excel_file", sheet_name="sheetname")

    # Generate And Store All The Possible Duplicate Tags ['.1', '.2', '.3', ...]
    for count in range(0, len(dataframe.columns)):
        dup_id_range.append( '.{}'.format(count) )

    # Search And Replace All Duplicate Headers To What It Was Set As Originally
    def rename(dataframe, character_number):
        duplicate_columns_chars = list(
            filter(lambda v: v[(len(v)-character_number):] in dup_id_range,
            dataframe.columns))

        for duplicate_column in duplicate_columns_chars:
            dataframe = dataframe.rename(
                columns={duplicate_column:duplicate_column[:-character_number]})
        return dataframe

    # Replace The Possible Duplicates Respectfully Based On Columns Count
    if len(dup_id_range) > 0:
        dataframe = rename(dataframe, 2)
        if len(dup_id_range) > 9:
            dataframe = rename(dataframe, 3)
            if len(dup_id_range) > 99:
                dataframe = rename(dataframe, 4)
                # If You Have More Than A Thousand Columns (lol)
                #if len(dup_id_range) > 999:
                #    dataframe = rename(dataframe, 5)

    return dataframe
</code>```

USAGE:

```<code># This Dataframe Will Have All Your Headers, Allowing Your Duplicates
my_dataframe = dataframe_allowing_duplicate_headers()
</code>```

Body:
Is there way to ignore duplicate column names after using to_excel() function of pandas?

Say, I have old_wb.xlsx:

>> df1 = pd.read_excel('wb1.xlsx')
        ---------------------merged header--------------------
        col1    col2   col3   col1   col4   col1   col2   col5
        test    test   test   test   test   test   test   test

and say I did some processing to my Excel file, for example, remove the merged header and save it to another Excel file:

>> df1.to_excel('new_wb.xlsx', 'Sheet1', merged_cells=False, header=None, index=False)

The column names of new_wb.xlsx looks like this:

        col1    col2   col3   col1.1   col4   col1.2   col2.1   col5
        test    test   test   test     test   test     test     test

It added .1 to the duplicate column names and it also increments as the duplicate column name goes.

I tried renaming the column name before using to_excel() but it didn't work. It seems the renaming of duplicates happens in to_excel().

>> df1.rename(columns=lambda x: x.replace('.1',''))

Upon searching, I found an argument for to_excel() which is mangle_dupe_cols=False, unfortunately it returned:

ValueError: Setting mangle_dupe_cols=False is not supported yet

Any help on how to ignore duplicate column names in saving `to_excel()'

Body:
@Ricky Aguilar has a great solution. I took his solution and just made it more dynamic.

Now you can rename all your duplicate headers, without even knowing what their values are

def dataframe_allowing_duplicate_headers():
    # To Hold All The Possible Duplicate Tags ['.1', '.2', '.3', ...]
    dup_id_range = []

    # Load Your Excel File Using Pandas
    dataframe = pandas.read_excel("path_to_excel_file", sheet_name="sheetname")

    # Generate And Store All The Possible Duplicate Tags ['.1', '.2', '.3', ...]
    for count in range(0, len(dataframe.columns)):
        dup_id_range.append( '.{}'.format(count) )

    # Search And Replace All Duplicate Headers To What It Was Set As Originally
    def rename(dataframe, character_number):
        duplicate_columns_chars = list(
            filter(lambda v: v[(len(v)-character_number):] in dup_id_range,
            dataframe.columns))

        for duplicate_column in duplicate_columns_chars:
            dataframe = dataframe.rename(
                columns={duplicate_column:duplicate_column[:-character_number]})
        return dataframe

    # Replace The Possible Duplicates Respectfully Based On Columns Count
    if len(dup_id_range) > 0:
        dataframe = rename(dataframe, 2)
        if len(dup_id_range) > 9:
            dataframe = rename(dataframe, 3)
            if len(dup_id_range) > 99:
                dataframe = rename(dataframe, 4)
                # If You Have More Than A Thousand Columns (lol)
                #if len(dup_id_range) > 999:
                #    dataframe = rename(dataframe, 5)

    return dataframe

USAGE:

# This Dataframe Will Have All Your Headers, Allowing Your Duplicates
my_dataframe = dataframe_allowing_duplicate_headers()


问:
Can we benefit from DDOS package if we are already using express-rate-limit?
I implemented the Express-rate-limit npm module on my code (nodejs)
I saw the DDOS Module.

Anyone who have good expertise on Nodejs please suggest me that wheher I have to use DDOS module or not.

I installed the module but this will block the request. I read about express rate-limit also, this module is also working same as DDOS.

Someone suggest me that use DDOS. I told that I already used Express-Rate-Limit but he said that Use this also.

I am confused now. Please give me the Proper input regarding this. Any help is really appreciate.

答:
it's fine as basic shield from ddos, or handling external requests for your api methods, that can go-out-of limit.
But if you want to prevent real ddos attacks, your should check debouncing and event throttling. Also think about per-machine custom firewall configurations;)

Dig a bit more into docs of this module ;)

burst Burst is the number or amount of allowable burst requests before
  the client starts being penalized. When the client is penalized, the
  expiration is increased by twice the previous expiration.

bursts = base request counter for 1 unit of time, defined by default as 1 second, or a custom set up

limit

limit is the number of maximum counts allowed (do not confuse that
  with maxcount). count increments with each request. If the count
  exceeds the limit, then the request is denied. Recommended limit is to
  use a multiple of the number of bursts.

requests received => check for the limit. If limit achieved, requester gets a penalty.
When you see a lot of requests(multiple bursts detected).
That's real detection for excide of request limit.
So, 5 bursts set, 20 as limit, when burst detected as 5, it will flag 20 request counter like a fully recognized limitation

maxexpiry

maxexpiry is the seconds of maximum amount of expiration time. In
  order for the user to use whatever service you are providing again,
  they have to wait through the expiration time.

And that's it. Just dive into testing this stuff;)


问:
Display output of command in terminal while using command substitution
So I'm trying to check for the output of a command, but I also want to be able display the output directly in the terminal.

```<code>#!/bin/bash
while :
do
OUT=$(streamlink -o "$NAME" "$STREAM" best)
echo "$OUT"
if [[ $OUT == *"No playable streams"* ]]; then
  echo "Delaying!"
  sleep 15s
fi
done
</code>```

This is what I tried to do.

The code checks if the output of a command contains that error substring, if so it'd add a delay. It works well on that part.

But it doesn't work well when the command is actually successfully downloading a file as it won't perform that echo until it is finished with the download (which would take hours). So until then I have no way of personally checking the output of the command

Plus the output of this particular command displays and updates the speed and filesize in real-time, something echo wouldn't be able to replicate.

So is there a way to be able to display the output of a command in real-time, while also command substituting them in order to check the output for substrings after the command is finished?

答:
Use a temporary file:</p>

```<code>TEMP=$(mktemp) || exit 1

while true
do
    streamlink -o "$NAME" "$STREAM" best |& tee "$TEMP"
    OUT=$( cat "$TEMP" )
    #echo "$OUT" # not longer needed
    if [[ $OUT == *"No playable streams"* ]]; then
        echo "Delaying!"
        sleep 15s
    fi
done

# not really needed here because of endless loop
rm -f "$TEMP"
</code>```

Body:
So I'm trying to check for the output of a command, but I also want to be able display the output directly in the terminal.

#!/bin/bash
while :
do
OUT=$(streamlink -o "$NAME" "$STREAM" best)
echo "$OUT"
if [[ $OUT == *"No playable streams"* ]]; then
  echo "Delaying!"
  sleep 15s
fi
done

This is what I tried to do.

The code checks if the output of a command contains that error substring, if so it'd add a delay. It works well on that part.

But it doesn't work well when the command is actually successfully downloading a file as it won't perform that echo until it is finished with the download (which would take hours). So until then I have no way of personally checking the output of the command

Plus the output of this particular command displays and updates the speed and filesize in real-time, something echo wouldn't be able to replicate.

So is there a way to be able to display the output of a command in real-time, while also command substituting them in order to check the output for substrings after the command is finished?

Body:
Use a temporary file:

TEMP=$(mktemp) || exit 1

while true
do
    streamlink -o "$NAME" "$STREAM" best |& tee "$TEMP"
    OUT=$( cat "$TEMP" )
    #echo "$OUT" # not longer needed
    if [[ $OUT == *"No playable streams"* ]]; then
        echo "Delaying!"
        sleep 15s
    fi
done

# not really needed here because of endless loop
rm -f "$TEMP"


问:
Unit testing, statics, and factories
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

```<code>double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah
</code>```

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you

答:
Statics are evil. Do not touch statics.

"static" here probably means Singletons, i.e. global state. That is indeed difficult to use in unit tests, and can introduce lots of subtle issues, so it is better to avoid it in general. However, static members (fields, methods or inner classes) in general are not necessarily a problem per se.

Do not test privates either, you probably want a class there instead.

This is true in general, if you feel the need to test a private method, it is a sign that your API is not fine grained enough, and the enclosing class may be trying to do too much. Often you may identify some coherent group of functionality which is better to extract into a separate class. This improves your design and in turn makes unit testing easier.

Title: Unit testing, statics, and factories

Body:
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you


问:
3D object material goes black when morph target influence reaches value 1
I include an Object with morphtargets and a standard material into a three.js scene ; the object is loaded from a GLTF export done from Blender ; the morphTarget influences values are working right as long as the value is lower than 1; when it equals 1 the object goes to black. Going back below 1 and the object comes back.

three.js r 104 - Blender 2.80 with gltf 2 exporter.
I'm looking for help on what can cause this ?

答:
Finally I found my mistake. I missed the following line in my code after merging all geometries:
joinedgeometry.computeMorphNormals ();
Everything OK now.
In case this can help someone else ...


问:
UWP app to access only specific folder on user's machine
Declaring an App Capability in manifest file, we can have our UWP app access certain folders such as Pictures, Videos, Music etc.

Moreover, the broadFileSystemAccess capability allows apps to get the same access to the file system as the user who is currently running the app without any additional file-picker style prompts during runtime.

But how about even if the user has access to his/her entire system but wants a UWP app to access only a specific folder needed for the app to have read access. Can we implement such a functionality in a UWP app without using file-picker?

Why do I need that?: Our app reads files from a folder that is too big to be included inside the app and has tons of files of various types inside it. Only read-access is needed.

答:
I'll try to provide you the logic of why your request is conflicting and thus not implemented at the system level.

Sandboxing means that the app has the access only to its own folders. From the system aspect the only exception to that rule could be that some folders are not considered security critical (like Pictures, Music, Downloads) and you may declare access to those folders. The second exception is if the user gives you access to the folder. In both of those cases sandboxing is not broken because the expansion of the sandbox is not arbitrary. As soon as you arbitrarily want to expand the sandbox, there is no difference in safety between having access to whole the system and few folders that you randomly pick. I am not sure how do you see the difference in that - in both case you arbitrarily pick to access some folders just if you have the access to whole the disk you do that from the code while if there was some capability to do that through some declaration then you would do it through declaration. But effects are the same - your app has arbitrary access to the unsafe portions of the disk that depends only on your preferences.


问:
Auth::id() can't find user id and return null, laravel
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

```<code>class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}
</code>```

and LikeController:

```<code>use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}
</code>```

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

```<code>Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);
</code>```

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/

答:
Ok ,

so i was also having that issue with my app when i was using jwt with vue js.
for getting current Auth::user().

You need to pass token with your request.
if you check jwt core file, It getting user from token.
and you are not passing token I guess.

If yes then please pass token along with your request.
And also check the documentation of jwt. did you install your package properly?
remember for laravel 5.5 or greater, that package version to use is jwt > 1.0.0
also, check the documentation of that version properly.

Body:
I am setting like and unlike options on articles. but in LikeController there is problem. when I push the like button it says ->

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id'
  cannot be null (SQL: insert into likes (user_id, article_id,
  updated_at, created_at) values (?, 5, 2019-05-30 07:58:34,
  2019-05-30 07:58:34))

Updated JWT and Routes

Like model:

class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

and LikeController:

use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}

I am not very sure why Auth::id() can't find the user id and return null?

Using JWT with vue.js

Routes:

Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

AuthController and User

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/


问:
ActiveRecord Chartkick
Hi am I'm just working on ActiveRecord for Chartkick as I'm still learning

at the moment
I wrote code for reservation chart

```<code><%= column_chart Reservation.where(:user_id => current_user.id, :status => 2).group(:tool_id).sum(:total) %>
</code>```

it displays fine

however, the red highlight is right but I want this ":tool_id" to change to more text like as "resrvation.tool_id" are the relationship to the "tool.brand"

when i wrote data table and it correct display

```<code>          <td><%= link_to reservation.tool.id, reservation.tool, target: :_blank %></td>
          <td><%= reservation.tool.brand %></td>
</code>```

so I wonder how to tweak tell this chart as a group(:tool_id)change to tool.brand

答:
```<code>Reservation.joins(:tools)
           .where(user_id: current_user.id, status: 2)
           .group('tools.brand')
           .sum('reservations.total)
</code>```

This will group on the name instead of the id so that way you can get a count of all the tools with the same name :D

Title: ActiveRecord Chartkick

Body:
Hi am I'm just working on ActiveRecord for Chartkick as I'm still learning

at the moment
I wrote code for reservation chart

<%= column_chart Reservation.where(:user_id => current_user.id, :status => 2).group(:tool_id).sum(:total) %>

it displays fine

however, the red highlight is right but I want this ":tool_id" to change to more text like as "resrvation.tool_id" are the relationship to the "tool.brand"

when i wrote data table and it correct display

          <%= link_to reservation.tool.id, reservation.tool, target: :_blank %>
          <%= reservation.tool.brand %>

so I wonder how to tweak tell this chart as a group(:tool_id)change to tool.brand

Body:
Reservation.joins(:tools)
           .where(user_id: current_user.id, status: 2)
           .group('tools.brand')
           .sum('reservations.total)

This will group on the name instead of the id so that way you can get a count of all the tools with the same name :D


问:
How to produce a running sequence in Oracle based on report column values
I have the following sample Oracle APEX report by where the Origin ID and Origin Name are retrieved from the origin_tab(id,origin_id,origin_name)

Based on these two column values, I need to generate the Temporary Origin ID value on the fly as part of the selection retrieval from the origin_tab.

The rule behind this is - where the Origin Name is the same against the Origin ID, take the Origin ID value before the dash and append a 3-digit sequence for each Orgin ID as per example below.

Since the origin name (AAA) is the same for the first two records, '001' is appended to the origin id 1111. The same for BBB, '002' is appended to those three records and so forth.

Please note that the Temporary Origin ID here is a string.

```<code>Origin ID         Origin Name        Temporary Origin ID
----------------- ------------------ --------------------
1111-1            AAA                1111001
1111-2            AAA                1111001
1111-3            BBB                1111002
1111-4            BBB                1111002
1111-5            BBB                1111002
1111-6            CCC                1111003
1111-7            DDD                1111004
1111-8            DDD                1111004
</code>```

What approach should I take in my query to achieve the above result, for the Temporary Origin ID?

答:
Make a flag column and put there 1 every time when name changes. You can detect this using lag() or subquery. Then concatenate analytical sum of flag column to 1111.

```<code>select Origin_ID, Origin_Name,
       '1111'||lpad(sum(flag) over (order by origin_id), 3, '0') Temp_Origin_ID
  from (
    select t.*,
           case lag(origin_name) over (order by origin_id) when origin_name then 0 else 1 end flag
      from t)
  order by Origin_ID
</code>```

dbfiddle demo

Body:
I have the following sample Oracle APEX report by where the Origin ID and Origin Name are retrieved from the origin_tab(id,origin_id,origin_name)

Based on these two column values, I need to generate the Temporary Origin ID value on the fly as part of the selection retrieval from the origin_tab.

The rule behind this is - where the Origin Name is the same against the Origin ID, take the Origin ID value before the dash and append a 3-digit sequence for each Orgin ID as per example below.

Since the origin name (AAA) is the same for the first two records, '001' is appended to the origin id 1111. The same for BBB, '002' is appended to those three records and so forth.

Please note that the Temporary Origin ID here is a string.

Origin ID         Origin Name        Temporary Origin ID
----------------- ------------------ --------------------
1111-1            AAA                1111001
1111-2            AAA                1111001
1111-3            BBB                1111002
1111-4            BBB                1111002
1111-5            BBB                1111002
1111-6            CCC                1111003
1111-7            DDD                1111004
1111-8            DDD                1111004

What approach should I take in my query to achieve the above result, for the Temporary Origin ID?

Body:
Make a flag column and put there 1 every time when name changes. You can detect this using lag() or subquery. Then concatenate analytical sum of flag column to 1111.

select Origin_ID, Origin_Name,
       '1111'||lpad(sum(flag) over (order by origin_id), 3, '0') Temp_Origin_ID
  from (
    select t.*,
           case lag(origin_name) over (order by origin_id) when origin_name then 0 else 1 end flag
      from t)
  order by Origin_ID

dbfiddle demo


答:
Static methods basically kill unit testing.

One of the basic ideas when you want to unit test your application is the ability to isolate different portions of your code. You usually do this by wiring mock objects for your environment. You can't wire anything if you are using static methods. Moreover, using static methods hides dependencies between objects.

In your last paragraph you say you want to learn test-driven design. If you are writing your tests after you've written your code your tests are not actually driving anything. Write your tests first.

Regarding private methods, you would usually have full test coverage of the public methods that use those private methods, so you are going to cover them anyway. If you have a really complex private method that you want to test (you should not) just use reflection to make it accessible. I'd rather break encapsulation than having untested code.

Misko Hevery has a very nice post on this topic.

Title: Unit testing, statics, and factories


问:
How to fix RegCreateKeyEx() returned error 5, 'Access is denied.' in SQL Server 2017
I am trying to change auth mode to mix mode with following command in SQL Server 2017:

```<code>EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
                 N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQLServer',
                 N'LoginMode', REG_DWORD, 2
</code>```

I have executed this command so far:

```<code>EXEC sp_addsrvrolemember 'NT AUTHORITY\SYSTEM', 'sysadmin';
GRANT EXECUTE ON xp_instance_regwrite TO public
</code>```

After restarting SQL Service I still get this error:

RegCreateKeyEx() returned error 5, 'Access is denied.'

I have given all permissions to all users in SQL, is this something to do with SQL or Windows and how am I able to fix it?

答: For me to work I had do change the user witch executes SQL Background Service. Click on Windows  -> search for Services and locate MS SQL Server and right click and change properties , at this place you can change sql user to someone with admin permission. not the best way, but it worked.</p>

Body:
I am trying to change auth mode to mix mode with following command in SQL Server 2017:

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
                 N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQLServer',
                 N'LoginMode', REG_DWORD, 2

I have executed this command so far:

EXEC sp_addsrvrolemember 'NT AUTHORITY\SYSTEM', 'sysadmin';
GRANT EXECUTE ON xp_instance_regwrite TO public

After restarting SQL Service I still get this error:

RegCreateKeyEx() returned error 5, 'Access is denied.'

I have given all permissions to all users in SQL, is this something to do with SQL or Windows and how am I able to fix it?


问:
Is there a way to not pass anything to a child prop method?
Error: TypeError: _this.props.handleChange is not a function

I have a React component that has a prop method that is used in another view component.

The problem is that my other view components need to use my Child component but it causes an error because it is required to use the prop method.

class NeedsPropMethod extends Component {
 handleChange = value => {
  // receives the value
 }

 return (
  <Child toy="car" color="blue" handleChange={this.handleChange}>
 )
}

class DoesntNeedPropMethod extends Component {
 return (
  <Child toy="car" color="blue"}>
 )
}

class Child extends Component {
 return (
  this.props.toy; // "car"
  this.props.color; // "blue"
  this.props.handleChange(value) // I do not need this but it gives me the error above
 );
}
```

答:
From Tony Ngo's answer

Child.propTypes = {
  handleChange: PropTypes.func
};
```

<p>then you just have to check if the prop method is used</p>

<pre class="lang-js prettyprint-override"><code>if (this.props.handleChange) {
 // do stuff here
}
</code>```

Body:
From Tony Ngo's answer

Child.propTypes = {
  handleChange: PropTypes.func
};

then you just have to check if the prop method is used

if (this.props.handleChange) {
 // do stuff here
}


问:
Convert gtable into ggplot in R ggplot2
Although gtable could be converted into ggplot using ggplotify::as.ggplot, the output is different from the origin ggplot. For example:

```<code>library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
g <- ggplot_gtable(ggplot_build(p))
p_new <- ggplotify::as.ggplot(p)

# origin
p + theme(aspect.ratio = 2)

# changed
p_new + theme(aspect.ratio = 2)   # different figure shape from the origin one
</code>```

How could I covert gtable into the same ggplot p_new as the origin one p?

答:
You can use  ggplotify::as.ggplot():

```<code>library("ggplotify")
as.ggplot(q)
</code>```

Title: Convert gtable into ggplot in R ggplot2

Body:
Although gtable could be converted into ggplot using ggplotify::as.ggplot, the output is different from the origin ggplot. For example:

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()
g <- ggplot_gtable(ggplot_build(p))
p_new <- ggplotify::as.ggplot(p)

# origin
p + theme(aspect.ratio = 2)

# changed
p_new + theme(aspect.ratio = 2)   # different figure shape from the origin one

How could I covert gtable into the same ggplot p_new as the origin one p?

Body:
You can use  ggplotify::as.ggplot():

library("ggplotify")
as.ggplot(q)


问:
Activity with ProgressBar -> Service -> AsyncTask for downloading - but how to update the progress?
this is the current state/situation: I have an Activity which binds a Service which creates AsyncTasks which downloads various web resources. That works well, but of course the ProgressBar shows nothing.

Previously i had an Activity which created an AsyncTask which downloaded some stuff. The AsyncTask got the View which holds the ProgressBar. So i could update the progress using onProgressUpdate and publishProgress. Obviously this doesn't work any longer because I have no reference to the ProgressBar.

So, do you have any idea on how to update the progress?

Thanks in advance.

答:
Very nice explained indeed just missing the example :)
I went throw it and here it is.</p>

```<code>public class Detail extends Activity {

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
                mProgressDialog.setProgress(intent.getFlags());
            }
        }
    };

    // Flag if receiver is registered
    private boolean mReceiversRegistered = false;
    // Define a handler and a broadcast receiver
    private final Handler mHandler = new Handler();

    @Override
    protected void onResume() {
      super.onResume();

      // Register Sync Recievers
      IntentFilter intentToReceiveFilter = new IntentFilter();
      intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
      this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
      mReceiversRegistered = true;
    }

    @Override
    public void onPause() {
      super.onPause();

      // Make sure you unregister your receivers when you pause your activity
      if(mReceiversRegistered) {
        unregisterReceiver(mIntentReceiver);
        mReceiversRegistered = false;
      }
    }
}

public class DownloadService extends Service {
    private static final String CLASS_NAME = DownloadService.class.getSimpleName();
    private List<Download> downloads = new ArrayList<Download>();
    private int currentPosition;
    public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    private Context ctx;
    @Override
    public IBinder onBind(Intent arg0) {
        ctx = getApplicationContext();
        return mBinder;
    }

    private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... _url) {
            Log.d(Constants.LOG_TAG, CLASS_NAME + " Start the background GetNewsTask \nURL :" + _url[0]);
            int count;
            File finalFile = new File(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
            try {
                if (!finalFile.exists()) {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Donwloading apk from the Web");
                    URL url = new URL(_url[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    // this will be useful so that you can show a tipical 0-100%
                    // progress bar
                    int lenghtOfFile = conexion.getContentLength();
                    // downlod the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    File dir = new File(sdcardPath + Constants.APK_LOCAL_PATH);
                    if (!dir.exists())
                        dir.mkdirs();
                    OutputStream output = new FileOutputStream(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } else {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Apk in SDcard");
                    publishProgress(100);
                }
            } catch (Exception e) {
            }

            return null;

        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            Intent i = new Intent();
            i.setAction(CUSTOM_INTENT);
            i.setFlags(progress[0]);
            ctx.sendBroadcast(i);
        }
    }

    private String splitName(String url) {
        String[] output = url.split("/");
        return output[output.length - 1];
    }

    public static final String CUSTOM_INTENT = "es.tempos21.sync.client.ProgressReceiver";

    private final IDownloadService.Stub mBinder = new IDownloadService.Stub() {

        public void downloadAsynFile(String url) throws DeadObjectException {
            try {
                DownloadFile d = new DownloadFile();
                d.execute(url);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, CLASS_NAME + " " +e.getMessage());         }
        }

        }
};

interface IDownloadService {

    void downloadAsynFile(String url);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Very nice explained indeed just missing the example :)
I went throw it and here it is.

public class Detail extends Activity {

    private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadService.CUSTOM_INTENT)) {
                mProgressDialog.setProgress(intent.getFlags());
            }
        }
    };

    // Flag if receiver is registered
    private boolean mReceiversRegistered = false;
    // Define a handler and a broadcast receiver
    private final Handler mHandler = new Handler();

    @Override
    protected void onResume() {
      super.onResume();

      // Register Sync Recievers
      IntentFilter intentToReceiveFilter = new IntentFilter();
      intentToReceiveFilter.addAction(DownloadService.CUSTOM_INTENT);
      this.registerReceiver(mIntentReceiver, intentToReceiveFilter, null, mHandler);
      mReceiversRegistered = true;
    }

    @Override
    public void onPause() {
      super.onPause();

      // Make sure you unregister your receivers when you pause your activity
      if(mReceiversRegistered) {
        unregisterReceiver(mIntentReceiver);
        mReceiversRegistered = false;
      }
    }
}

public class DownloadService extends Service {
    private static final String CLASS_NAME = DownloadService.class.getSimpleName();
    private List<Download> downloads = new ArrayList<Download>();
    private int currentPosition;
    public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    private Context ctx;
    @Override
    public IBinder onBind(Intent arg0) {
        ctx = getApplicationContext();
        return mBinder;
    }

    private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... _url) {
            Log.d(Constants.LOG_TAG, CLASS_NAME + " Start the background GetNewsTask \nURL :" + _url[0]);
            int count;
            File finalFile = new File(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
            try {
                if (!finalFile.exists()) {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Donwloading apk from the Web");
                    URL url = new URL(_url[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    // this will be useful so that you can show a tipical 0-100%
                    // progress bar
                    int lenghtOfFile = conexion.getContentLength();
                    // downlod the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    File dir = new File(sdcardPath + Constants.APK_LOCAL_PATH);
                    if (!dir.exists())
                        dir.mkdirs();
                    OutputStream output = new FileOutputStream(sdcardPath + Constants.APK_LOCAL_PATH + "/" + splitName(_url[0]));
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } else {
                    Log.i(Constants.LOG_TAG, CLASS_NAME + " Apk in SDcard");
                    publishProgress(100);
                }
            } catch (Exception e) {
            }

            return null;

        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            Intent i = new Intent();
            i.setAction(CUSTOM_INTENT);
            i.setFlags(progress[0]);
            ctx.sendBroadcast(i);
        }
    }

    private String splitName(String url) {
        String[] output = url.split("/");
        return output[output.length - 1];
    }

    public static final String CUSTOM_INTENT = "es.tempos21.sync.client.ProgressReceiver";

    private final IDownloadService.Stub mBinder = new IDownloadService.Stub() {

        public void downloadAsynFile(String url) throws DeadObjectException {
            try {
                DownloadFile d = new DownloadFile();
                d.execute(url);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, CLASS_NAME + " " +e.getMessage());         }
        }

        }
};

interface IDownloadService {

    void downloadAsynFile(String url);
}


问:
GrantPermissionRule unresolved reference
I'm using Android Studio to create an app with kotlin. I'm trying to unit test my MainActivity class and since I'm using API 28, I need to grant permissions in order to run the unit tests. I put @get:Rule var permissionRule = GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO) at the top of my test class, but Android Studio is telling me that GrantPermissionRule is an unresolved reference. My code is below.

MainActivity class:

```<code>class MainActivity : AppCompatActivity(), MediaPlayer.OnCompletionListener {

    lateinit var recorder: MediaRecorder
    lateinit var player: MediaPlayer
    lateinit var file: File
    lateinit var button1: Button
    lateinit var button2: Button
    lateinit var button3: Button
    lateinit var tv1: TextView
    // coding180.com

    override fun onCreate(savedInstanceState: Bundle?) {

        // call the super class onCreate to complete the creation of activity
        // like the view hierarchy
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermissionToRecordAudio()
        }

        tv1 = findViewById(R.id.tv1) as TextView
        button1 = findViewById(R.id.btnStart) as Button
        button2 = findViewById(R.id.btnStop) as Button
        button3 = findViewById(R.id.btnPlay) as Button

        ...

    }
</code>```

Test class:

```<code>@RunWith(RobolectricTestRunner::class)
class MainActivityTest {

    @get:Rule var permissionRule =
             GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO)

    lateinit var testMainActivity: MainActivity

    @Before
    fun setup() {
        testMainActivity = MainActivity()
    }

    @Test
    @Throws(Exception::class)
    fun onCreateTest() {

        //Activity variables
        val intent = Intent()
        val bundle = Bundle()
        intent.putExtras(bundle)
        val controller = Robolectric.buildActivity(MainActivity::class.java,
                                                   intent).create()
        val activity = controller.get() as Activity

        //Start activity
        controller.start()

        //Asserts
        assertFalse(activity.isFinishing)
    }
</code>```

I haven't been able to find anyone else who has this problem. Does anyone know why Android Studio does not recognize GrantPermissionRule and how to fix it?

答:
Your code looks ok, add

```<code>androidTestImplementation 'com.android.support.test:rules:1.0.2'
</code>```

To your build.gradle

Body:
I'm using Android Studio to create an app with kotlin. I'm trying to unit test my MainActivity class and since I'm using API 28, I need to grant permissions in order to run the unit tests. I put @get:Rule var permissionRule = GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO) at the top of my test class, but Android Studio is telling me that GrantPermissionRule is an unresolved reference. My code is below.

MainActivity class:

class MainActivity : AppCompatActivity(), MediaPlayer.OnCompletionListener {

    lateinit var recorder: MediaRecorder
    lateinit var player: MediaPlayer
    lateinit var file: File
    lateinit var button1: Button
    lateinit var button2: Button
    lateinit var button3: Button
    lateinit var tv1: TextView
    // coding180.com

    override fun onCreate(savedInstanceState: Bundle?) {

        // call the super class onCreate to complete the creation of activity
        // like the view hierarchy
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermissionToRecordAudio()
        }

        tv1 = findViewById(R.id.tv1) as TextView
        button1 = findViewById(R.id.btnStart) as Button
        button2 = findViewById(R.id.btnStop) as Button
        button3 = findViewById(R.id.btnPlay) as Button

        ...

    }

Test class:

@RunWith(RobolectricTestRunner::class)
class MainActivityTest {

    @get:Rule var permissionRule =
             GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO)

    lateinit var testMainActivity: MainActivity

    @Before
    fun setup() {
        testMainActivity = MainActivity()
    }

    @Test
    @Throws(Exception::class)
    fun onCreateTest() {

        //Activity variables
        val intent = Intent()
        val bundle = Bundle()
        intent.putExtras(bundle)
        val controller = Robolectric.buildActivity(MainActivity::class.java,
                                                   intent).create()
        val activity = controller.get() as Activity

        //Start activity
        controller.start()

        //Asserts
        assertFalse(activity.isFinishing)
    }

I haven't been able to find anyone else who has this problem. Does anyone know why Android Studio does not recognize GrantPermissionRule and how to fix it?

Body:
Your code looks ok, add

androidTestImplementation 'com.android.support.test:rules:1.0.2'

To your build.gradle


问:
type 'int' is not subtype of type 'String' on Flutter
I modified description value to 1 on my database.

```<code>List<DataEquipmentReg> values = snapshot.data;

 assetArray.add('${values[i].eq_no.toString()} : ${values[i].description.toString()}');
</code>```

After edit description value to String, Error is not coming

DataEquipmentReg POJO Class

```<code>class DataEquipmentReg {
 final String eq_no;
  final String description;
}
</code>```

Widget

```<code>   Text(assetArray[index].toString(),),
</code>```

Database in sqlite

```<code>  await db.execute("""CREATE TABLE EquipmentRegTable(eq_no STRING, description STRING)""");
</code>```

答:
I solved this problem like this,

in my read data on cache method, I changed this,

```<code>  Future<List<DataEquipmentReg>> displayEquipmentReg() async {
    var db = await db1;
    final List<Map<String, dynamic>> maps = await db.query('EquipmentRegTable');

    return List.generate(maps.length, (i) {
      return DataEquipmentReg(
        eq_no: '${maps[i]['eq_no']}',
        description'${ maps[i]['description']}',
      );
    });
  }
</code>```

Body:
I modified description value to 1 on my database.

List<DataEquipmentReg> values = snapshot.data;

 assetArray.add('${values[i].eq_no.toString()} : ${values[i].description.toString()}');

After edit description value to String, Error is not coming

DataEquipmentReg POJO Class

class DataEquipmentReg {
 final String eq_no;
  final String description;
}

Widget

   Text(assetArray[index].toString(),),

Database in sqlite

  await db.execute("""CREATE TABLE EquipmentRegTable(eq_no STRING, description STRING)""");

Body:
I solved this problem like this,

in my read data on cache method, I changed this,

  Future<List<DataEquipmentReg>> displayEquipmentReg() async {
    var db = await db1;
    final List<Map<String, dynamic>> maps = await db.query('EquipmentRegTable');

    return List.generate(maps.length, (i) {
      return DataEquipmentReg(
        eq_no: '${maps[i]['eq_no']}',
        description'${ maps[i]['description']}',
      );
    });
  }


问:
Custom SignUpURL in Android Management API
I am trying to implement Android Management API in my project where the first step is to create an enterprise:

Post the Callbackurl and ProjectID to the Following URL
   https://androidmanagement.googleapis.com/v1/signupUrls

I get the response name and url:

```<code>{
  "name": "signupUrls/C265d41bc093bdd97",
  "url": "https://play.google.com/work/adminsignup?token=someToken"
}
</code>```

How can I Change this "url" parameter to my own. Do I require to upload my DPC to playstore?

I am out of guesses. please help

Thanks in advance.

答:
The flow is this:

1) Create a Project in Google developer console, enable Android Management API, create credentials and get the project id. (I think you already done that).

2) Create a SignupUrl with signupUrls.create. (What you have done to get that JSON)

3) Keep the SignupUrl Name and redirect the user (or go) to the returned URL (inside the JSON posted).

3) Follow the procedure to create an enterprise.

This will start the creation of an enterprise to the signed Google Account.

4) At the end of the procedure you will be redirected to the callbackUrl specified inside  signupUrls.create. Appended to the callbackUrl, as a GET query parameter, will be a token.

5) You must use the appended token to conclude the flow calling the API enterprises.create with these parameters:

The signup url name

The enterprise token returned as parameter

(optional) a request body with some enterprise parameters (logo, name, etc)

At the end of this coming and going between URLs and API calls, you will end with an Enterprise created on the Google Account and the enterprise ID in the form enterprise/<yourID> to interact with the API.

You can check all the Enterprise infos at the created Google Play for Work (or Managed Google Play) at http://play.google.com/work . Left menu "Administration Settings" at check your enterpriseId.

Body:
I am trying to implement Android Management API in my project where the first step is to create an enterprise:

Post the Callbackurl and ProjectID to the Following URL
   https://androidmanagement.googleapis.com/v1/signupUrls

I get the response name and url:

{
  "name": "signupUrls/C265d41bc093bdd97",
  "url": "https://play.google.com/work/adminsignup?token=someToken"
}

How can I Change this "url" parameter to my own. Do I require to upload my DPC to playstore?

I am out of guesses. please help

Thanks in advance.


问:
Request Sends More Than One Using Ajax.BeginForm and Jquery.Unobtrusive
HTML Form sends POST request more than one. I am using jquery.unobtrusive-ajax.js for async connection.

When I submit the form request has been sent to server two times. These two connections' details are listed in the Browser's Network -> XHR tab.

Thank you for your suggestions and helps.

My HTML form and my JS files as follows:

JS

```<code><script src="/assets/content/js/jquery.unobtrusive-ajax.js"></script>
<script src="/assets/global/scripts/datatable.js" type="text/javascript"></script>
<script src="/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
<script src="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.js" type="text/javascript"></script>
<script src="/assets/global/plugins/bootstrap-toastr/toastr.min.js" type="text/javascript"></script>
<script src="/assets/content/js/jquery.unobtrusive-ajax.js"></script>
</code>```

HTML Form

```<code>@using (Ajax.BeginForm("UpdateDocument", "Document",
new AjaxOptions()
{
    HttpMethod = "POST",
    OnBegin = "Document.documentUpdateBegin",
    OnSuccess = "Document.documentUpdateSuccess",
    OnFailure = "Document.documentUpdateFailure"
}))
{
<div class="form-body">

    <input type="hidden" name="ID" value="@Model.DocumentItem.ID" />

    <div class="form-group form-md-line-input form-md-floating-label">
        <input type="text"
            class="form-control"
            name="Title" id="title"
            autocomplete="off"
            maxlength="250"
            value="@Model.DocumentItem.Title"
            required="required" />
        <label for="title_value">Title</label>
        <span class="help-block">Max 250 characters</span>
    </div>

    <div class="form-group form-md-line-input form-md-floating-label">
        <label class="control-label col-md-2"
            style="padding-left: 0px; margin: 5px 0px; color: #888;">
            Durum</label>
        <div class="col-md-2">
            @Html.CheckBox("IsActive", Model.DocumentItem.IsActive,
            new
            {
                @class = "make-switch",
                id = "is_active",
                data_on_text = " Aktif ",
                data_off_text = " Pasif "
            })
        </div>
    </div>
</div>
<div class="form-actions noborder margin-top-20">
    <div class="col-md-2">
        <button type="submit" class="btn btn-block blue">UPDATE</button>
    </div>
</div>
}
</code>```

答:
I found the solution.

There are two javascript jquery.unobtrusive-ajax.js file declaration in JS section.

After I removed the second  problem is solved.

Body:
HTML Form sends POST request more than one. I am using jquery.unobtrusive-ajax.js for async connection.

When I submit the form request has been sent to server two times. These two connections' details are listed in the Browser's Network -> XHR tab.

Thank you for your suggestions and helps.

My HTML form and my JS files as follows:

JS

HTML Form

@using (Ajax.BeginForm("UpdateDocument", "Document",
new AjaxOptions()
{
    HttpMethod = "POST",
    OnBegin = "Document.documentUpdateBegin",
    OnSuccess = "Document.documentUpdateSuccess",
    OnFailure = "Document.documentUpdateFailure"
}))
{

    <input type="hidden" name="ID" value="@Model.DocumentItem.ID" />

        <input type="text"
            class="form-control"
            name="Title" id="title"
            autocomplete="off"
            maxlength="250"
            value="@Model.DocumentItem.Title"
            required="required" />
        Title
        Max 250 characters

            Durum

            @Html.CheckBox("IsActive", Model.DocumentItem.IsActive,
            new
            {
                @class = "make-switch",
                id = "is_active",
                data_on_text = " Aktif ",
                data_off_text = " Pasif "
            })

        <button type="submit" class="btn btn-block blue">UPDATE</button>

}

Body:
I found the solution.

There are two javascript jquery.unobtrusive-ajax.js file declaration in JS section.

After I removed the second <script src="/assets/content/js/jquery.unobtrusive-ajax.js"></script> problem is solved.


问:
How to update XML file with lxml
I want to update xml file with new information by using lxml library.
For example, I have this code:

```<code>>>> from lxml import etree
>>>
>>> tree = etree.parse('books.xml')
</code>```

where 'books.xml' file, has this content: http://www.w3schools.com/dom/books.xml

I want to update this file with new book:

```<code>>>> new_entry = etree.fromstring('''<book category="web" cover="paperback">
... <title lang="en">Learning XML 2</title>
... <author>Erik Ray</author>
... <year>2006</year>
... <price>49.95</price>
... </book>''')
</code>```

My question is, how can I update tree element tree with new_entry tree and save the file.

答:
I don't have enough reputation to comment, therefore I'll write an answer...

The most simple change make the code of Guillaume work is to change the line

```<code>f = open('books-mod.xml', 'w')
</code>```

to

```<code>f = open('books-mod.xml', 'wb')
</code>```

Title: How to update XML file with lxml

Body:
I want to update xml file with new information by using lxml library.
For example, I have this code:

>>> from lxml import etree
>>>
>>> tree = etree.parse('books.xml')

where 'books.xml' file, has this content: http://www.w3schools.com/dom/books.xml

I want to update this file with new book:

>>> new_entry = etree.fromstring('''<book category="web" cover="paperback">
... <title lang="en">Learning XML 2</title>
... <author>Erik Ray</author>
... <year>2006</year>
... <price>49.95</price>
... </book>''')

My question is, how can I update tree element tree with new_entry tree and save the file.

Body:
I don't have enough reputation to comment, therefore I'll write an answer...

The most simple change make the code of Guillaume work is to change the line

f = open('books-mod.xml', 'w')

to

f = open('books-mod.xml', 'wb')