问:
Django CRUD template not showing up
Im making a CRUD application using class instances.
My app is a very simple accounting app:

Django: 3.03
Python: 3.8.0

accounts/models.py

```<code>class Project(models.Model):
    ## normal fields
</code>```

accounts/views.py

```<code>class ProjectCreate(CreateView):
    model = Project
    fields = '__all__'

class ProjectUpdate(UpdateView):
    model = Project
    fields = '__all__'

class ProjectDelete(DeleteView):
    model = Project
    success_url = reverse_lazy('project')
</code>```

accounts/urls.py:

```<code>urlpatterns = [

path('project/create/', project_views.ProjectCreate.as_view(), name='project_create'),
    path('project/<int:pk>/update/', project_views.ProjectUpdate.as_view(), name='project_update'),
    path('project/<int:pk>/delete/', project_views.ProjectDelete.as_view(), name='project_delete'),

]
</code>```

I have 2 template files under the following directory:

```<code>accounts
    accounts
        templates
            project
                project_form.html
                project_confirm_delete.html
        models.py
        urls.py
        views.py
        forms.py
</code>```

When i call the view:

http://localhost:8000/accounts/project/create/

I get the following error:

```<code>47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: accounts/project_form.html
</code>```

settings.py:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'accounts.utils.accounts_vars',
            ],
        },
    },
]
</code>```

I cant figure out why this is not working. Can you please help.
Any help would be much appreciated. Thanks.

答:
You are not telling your views which template to use. You do this by setting the template_name parameter in your view, e.g.:

```<code>class ProjectUpdate(UpdateView):
      model = Project
      fields = '__all__'
      template_name = 'project/project_form.html
</code>```

'

Title: Django CRUD template not showing up

Body:
Im making a CRUD application using class instances.
My app is a very simple accounting app:

Django: 3.03
Python: 3.8.0

accounts/models.py

class Project(models.Model):
    ## normal fields

accounts/views.py

class ProjectCreate(CreateView):
    model = Project
    fields = '__all__'

class ProjectUpdate(UpdateView):
    model = Project
    fields = '__all__'

class ProjectDelete(DeleteView):
    model = Project
    success_url = reverse_lazy('project')

accounts/urls.py:

urlpatterns = [

path('project/create/', project_views.ProjectCreate.as_view(), name='project_create'),
    path('project/<int:pk>/update/', project_views.ProjectUpdate.as_view(), name='project_update'),
    path('project/<int:pk>/delete/', project_views.ProjectDelete.as_view(), name='project_delete'),

]

I have 2 template files under the following directory:

accounts
    accounts
        templates
            project
                project_form.html
                project_confirm_delete.html
        models.py
        urls.py
        views.py
        forms.py

When i call the view:

http://localhost:8000/accounts/project/create/

I get the following error:

47, in select_template
    raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain)
django.template.exceptions.TemplateDoesNotExist: accounts/project_form.html

settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
                'accounts.utils.accounts_vars',
            ],
        },
    },
]

I cant figure out why this is not working. Can you please help.
Any help would be much appreciated. Thanks.

Body:
You are not telling your views which template to use. You do this by setting the template_name parameter in your view, e.g.:

class ProjectUpdate(UpdateView):
      model = Project
      fields = '__all__'
      template_name = 'project/project_form.html

'


来源: stackexchange

问:
'ImportError: No module named pillow' in PyCharm
I'm getting an error while using PyCharm which doesn't allow me to import the pillow module even though I have it installed as a package in the project interpreter. Any help is greatly appreciated!

http://imgur.com/a/DfjC3

答:
After running this command on your terminal

pip install pillow
```

and you are sure it was installed, but still having same problem of PIL module not found.

Go to your  IDE and make sure existing interpreter is set to python interpreter and not anaconda

ContentLicense: CC BY-SA 3.0

Body:
After running this command on your terminal

pip install pillow

and you are sure it was installed, but still having same problem of PIL module not found.

Go to your  IDE and make sure existing interpreter is set to python interpreter and not anaconda

ContentLicense: CC BY-SA 4.0


问:
Inheritance base class reference C#
```<code>class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();
</code>```

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"

答:
It's still a reference, a pointer to the object on the heap.  It is of type Drifted.

Even though your reference is of the Base type, the underlying object is Drifted and any overridden members in the derived class Drifted will be used instead of those on Base, even though you are trying to use Base.

In the case of member hiding using the new syntax, if you have a reference to the base type it will bypass any derived classes that are hiding the members.

An overview can be found online with Googling for "C# Reference Types".  I skimmed this, looks like a worthwhile read:

http://www.albahari.com/valuevsreftypes.aspx

Title: Inheritance base class reference C#

Body:
class Base
    {
        //...
        public int i = 5;
    }

class Drifted : Base
{
    //...
    public int b = 10;
}

Base ObjectOrReference = new Drifted();

So Base ObjectOrReference;is reference to the base type.
When we write Base ObjectOrReference = new Drifted(); it becomes object because by using 'new' we allocate memory for it? Or it still reference and if it is true, what type does it have?
Direct question is: "Is ObjectOrReference object?"


问:
Result set larger than one row when Corda node use postgresql and schema
I'm currently trying to have 2 node (one notary , one normal node) using the same Postgresql DB for storing data (instead of the embedded H2), but with a different schema for each (node schema, notary schema) .

Ah , I'm using the non-enterprise version btw, version 4.3 .

The notary node is the first one to start, it creates the needed tables in the notary schema , all seems fine there .

But when the 'normal' node boot, it crash saying :

```<code>[ERROR] 10:17:50+0000 [main] changelog.ChangeSet. - Change Set migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda failed.  Error: Migration failed for change set mig │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  {changeSet=migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda, databaseChangeLog=master.changelog.json}                                                              │
│ [ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node registration: Could not create the DataSource: Migration failed for change set migration/node-core.changelog-postgres-blob.xml: │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  [errorCode=14m37zv, moreInformationAt=https://errors.corda.net/OS/4.3/14m37zv]                                                                                │
[ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node startup: net.corda.core.utilities.Try$Failure cannot be cast to net.corda.core.utilities.Try$Success [errorCode=rmnkpl, moreInf │

</code>```

The node.conf I have for the notary is the following :

```<code>dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=notary"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}
</code>```

And the one for the 'normal' node is :

```<code>dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=node"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

</code>```

So as you can see, the only difference is the ?currentSchema value .

Am I missing something ?

EDIT :

in the doc , they are saying :

If your PostgresSQL database is hosting multiple schema instances (using the JDBC URL currentSchema=my_schema) for different Corda nodes, you will need to create a hibernate_sequence sequence object manually for each subsequent schema added after the first instance. Corda doesn’t provision Hibernate with a schema namespace setting and a sequence object may be not created. Run the DDL statement and replace my_schema with your schema namespace:

I have done that and when connecting to the db , I can see taht for both schema I have tables created . Though for the notary I have 32 tables and only 26 for the 'normal' node .

答:
I was trying to use different schemes for different nodes. But i failed. Because there are some automatically-created tables without scheme. So i decided to use different database instances on the same db server.

I think this method might relieve your pain a little bit.

Body:
I'm currently trying to have 2 node (one notary , one normal node) using the same Postgresql DB for storing data (instead of the embedded H2), but with a different schema for each (node schema, notary schema) .

Ah , I'm using the non-enterprise version btw, version 4.3 .

The notary node is the first one to start, it creates the needed tables in the notary schema , all seems fine there .

But when the 'normal' node boot, it crash saying :

[ERROR] 10:17:50+0000 [main] changelog.ChangeSet. - Change Set migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda failed.  Error: Migration failed for change set mig │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  {changeSet=migration/node-core.changelog-postgres-blob.xml::modify checkpoint_value column type::R3.Corda, databaseChangeLog=master.changelog.json}                                                              │
│ [ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node registration: Could not create the DataSource: Migration failed for change set migration/node-core.changelog-postgres-blob.xml: │
│      Reason:                                                                                │
│           master.changelog.json : liquibase.precondition.core.SqlPrecondition@7c682e26 : Result set larger than one row                                                                                │
│  [errorCode=14m37zv, moreInformationAt=https://errors.corda.net/OS/4.3/14m37zv]                                                                                │
[ERROR] 10:17:50+0000 [main] internal.NodeStartupLogging. - Exception during node startup: net.corda.core.utilities.Try$Failure cannot be cast to net.corda.core.utilities.Try$Success [errorCode=rmnkpl, moreInf │

The node.conf I have for the notary is the following :

dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=notary"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

And the one for the 'normal' node is :

dataSourceProperties: {
    dataSourceClassName="org.postgresql.ds.PGSimpleDataSource"
    dataSource.url="jdbc:postgresql://psql-path:5432/postgres?currentSchema=node"
    dataSource.user="dbUser"
    dataSource.password="xxxxxx"
}

So as you can see, the only difference is the ?currentSchema value .

Am I missing something ?

EDIT :

in the doc , they are saying :

If your PostgresSQL database is hosting multiple schema instances (using the JDBC URL currentSchema=my_schema) for different Corda nodes, you will need to create a hibernate_sequence sequence object manually for each subsequent schema added after the first instance. Corda doesn’t provision Hibernate with a schema namespace setting and a sequence object may be not created. Run the DDL statement and replace my_schema with your schema namespace:

I have done that and when connecting to the db , I can see taht for both schema I have tables created . Though for the notary I have 32 tables and only 26 for the 'normal' node .


问:
Android Kotlin How to update content in current activity on FirebaseMessagingService onMessageReceived?
The scenario is when user open chat activity and after that a firebase chat data notification is received. Code below,

```<code>class myFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // how do i update chat content here?
        // startActivity with FLAG_ACTIVITY_NEW_TASK will restart the activity
        // startActivity with FLAG_ACTIVITY_REORDER_TO_FRONT will crash the app
        // or is there a way to call a method in chat activity to update it's content?
    }
}
</code>```

How do i update chat content in the currently openned chat activity/screen?

答:
You can add a listener in the chat activity, that is notified when notification is received

create new file:

```<code>class NotificationReceivedListener {

    var listener: OnNotificationReceivedListener? = null

    interface OnNotificationReceivedListener{
        fun onNotificationReceived(bundle: Bundle?)
    }

    fun setOnNotificationReceivedListener(param: OnNotificationReceivedListener) {
        listener = param
    }

    fun notificationReceived(bundle: Bundle?){

        listener?.let {
            it.onNotificationReceived(bundle)
        }
    }

}
</code>```

in FirebaseMessagingService companion object:

```<code>var notificationReceivedListener = NotificationReceivedListener()
</code>```

in onMessageReceived:

```<code>notificationReceivedListener.notificationReceived(payloadBundle)
</code>```

in activity:

```<code>MyFirebaseMessagingService.notificationReceivedListener.setOnNotificationReceivedListener(object :
NotificationReceivedListener.OnNotificationReceivedListener {
                    override fun onNotificationReceived(args: Bundle?) {
                          activity!!.runOnUiThread( {...})
            }
</code>```

Body:
The scenario is when user open chat activity and after that a firebase chat data notification is received. Code below,

class myFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // how do i update chat content here?
        // startActivity with FLAG_ACTIVITY_NEW_TASK will restart the activity
        // startActivity with FLAG_ACTIVITY_REORDER_TO_FRONT will crash the app
        // or is there a way to call a method in chat activity to update it's content?
    }
}

How do i update chat content in the currently openned chat activity/screen?

Body:
You can add a listener in the chat activity, that is notified when notification is received

create new file:

class NotificationReceivedListener {

    var listener: OnNotificationReceivedListener? = null

    interface OnNotificationReceivedListener{
        fun onNotificationReceived(bundle: Bundle?)
    }

    fun setOnNotificationReceivedListener(param: OnNotificationReceivedListener) {
        listener = param
    }

    fun notificationReceived(bundle: Bundle?){

        listener?.let {
            it.onNotificationReceived(bundle)
        }
    }

}

in FirebaseMessagingService companion object:

var notificationReceivedListener = NotificationReceivedListener()

in onMessageReceived:

notificationReceivedListener.notificationReceived(payloadBundle)

in activity:

MyFirebaseMessagingService.notificationReceivedListener.setOnNotificationReceivedListener(object :
NotificationReceivedListener.OnNotificationReceivedListener {
                    override fun onNotificationReceived(args: Bundle?) {
                          activity!!.runOnUiThread( {...})
            }


问:
How to make a complex robot model in webots?
I make my robot using cyberbotics webots. I can’t figure out how to make a beautiful 3D model. At least at the mantis hexapod level.
I understand that you can import ready-made fraud only in vrml97 format, but it is not supported by fusion 360 and other programs.
But in webots itself, I did not find a way to build a model more complicated than using cubes, pyramids, and other simple objects.
There was also an idea to assemble a model from a large number of rectangles using grouping, but it seems to me that such a model will greatly slow down.
Is it possible to see how the finished robots are made, and make changes to them?</p>

答:
The node you are looking for is the IndexedFaceSet https://www.cyberbotics.com/doc/reference/indexedfaceset, it allows you to efficiently model a shape using a set of triangle faces, you will find an example of this in this simulation world: https://cyberbotics.com/doc/guide/samples-geometries#high_resolution_indexedfaceset-wbt

One possible workflow to do this is to use Blender to create your mesh and then use the Webots exporter to export it to Webots: https://github.com/cyberbotics/blender-webots-exporter


问:
How to Create a Global Function then use on Controller
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

```<code>Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function
</code>```

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.

答:
I've edited Jerdine Saibo's answer.
By the time it gets approved, here's an updated code. (pRound methods needs to be static)</p>

```<code>namespace ProjectName.Functions
{
   public static class Utility
   {
      public static float pRound(float number, int digits){
         float result = 0;
         // your code here
         return result;
      }
   }
}
</code>```

Body:
Im From VB.net base want to learn ASP.NET MVC

For Example : Function created below (how to create in global folder/cs and how to call it then use in Controller)

Function pRound(Number ,NumDigits)
    Dim dblPower, vPSTEmp, intSgn

    dblPower = 10 ^ NumDigits
    vPSTEmp = CDbl(Number * dblPower + 0.5)
    pRound = Int(vPSTEmp) / dblPower
End Function

For vb I just add <--#include file="include/function.asp"-->

then can use it like pRound(number, 4)

Please Teach Me How to Do it. Thx a lot.

Body:
I've edited Jerdine Saibo's answer.
By the time it gets approved, here's an updated code. (pRound methods needs to be static)

namespace ProjectName.Functions
{
   public static class Utility
   {
      public static float pRound(float number, int digits){
         float result = 0;
         // your code here
         return result;
      }
   }
}


问:
how to make modal movable from one end to other end using vue js
Have code like this in vue.js ,my agenda is to make the modal movable from one end to other end, here is my code,have used bootstrap modal for this purpose and have included : draggable </p>

```<code><b-modal ref="my-modal" hide-footer title="Edit Record">
    <div class="card">
        <div class="card-header d-flex justify-content-between">
            <div class="">Viz Attributes</div>
        </div>

        <div class="card-body">
        </div>
    </div>
</b-modal>
</code>```

答:
you can't position them absolutely in the viewport.

You would need to change the positioning of the modal dialog sub-container to absolute and control the left/top position based on dragging. This is not an overly easy task.  You would need to create your own modal to draggable.
I suggest to you use Vue.js modal component  DEMO: www.vue-js-modal.yev.io
install: www.npmjs.com/package/vue-js-modal

<modal name="bar" draggable=".window-header">

DRAG ME HERE

     Hello!

</modal>```

Draggable property can accept not only Boolean but also String parameters.

Body:
Have code like this in vue.js ,my agenda is to make the modal movable from one end to other end, here is my code,have used bootstrap modal for this purpose and have included : draggable

Viz Attributes

Body:
you can't position them absolutely in the viewport.

You would need to change the positioning of the modal dialog sub-container to absolute and control the left/top position based on dragging. This is not an overly easy task.  You would need to create your own modal to draggable.
I suggest to you use Vue.js modal component  DEMO: www.vue-js-modal.yev.io
install: www.npmjs.com/package/vue-js-modal

<modal name="bar" draggable=".window-header">
  <div class="window-header">DRAG ME HERE</div>
  <div>
     Hello!
  </div>
</modal>

Draggable property can accept not only Boolean but also String parameters.


问:
Haxm installed but it shows install haxm required
in my sdk manager haxm IS installed

but

how can i handle this error?

答:
Faced this issue few days ago,  Here's how i fixed it:

Close Android Studio

Remove/UnInstall HaxM

Run AndroidStudio  as Admin

Re-Install HaxM

Thats it.


问:
Scheme/"The Seasoned Schemer": Question about the syntax of the definition of "try" function
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

```<code>(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))
</code>```

where letcc is defined as

```<code>(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))
</code>```

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

```<code>(letcc success
       (letcc var (success a)) . b)
</code>```

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

```<code>(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4
</code>```

答:
Let us try and see what happens.  I am using mit-scheme.

File try.scm:

```<code>(define-syntax letcc
  (syntax-rules ()
     ((letcc var body ...)
      (call-with-current-continuation
          (lambda (var)  body ... )))))

(define-syntax try
  (syntax-rules ()
     ((try var a . b)
      (letcc success
        (letcc var (success a)) . b))))

(try var (+ 1 1) 4)

(try var (var '(2)) 4)
</code>```

First step: you compile the file:

```<code>> (sf "try")
</code>```

This will generate the try.bin.

Second step, print the desugared syntax:

```<code>> (pp (unsyntax (fasload "try")))

;Loading "try.bin"... done
 ................
 (call-with-current-continuation
  (lambda (success)
    (call-with-current-continuation
        (lambda (var) (success (+ 1 1))))
    4))
 (call-with-current-continuation
  (lambda (success)
    (call-with-current-continuation
        (lambda (var) (success (var '(2)))))
    4)))
</code>```

Now you see explicitly what is executed, hence the result.

In the case of (try var (+ 1 1) 4) you jump out 2 nested calcc, as you call success with value 2, while in the (try var (var '(2)) 4) you jump out 1 level and the 4 from the sequence of the 1st continuation will be returned.

Body:
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))

where letcc is defined as

(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

(letcc success
       (letcc var (success a)) . b)

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4

Body:
Let us try and see what happens.  I am using mit-scheme.

File try.scm:

(define-syntax letcc
  (syntax-rules ()
     ((letcc var body ...)
      (call-with-current-continuation
          (lambda (var)  body ... )))))

(define-syntax try
  (syntax-rules ()
     ((try var a . b)
      (letcc success
        (letcc var (success a)) . b))))

(try var (+ 1 1) 4)

(try var (var '(2)) 4)

First step: you compile the file:

> (sf "try")

This will generate the try.bin.

Second step, print the desugared syntax:

> (pp (unsyntax (fasload "try")))

;Loading "try.bin"... done
 ................
 (call-with-current-continuation
  (lambda (success)
    (call-with-current-continuation
        (lambda (var) (success (+ 1 1))))
    4))
 (call-with-current-continuation
  (lambda (success)
    (call-with-current-continuation
        (lambda (var) (success (var '(2)))))
    4)))

Now you see explicitly what is executed, hence the result.

In the case of (try var (+ 1 1) 4) you jump out 2 nested calcc, as you call success with value 2, while in the (try var (var '(2)) 4) you jump out 1 level and the 4 from the sequence of the 1st continuation will be returned.


问:
Grep a "text" and print all the line before and after the text. each log session is separated by 2 blank lines
```<code>1
1
1
1
  Text
11
1
1
1
</code>```

The text above can be anywhere therefore grep -C wont help.
I have tried that using AWK but i want to do it using grep

```<code>zgrep -C25 "Text" engine.*.log.gz
</code>```

doesn't work as text may appear anywhere

I know the awk option but it doesn't work on .gz file i have to convert it its a lengthy  process

  awk -v RS= '/Text/' engine.*.log.gz

答:
Thank you so much for the help, but I figured out the solution

zgrep -C34 "text" engine.*.log.gz |awk  '/20yy-mm-dd hh:mm:ss/,/SENT MESSAGES (asynchronous)/'

Search the "text" along side 34 lines before and after it to get average out all the lines required

All of my logs session always begins with date and time so is used AWK for that

All of my logs session always ends with "SENT MESSAGES (asynchronous):" So AWK did that trick for me.

Body:
1
1
1
1
  Text
11
1
1
1

The text above can be anywhere therefore grep -C wont help.
I have tried that using AWK but i want to do it using grep

zgrep -C25 "Text" engine.*.log.gz

doesn't work as text may appear anywhere

I know the awk option but it doesn't work on .gz file i have to convert it its a lengthy  process

  awk -v RS= '/Text/' engine.*.log.gz


问:
Set range equal to multiple named ranges with line break
I am setting a range variable equal to a list of ranges. The list is so long that I would like to use a line break for easier management. However, I am having a tough time getting the syntax. I've tried many combinations.

The code in one line works and looks like this (with a lot more named ranges):

```<code>Dim xNamedRangeList As Range
Set xNamedRangeList = Range("NamedRange1, NamedRange2")
</code>```

My best attempt so far is this.

```<code>Set xNamedRangeList = " Range(""" & _
"NamedRange1," & _
"NamedRange2" &_
""")"
</code>```

Debug.print looks like this: Ranged("NamedRange1, NamedRange2")

While this works in debug.print, it sure doesn't work when I set xNamedRangeList equal to it. I think I've turned the formula into a string, but not sure how to make it work in the formula.

答:
The correct syntax would be as shown by @TimWilliams.

But you say "with a lot more named ranges", so please note that the length an address used in Range(address) can have is limited to 255 characters. So if you have a lot of ranges you might hit that limit and it doesn't work.

If that might be the case you must use the Application.Union method:

```<code>Dim xNamedRangeList As Range
Set xNamedRangeList = Application.Union(Range("NamedRange1"), Range("NamedRange2"))
</code>```

Line breaks are always Space followed by underscore _ and Enter.

```<code>Set xNamedRangeList = Application.Union(Range("NamedRange1"), _
Range("NamedRange2"))
</code>```

Body:
I am setting a range variable equal to a list of ranges. The list is so long that I would like to use a line break for easier management. However, I am having a tough time getting the syntax. I've tried many combinations.

The code in one line works and looks like this (with a lot more named ranges):

Dim xNamedRangeList As Range
Set xNamedRangeList = Range("NamedRange1, NamedRange2")

My best attempt so far is this.

Set xNamedRangeList = " Range(""" & _
"NamedRange1," & _
"NamedRange2" &_
""")"

Debug.print looks like this: Ranged("NamedRange1, NamedRange2")

While this works in debug.print, it sure doesn't work when I set xNamedRangeList equal to it. I think I've turned the formula into a string, but not sure how to make it work in the formula.

Body:
The correct syntax would be as shown by @TimWilliams.

But you say "with a lot more named ranges", so please note that the length an address used in Range(address) can have is limited to 255 characters. So if you have a lot of ranges you might hit that limit and it doesn't work.

If that might be the case you must use the Application.Union method:

Dim xNamedRangeList As Range
Set xNamedRangeList = Application.Union(Range("NamedRange1"), Range("NamedRange2"))

Line breaks are always Space followed by underscore _ and Enter.

Set xNamedRangeList = Application.Union(Range("NamedRange1"), _
Range("NamedRange2"))


问:
Fastest way to see added, removed, and changed Objects (not primitives) between two arrays
I have a completely manual, ugly way to find all added, removed, and changed Objects (not primitives) between two arrays, and I'm wondering if there is a faster, more efficient way to accomplish this same thing. Any libraries that accomplish this?  the lodash difference function tells me all differences rather than which ones have been added and which have changed, so it doesn't do what I need.

Here is my code.  It works, and i want to do exactly this, just the most efficient way available:

```<code>    let previousState = state[0]; //<-- an array of object literals
    let currentState = state[1]; //<-- an array of object literals

    let added = [];
    let removed = [];
    let edited = [];

    for(let i = 0; i < previousState.length; i++){
        let old = previousState[i];
        let current = currentState.find(x => x.id === old.id);
        if(!current){
            removed.push(current);
        }
    }

    for(let i = 0; i < currentState.length; i++){
        let current = currentState[i];
        let old = previousState.find(x => x.id === current.id);
        if(!old){
            added.push(current);
            continue;
        }
        if(!_.isEqual(current, old)){ //<-- this is the lodash .isEqual function
            edited.push(current);
        }
    }
</code>```

答:
From what I measured this is a bit more than twice as fast as the original algorithm.</p>

```<code>let control = {};
state[0].forEach(s => {
  control[s.id] = s;
});

let added = [];
let edited = [];

state[1].forEach(s => {
  if (control[s.id]) {
    if (!_.isEqual(control[s.id], s)) {
      edited.push(s);
    }
    delete control[s.id];
  } else {
    added.push(s);
  }
});

let removed = Object.values(control);
</code>```

Body:
I have a completely manual, ugly way to find all added, removed, and changed Objects (not primitives) between two arrays, and I'm wondering if there is a faster, more efficient way to accomplish this same thing. Any libraries that accomplish this?  the lodash difference function tells me all differences rather than which ones have been added and which have changed, so it doesn't do what I need.

Here is my code.  It works, and i want to do exactly this, just the most efficient way available:

    let previousState = state[0]; //<-- an array of object literals
    let currentState = state[1]; //<-- an array of object literals

    let added = [];
    let removed = [];
    let edited = [];

    for(let i = 0; i < previousState.length; i++){
        let old = previousState[i];
        let current = currentState.find(x => x.id === old.id);
        if(!current){
            removed.push(current);
        }
    }

    for(let i = 0; i < currentState.length; i++){
        let current = currentState[i];
        let old = previousState.find(x => x.id === current.id);
        if(!old){
            added.push(current);
            continue;
        }
        if(!_.isEqual(current, old)){ //<-- this is the lodash .isEqual function
            edited.push(current);
        }
    }

Body:
From what I measured this is a bit more than twice as fast as the original algorithm.

let control = {};
state[0].forEach(s => {
  control[s.id] = s;
});

let added = [];
let edited = [];

state[1].forEach(s => {
  if (control[s.id]) {
    if (!_.isEqual(control[s.id], s)) {
      edited.push(s);
    }
    delete control[s.id];
  } else {
    added.push(s);
  }
});

let removed = Object.values(control);


问:
Bullets in a Xaml Tooltip
Everything is in the title. I'd like to be able to add some bullet list in a Tooltip but so far haven't found any simple way.

thanks in advance!

答:
I got it displaying correctly with the following:</p>

```<code><ListView
        x:Name="listView"
        Margin="0,-5,0,0"
        BackgroundColor="Transparent"
        HasUnevenRows="True"
        HeightRequest="50"
        HorizontalOptions="CenterAndExpand"
        ItemsSource="{Binding TradingHoursList}"
        SeparatorColor="Transparent">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <RelativeLayout>
                    <Label Text="•"/>
                    <Label
                            Margin="10,0,0,0"
                            FontAttributes="Italic"
                            FontFamily="Arial Black"
                            FontSize="15"
                            HorizontalOptions="Start"
                            Text="{Binding}"
                            VerticalOptions="Start"/>
                </RelativeLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Title: Bullets in a Xaml Tooltip

Body:
I got it displaying correctly with the following:

<ListView
        x:Name="listView"
        Margin="0,-5,0,0"
        BackgroundColor="Transparent"
        HasUnevenRows="True"
        HeightRequest="50"
        HorizontalOptions="CenterAndExpand"
        ItemsSource="{Binding TradingHoursList}"
        SeparatorColor="Transparent">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <RelativeLayout>
                    <Label Text="&#x2022;"/>
                    <Label
                            Margin="10,0,0,0"
                            FontAttributes="Italic"
                            FontFamily="Arial Black"
                            FontSize="15"
                            HorizontalOptions="Start"
                            Text="{Binding}"
                            VerticalOptions="Start"/>
                </RelativeLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


问:
Get current component name
Is that possible to get current component name?

for example if I have localhost:3000/en/mycomponent and I'll to this.router.url it returns /en/mycomponent which is /language/component

I want to make redirect on language change.

I can make

this.router.navigate([this.lang, my component here]);

But how can I get current component from routing?

答:
Angular CLI:

You can access the component name from the constructor:

```<code> console.log('this', this.constructor.name);

 this.constructor.name; // Component name
</code>```

Title: Get current component name

Body:
Angular CLI:

You can access the component name from the constructor:

 console.log('this', this.constructor.name);

 this.constructor.name; // Component name


问:
AlarmManager setInexactRepeating not triggered repeatedly
I am trying to schedule alarm which will perform some task after every hour. For testing purpose, I have set the alarm to trigger after every 5 seconds but it triggers only once.

```<code>private fun register30MinSchedule() {
        val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val alarmIntent = Intent(this, AlarmReceiver::class.java).let { intent ->
            PendingIntent.getBroadcast(applicationContext, LocationTrack_Service_ID, intent, 0)
        }

        alarmMgr?.setInexactRepeating(
                AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(),
                System.currentTimeMillis() + 5000 ,
                alarmIntent
        )
    }
</code>```

AlarmReceiver is called only once. Can anyone please point me the mistake I am making?

Regards,

答:
I was able to figure out the issue. All methods of AlarmManager requires the precise time. In my scenario, i was using the variable time for 2nd and 3rd parameter triggerTimeMillis i.e. System.currentTimeMillis() + 5000. So, the correct way of setting repeating alarm is:

```<code>val initialTime = System.currentTimeMillis()
val repeatingInterval = initialTime + 5000

alarmMgr?.setInexactRepeating(AlarmManager.RTC_WAKEUP, initialTime, repeatingInterval,alarmIntent)
</code>```

This is trigger after every repeating interval. Hope this helps.

Body:
I am trying to schedule alarm which will perform some task after every hour. For testing purpose, I have set the alarm to trigger after every 5 seconds but it triggers only once.

private fun register30MinSchedule() {
        val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val alarmIntent = Intent(this, AlarmReceiver::class.java).let { intent ->
            PendingIntent.getBroadcast(applicationContext, LocationTrack_Service_ID, intent, 0)
        }

        alarmMgr?.setInexactRepeating(
                AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(),
                System.currentTimeMillis() + 5000 ,
                alarmIntent
        )
    }

AlarmReceiver is called only once. Can anyone please point me the mistake I am making?

Regards,

Body:
I was able to figure out the issue. All methods of AlarmManager requires the precise time. In my scenario, i was using the variable time for 2nd and 3rd parameter triggerTimeMillis i.e. System.currentTimeMillis() + 5000. So, the correct way of setting repeating alarm is:

val initialTime = System.currentTimeMillis()
val repeatingInterval = initialTime + 5000

alarmMgr?.setInexactRepeating(AlarmManager.RTC_WAKEUP, initialTime, repeatingInterval,alarmIntent)

This is trigger after every repeating interval. Hope this helps.


问:
How do I center a custom checkbox vertically in div?
I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  visibility: visible;
  border: 1px solid #FFF;
  padding: 0 3px;
  margin: 2px 0;
  border-radius: 8px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid
        black;">

  <input type="checkbox">
  <span id="text">TEXTTEXTTEXTTEXT</span>
</div></code>```

答:
div{
    display: flex;
    justify-content: center;
    align-items: center;
    resize: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
    input[type=checkbox] {
        cursor: pointer;
        font-size: 17px;
        visibility: hidden;
        transform: scale(1.2);
        height:100%;
        display: flex;
        justify-content: center;
        align-items: center;
        resize: both;
    }

    input[type=checkbox]:after {
        content: " ";
        background-color: #fff;
        display: inline-block;
        color: #00BFF0;
        width: 14px;
        height: 18px;
        visibility: visible;
        border: 1px solid #FFF;
        padding: 0 3px;
        margin: 2px 0;
        border-radius: 8px;
        box-shadow: 0 0 15px 0 rgba(0,0,0,0.09), 0 0 2px 0 rgba(0,0,0,0.18);
    }

    input[type=checkbox]:checked:after {
        content: "\2714";
        display: unset;
        font-weight: bold;
    }

    </style>

    <div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid
    black;">

    <input type="checkbox">
    <span id="text">TEXTTEXTTEXTTEXT</span>
    </div></code>```

Body:
I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  visibility: visible;
  border: 1px solid #FFF;
  padding: 0 3px;
  margin: 2px 0;
  border-radius: 8px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}

  <input type="checkbox">
  TEXTTEXTTEXTTEXT

Body:
div{
    display: flex;
    justify-content: center;
    align-items: center;
    resize: both;
}

<style>
    input[type=checkbox] {
        cursor: pointer;
        font-size: 17px;
        visibility: hidden;
        transform: scale(1.2);
        height:100%;
        display: flex;
        justify-content: center;
        align-items: center;
        resize: both;
    }

    input[type=checkbox]:after {
        content: " ";
        background-color: #fff;
        display: inline-block;
        color: #00BFF0;
        width: 14px;
        height: 18px;
        visibility: visible;
        border: 1px solid #FFF;
        padding: 0 3px;
        margin: 2px 0;
        border-radius: 8px;
        box-shadow: 0 0 15px 0 rgba(0,0,0,0.09), 0 0 2px 0 rgba(0,0,0,0.18);
    }

    input[type=checkbox]:checked:after {
        content: "\2714";
        display: unset;
        font-weight: bold;
    }

    </style>

    <div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid
    black;">

    <input type="checkbox">
    <span id="text">TEXTTEXTTEXTTEXT</span>
    </div>


问:
GetProcAddress function in C++
Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"

Here is a code which I used:

```<code>typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL = LoadLibrary(L"MYDLL.DLL");
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");
</code>```

答:
Most probably LoadLibrary() failed. You just can't see that because apparently you are not checking what it is returning:

If the function fails, the return value is NULL. To get extended error information, call GetLastError.

EDIT:

We don't know how you are exporting the function on the DLL code, but this thread explains a couple of reasons on why GetProcAddress fails.

Title: GetProcAddress function in C++

Body:
Hello guys: I've loaded my DLL in my project but whenever I use the GetProcAddress function. it returns NULL! what should I do?
I use this function ( double GetNumber(double x) ) in "MYDLL.dll"

Here is a code which I used:

typedef double (*LPGETNUMBER)(double Nbr);
HINSTANCE hDLL = NULL;
LPGETNUMBER lpGetNumber;
hDLL = LoadLibrary(L"MYDLL.DLL");
lpGetNumber = (LPGETNUMBER)GetProcAddress((HMODULE)hDLL, "GetNumber");


问:
Using output status of VerifyElementPresent in Selenium IDE on chrom
I am using Seleium IDE on chrome. I want to make a simple code using the output of "VerifyElementPresent" command. If the output is true, execute code1 else execute code2.

I cannot find a way to store the output of this command in a variable so I can use it further.

THanks

答:
There is no information in documentation about storing result of 'verify element present' command. But you can use 'store xpath count' for this reason.</p>

```<code>store xpath count | xpath=some_xpath | n
if | ${n} > 0 |
code1...
else | |
code2...
end | |
</code>```

Body:
There is no information in documentation about storing result of 'verify element present' command. But you can use 'store xpath count' for this reason.

store xpath count | xpath=some_xpath | n
if | ${n} > 0 |
code1...
else | |
code2...
end | |


问:
How to run a Lua script within a Windows Forms TextBox
I used Visual Studio 2019 to build a form of some sort that I want to use to execute scripts in a TextBox within that textbox, so if I do print("Hello"); the next line will be hello.
I use FastColoredTextBox to do that and I noticed it has a language property that I already set to Lua. How can I actually execute commands within that textbox tho?

I appreciate all your help :)

答:
You can install DynamicLua package to compile and run Lua code in C#.

For example, I assume you have a fastColoredTextBox1 on your form and a button to toolStripButton1 to run the code, then you can add the following code:

```<code>private void Form1_Load(object sender, EventArgs e)
{
    this.fastColoredTextBox1.Language = FastColoredTextBoxNS.Language.Lua;
    this.fastColoredTextBox1.Text= "function echo(s) return s end" + "\n" +
        "return echo(\"Hello!\")";
}

private void toolStripButton1_Click(object sender, EventArgs e)
{
    dynamic lua = new DynamicLua.DynamicLua();
    var result = lua(fastColoredTextBox1.Text);
    MessageBox.Show($"{result}");
}
</code>```

Body:
You can install DynamicLua package to compile and run Lua code in C#.

For example, I assume you have a fastColoredTextBox1 on your form and a button to toolStripButton1 to run the code, then you can add the following code:

private void Form1_Load(object sender, EventArgs e)
{
    this.fastColoredTextBox1.Language = FastColoredTextBoxNS.Language.Lua;
    this.fastColoredTextBox1.Text= "function echo(s) return s end" + "\n" +
        "return echo(\"Hello!\")";
}

private void toolStripButton1_Click(object sender, EventArgs e)
{
    dynamic lua = new DynamicLua.DynamicLua();
    var result = lua(fastColoredTextBox1.Text);
    MessageBox.Show($"{result}");
}


问:
DatePicker dialog is not showing on single tap
Expectation:

When user will tap on MaterialTextView component, DatePickerDialog should open.

Whats happening:

User needs to tap twice on MaterialTextView component for opening DatePickerDialog.

MainActivity

```<code>protected void onCreate(Bundle SavedInstanceState){
MaterialTextView issueDate = findViewById(R.id.edIssueDate);
 issueDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            hideKeyboard(AddNewCoupon.this);
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddNewCoupon.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    issueDate.setText(String.valueOf(dayOfMonth)+"/"+String.valueOf(month)+"/"+String.valueOf(year));
                    //newCustomer.hideKeyboard(AddNewCoupon.this);
                }
            }, year, month, day);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            datePickerDialog.show();
        }
    });
}
</code>```

hideKeyboard() method:

```<code>public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    View view = activity.getCurrentFocus();
    if (view == null) {
        view = new View(activity);
    }

    if (imm != null)
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

Layout:

```<code><com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:focusable="auto"
                        android:focusableInTouchMode="true"
                        android:hint="@string/txtVIssueingDtHint"
                        android:nextFocusDown="@id/edExpDate"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</code>```

Dependencies:

```<code>dependencies {
...

implementation 'com.google.android.material:material:1.2.0-alpha04'

...
}
</code>```

Code runs perfectly as DatePickerDialog opens but the problem is user needs to tap twice for opeining it. Where I've made mistake? How can I fix the code?

答:
change your textview to</p>

```<code><com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:hint="@string/txtVIssueingDtHint"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</code>```

Body:
Expectation:

When user will tap on MaterialTextView component, DatePickerDialog should open.

Whats happening:

User needs to tap twice on MaterialTextView component for opening DatePickerDialog.

MainActivity

protected void onCreate(Bundle SavedInstanceState){
MaterialTextView issueDate = findViewById(R.id.edIssueDate);
 issueDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            hideKeyboard(AddNewCoupon.this);
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddNewCoupon.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    issueDate.setText(String.valueOf(dayOfMonth)+"/"+String.valueOf(month)+"/"+String.valueOf(year));
                    //newCustomer.hideKeyboard(AddNewCoupon.this);
                }
            }, year, month, day);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            datePickerDialog.show();
        }
    });
}

hideKeyboard() method:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    View view = activity.getCurrentFocus();
    if (view == null) {
        view = new View(activity);
    }

    if (imm != null)
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Layout:

<com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:focusable="auto"
                        android:focusableInTouchMode="true"
                        android:hint="@string/txtVIssueingDtHint"
                        android:nextFocusDown="@id/edExpDate"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />

Dependencies:

dependencies {
...

implementation 'com.google.android.material:material:1.2.0-alpha04'

...
}

Code runs perfectly as DatePickerDialog opens but the problem is user needs to tap twice for opeining it. Where I've made mistake? How can I fix the code?

Body:
change your textview to

<com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:hint="@string/txtVIssueingDtHint"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />


问:
How I can give access for everyone around the world to my spring boot app that started on my computer?
I started my spring boot app on my computer, and now I can easily make Http requests to http://localhost:8080/. How I can give access to everyone around the world to make Http requests to my app without deploying this app anywhere?

答:
If you don't want to deploy it in any cloud services, At-least you need to have a public IP. Without public IP, other user can access your server.

After getting access of public IP you need to set it in your PC. After that run the spring boot app, with public IP configured. Or you can set public IP in a router or gateway and redirect/forward port to your locally running application PORT.


问:
Open alert dialog in Bottom Navigation View while navigation to next fragment
I am having an BottomNavigationView in my activity and i have five fragments and i have used Navigation Jetpack component.

Each and every time i move to next fragment by clicking the BottomNavigationView item, i have to ask for a confirmation dialog (If i have to navigate from this screen Yes/No). If Yes i can move to next screen else for No i have to dismiss the dialog and proceed.

I there any better in Navigation Jetpack component itself to handle this situation.

I not getting any clear picture for this

答:
When you select BottomNavigationView item, you can should use this code;
First step, define BottomNavigationView in onCreate.

```<code>    mBtmView = (BottomNavigationView) findViewById(R.id.bottomView);
    mBtmView.setOnNavigationItemSelectedListener(this);
</code>```

Second step;

```<code>@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    mMenuId = item.getItemId();

    switch (item.getItemId()) {
        case R.id.action_food: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.
        }
        break;
        case R.id.action_medical: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
        case R.id.action_yoga: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
        case R.id.action_postures: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
    }
    return true;
}
</code>```

Body:
When you select BottomNavigationView item, you can should use this code;
First step, define BottomNavigationView in onCreate.

    mBtmView = (BottomNavigationView) findViewById(R.id.bottomView);
    mBtmView.setOnNavigationItemSelectedListener(this);

Second step;

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {

    mMenuId = item.getItemId();

    switch (item.getItemId()) {
        case R.id.action_food: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.
        }
        break;
        case R.id.action_medical: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
        case R.id.action_yoga: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
        case R.id.action_postures: {
//Show dialog to there. if reject swipe from your dialog, use setCurrentItem.

        }
        break;
    }
    return true;
}


问:
Looping through xml response
This is my current code for reading through an XML file hosted online and currently, it displays the first list item. However, I want to loop through the entire XML response and display all the items. How can I do this?

var x = new XMLHttpRequest();
x.open("GET", "https://api.lncontent.works/syndicated/media", true);
x.onreadystatechange = function() {
  if (x.readyState < 4) {
    document.getElementById('header-block').innerHTML = "Loading...";
  } else if (x.readyState === 4) {
    if (x.status == 200 && x.status < 300) {
      var xml = x.responseXML;
      // MAIN TITLE
      var titles = xml.getElementsByTagName("title");
      document.getElementById('header-block').innerHTML = titles[0].childNodes[0].nodeValue;

      var item = xml.getElementsByTagName("item");
      console.log(item[0]);

      for (i = 1; i < item.length; i++) {
        var title = document.getElementById('title-block').innerHTML = item[i].getElementsByTagName("title")[0].innerHTML;
        var link = document.getElementById('link-block').innerHTML = item[i].getElementsByTagName("link")[0].innerHTML;
        var description = document.getElementById('description-block').innerHTML = item[i].getElementsByTagName("description")[0].innerHTML;
        var pubDate = document.getElementById('pubDate-block').innerHTML = item[i].getElementsByTagName("pubDate")[0].innerHTML;
        var enclosure = document.getElementById('enclosure-block').innerHTML = item[i].getElementsByTagName("enclosure")[0].innerHTML;
        var genre = document.getElementById('genre-block').innerHTML = item[i].getElementsByTagName("jwplayer:genre")[0].innerHTML;
        var artist = document.getElementById('artist-block').innerHTML = item[i].getElementsByTagName("livenation:artists")[0].getElementsByTagName("artist")[0].innerHTML;
      }
    }
  }
};
x.send(null);```

NOTE: I start at item index 1 for my attempt at looping because index 0 is reserved for heading and is excluded from the list. This is the current output of the code:

答:
Kindly look at below
you were overwriting in for loop you need to append and display as below

find the working js here

var x = new XMLHttpRequest();
x.open("GET", "https://api.lncontent.works/syndicated/media", true);
x.onreadystatechange = function() {
debugger;
  if (x.readyState < 4) {
    document.getElementById('header-block').innerHTML = "Loading...";
  } else if (x.readyState === 4) {

    if (x.status == 200 && x.status < 300) {
     debugger;
      var xml = x.responseXML;
      // MAIN TITLE
      var titles = xml.getElementsByTagName("title");
      document.getElementById('header-block').innerHTML = titles[0].childNodes[0].nodeValue;

      var item = xml.getElementsByTagName("item");
      console.log(item[0]);
var  html='';
var htmlChild='';
      for (i = 1; i < item.length; i++) {
        var title =  item[i].getElementsByTagName("title")[0].innerHTML;
        var link  = item[i].getElementsByTagName("link")[0].innerHTML;
        var description =  item[i].getElementsByTagName("description")[0].innerHTML;
        var pubDate = item[i].getElementsByTagName("pubDate")[0].innerHTML;
        var enclosure  ='';
        if(item[i].getElementsByTagName("enclosure").length>0)
        {
        enclosure=item[i].getElementsByTagName("enclosure")[0].innerHTML;
        }

        var genre = '';
        if(item[i].getElementsByTagName("jwplayer:genre").length>0)
        {
        genre=item[i].getElementsByTagName("jwplayer:genre")[0].innerHTML;
        }

        var artist=''
        if(item[i].getElementsByTagName("livenation:artists").length>0)
        {
         artist = item[i].getElementsByTagName("livenation:artists")[0].getElementsByTagName("artist")[0].innerHTML;
        }

        htmlChild='';
        htmlChild+="
Title

"+title+ "
";
        htmlChild+="
link

"+link+ "
";
        htmlChild+="
description

"+title+ "
";
        htmlChild+="
pubDate

"+pubDate+ "
";
        htmlChild+="
enclosure

"+enclosure+ "
";
        htmlChild+="
genre

"+genre+ "
";
        htmlChild+="
artist

"+artist+ "
";
        html+='
'+htmlChild+'
';
      }
      document.getElementById('header-block').innerHTML =html;
    }
  }
};
x.send(null);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="header-block">

</div>
<div id="Content">

</div></code>```

Title: Looping through xml response

Body:
This is my current code for reading through an XML file hosted online and currently, it displays the first list item. However, I want to loop through the entire XML response and display all the items. How can I do this?

var x = new XMLHttpRequest();
x.open("GET", "https://api.lncontent.works/syndicated/media", true);
x.onreadystatechange = function() {
  if (x.readyState < 4) {
    document.getElementById('header-block').innerHTML = "Loading...";
  } else if (x.readyState === 4) {
    if (x.status == 200 && x.status < 300) {
      var xml = x.responseXML;
      // MAIN TITLE
      var titles = xml.getElementsByTagName("title");
      document.getElementById('header-block').innerHTML = titles[0].childNodes[0].nodeValue;

      var item = xml.getElementsByTagName("item");
      console.log(item[0]);

      for (i = 1; i < item.length; i++) {
        var title = document.getElementById('title-block').innerHTML = item[i].getElementsByTagName("title")[0].innerHTML;
        var link = document.getElementById('link-block').innerHTML = item[i].getElementsByTagName("link")[0].innerHTML;
        var description = document.getElementById('description-block').innerHTML = item[i].getElementsByTagName("description")[0].innerHTML;
        var pubDate = document.getElementById('pubDate-block').innerHTML = item[i].getElementsByTagName("pubDate")[0].innerHTML;
        var enclosure = document.getElementById('enclosure-block').innerHTML = item[i].getElementsByTagName("enclosure")[0].innerHTML;
        var genre = document.getElementById('genre-block').innerHTML = item[i].getElementsByTagName("jwplayer:genre")[0].innerHTML;
        var artist = document.getElementById('artist-block').innerHTML = item[i].getElementsByTagName("livenation:artists")[0].getElementsByTagName("artist")[0].innerHTML;
      }
    }
  }
};
x.send(null);

NOTE: I start at item index 1 for my attempt at looping because index 0 is reserved for heading and is excluded from the list. This is the current output of the code:

Body:
Kindly look at below
you were overwriting in for loop you need to append and display as below

find the working js here

var x = new XMLHttpRequest();
x.open("GET", "https://api.lncontent.works/syndicated/media", true);
x.onreadystatechange = function() {
debugger;
  if (x.readyState < 4) {
    document.getElementById('header-block').innerHTML = "Loading...";
  } else if (x.readyState === 4) {

    if (x.status == 200 && x.status < 300) {
     debugger;
      var xml = x.responseXML;
      // MAIN TITLE
      var titles = xml.getElementsByTagName("title");
      document.getElementById('header-block').innerHTML = titles[0].childNodes[0].nodeValue;

      var item = xml.getElementsByTagName("item");
      console.log(item[0]);
var  html='';
var htmlChild='';
      for (i = 1; i < item.length; i++) {
        var title =  item[i].getElementsByTagName("title")[0].innerHTML;
        var link  = item[i].getElementsByTagName("link")[0].innerHTML;
        var description =  item[i].getElementsByTagName("description")[0].innerHTML;
        var pubDate = item[i].getElementsByTagName("pubDate")[0].innerHTML;
        var enclosure  ='';
        if(item[i].getElementsByTagName("enclosure").length>0)
        {
        enclosure=item[i].getElementsByTagName("enclosure")[0].innerHTML;
        }

        var genre = '';
        if(item[i].getElementsByTagName("jwplayer:genre").length>0)
        {
        genre=item[i].getElementsByTagName("jwplayer:genre")[0].innerHTML;
        }

        var artist=''
        if(item[i].getElementsByTagName("livenation:artists").length>0)
        {
         artist = item[i].getElementsByTagName("livenation:artists")[0].getElementsByTagName("artist")[0].innerHTML;
        }

        htmlChild='';
        htmlChild+="<div>Title</div><div>"+title+ "</div>";
        htmlChild+="<div>link</div><div>"+link+ "</div>";
        htmlChild+="<div>description</div><div>"+title+ "</div>";
        htmlChild+="<div>pubDate</div><div>"+pubDate+ "</div>";
        htmlChild+="<div>enclosure</div><div>"+enclosure+ "</div>";
        htmlChild+="<div>genre</div><div>"+genre+ "</div>";
        htmlChild+="<div>artist</div><div>"+artist+ "</div>";
        html+='<div style="border: 1px solid black;">'+htmlChild+'<div>';
      }
      document.getElementById('header-block').innerHTML =html;
    }
  }
};
x.send(null);

<div id="header-block">

</div>
<div id="Content">

</div>


问:
Contact form 7 input box not clickable
I have one site developed in wordpress and One of my contact form is not working while clicking on input box i am not able to enter any deatils in that can any body check and suggest me solution I have tried many related to CSS but none of them are working.

Link of form https://kulorgroup.com/contact-us/

Thank you,

答: Have you added any plugin or something which disabled the selection to the website content and even not allow me to right click, while i checked it with original theme it works fine.</p>

Title: Contact form 7 input box not clickable


问:
Seaborn barplot label bars with 3rd variable
I am fairly new to Python visualization. I have data with 3 variables; month, frequency and word. I am trying to see which word appeared most in a month.

```<code>import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

sns.barplot(x = 'month', y = 'freq', data = test)
</code>```

So far, I have month on the x-axis, freq on the y-axis. But, I want to label bars with the words that appear in those months. For example "hello" should appear on Jan-2019 bar.

答:
If I understood you correctly, you can do in this way:

```<code>import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
         'freq':[3,5,22,6,3],
         'word':['hello','world','seaborn','exp','python']})

ax = sns.barplot(x = 'month', y = 'freq', data = test)

for bar, label in zip(ax.patches, test['word']):
    x = bar.get_x()
    width = bar.get_width()
    height = bar.get_height()
    ax.text(x+width/2., height + 0.2, label, ha="center")
</code>```

Body:
I am fairly new to Python visualization. I have data with 3 variables; month, frequency and word. I am trying to see which word appeared most in a month.

import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

sns.barplot(x = 'month', y = 'freq', data = test)

So far, I have month on the x-axis, freq on the y-axis. But, I want to label bars with the words that appear in those months. For example "hello" should appear on Jan-2019 bar.

Body:
If I understood you correctly, you can do in this way:

import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
         'freq':[3,5,22,6,3],
         'word':['hello','world','seaborn','exp','python']})

ax = sns.barplot(x = 'month', y = 'freq', data = test)

for bar, label in zip(ax.patches, test['word']):
    x = bar.get_x()
    width = bar.get_width()
    height = bar.get_height()
    ax.text(x+width/2., height + 0.2, label, ha="center")


问:
Relation onetoone in QueryBuilder
I'm trying to make a query with QueryBuilder for a delete already used object.
The correct Mysql query is:

```<code>SELECT * FROM token LEFT JOIN att_token ON token.id = att_token.id_token_id WHERE att_token.id_utilisateur_id IS null ORDER BY token.num_serie ASC
</code>```

My QueryBuilder in my repository is:

```<code>'query_builder' => function (EntityRepository $Token) {
  return $Token->createQueryBuilder('u')
  ->from('App\Entity\AttToken', 'att_token')
  ->LeftJoin('att_token.IdToken','attu')
  ->Where('att_token.IdUtilisateur IS null')
  ->orderBy('u.numSerie', 'ASC');
</code>```

But I have no result, no error. I don't know where is my mistake...

I have a OneToOne relation between Token and AttToken entity, in AttToken I have the relation description but not in Token entity...

If someone have a idea ...

Have a nice day.

答:
I solved it.
I start to delete IdToken attribute on AttToken.
Then I use

```<code>php bin/console make:entity
</code>```

To create it again and answer yes to

```<code>Do you want to add a new property to Token so that you can access/update AttToken objects from it - e.g. $token->getAttToken()? (yes/no) [no]:
</code>```

Then my createQueryBuilder come simply like:

```<code>->LeftJoin('u.attToken','attu')
->Where('attu.IdUtilisateur IS null')
->orderBy('u.numSerie', 'ASC');
</code>```

Have a nice day

Title: Relation onetoone in QueryBuilder

Body:
I'm trying to make a query with QueryBuilder for a delete already used object.
The correct Mysql query is:

SELECT * FROM token LEFT JOIN att_token ON token.id = att_token.id_token_id WHERE att_token.id_utilisateur_id IS null ORDER BY token.num_serie ASC

My QueryBuilder in my repository is:

'query_builder' => function (EntityRepository $Token) {
  return $Token->createQueryBuilder('u')
  ->from('App\Entity\AttToken', 'att_token')
  ->LeftJoin('att_token.IdToken','attu')
  ->Where('att_token.IdUtilisateur IS null')
  ->orderBy('u.numSerie', 'ASC');

But I have no result, no error. I don't know where is my mistake...

I have a OneToOne relation between Token and AttToken entity, in AttToken I have the relation description but not in Token entity...

If someone have a idea ...

Have a nice day.

Body:
I solved it.
I start to delete IdToken attribute on AttToken.
Then I use

php bin/console make:entity

To create it again and answer yes to

Do you want to add a new property to Token so that you can access/update AttToken objects from it - e.g. $token->getAttToken()? (yes/no) [no]:

Then my createQueryBuilder come simply like:

->LeftJoin('u.attToken','attu')
->Where('attu.IdUtilisateur IS null')
->orderBy('u.numSerie', 'ASC');

Have a nice day


问:
PHPUnit Zend Framework Controller Tests - Failed asserting last controller used <"error"> - display errors
We are currently putting unit tests around zend framework controllers.

(I've abstracted this code example a little bit, but the idea is the same....)

We've happily managed to make the test fail, with the error message

Failed asserting last controller used <"error"> ....

with the test:

```<code>$this->dispatch('/controller/action/param');
$this->assertController('controller');
$this->assertAction('action');
</code>```

So in this instance, how do I get the real error message to bubble up to PHPUnit, i.e. if there is an error in the controller, I want to know about it rather than invoking the error controller.

If I set resources.frontController.params.noErrorHandler = 1 in the application.ini, the test passes even though there is an error, because that controller and action still occurs, but just outputs nothing (I know I could look for assertions in the output, but that's not the point - I want the original error).

I've tried turned on

```<code>convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
</code>```

in phpunit.xml as well, no joy.

Any pointers would be much appreciated.

I hope all of that made sense!?

Many thanks.

答:
This is an issue I've run into as well, and it can be pretty difficult sometimes to track down the error. One solution I stumbled on by chance -- I modified the error controller to send an e-mail in the event of an error in our production environment, but I accidentally had it set to send in the testing environment as well -- and then when one of these errors happened on a unit test, I got an e-mail detailing the error.

You don't have to use e-mail notification, but you might want to look into error logging at http://framework.zend.com/manual/en/zend.log.writers.html. You could have the errors written to a log file and then check the log file.

Body:
We are currently putting unit tests around zend framework controllers.

(I've abstracted this code example a little bit, but the idea is the same....)

We've happily managed to make the test fail, with the error message

Failed asserting last controller used <"error"> ....

with the test:

$this->dispatch('/controller/action/param');
$this->assertController('controller');
$this->assertAction('action');

So in this instance, how do I get the real error message to bubble up to PHPUnit, i.e. if there is an error in the controller, I want to know about it rather than invoking the error controller.

If I set resources.frontController.params.noErrorHandler = 1 in the application.ini, the test passes even though there is an error, because that controller and action still occurs, but just outputs nothing (I know I could look for assertions in the output, but that's not the point - I want the original error).

I've tried turned on

convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"

in phpunit.xml as well, no joy.

Any pointers would be much appreciated.

I hope all of that made sense!?

Many thanks.


问:
Django Rest Framework: Count Number of Objects with multiple ManyToManyField values
In the example below, I have two models with a ManyToMany relation and I'm trying to count the number of posts related to the tags.

There are 3 tags: Sports, Films, Health

There are 3 posts: 1 for Sports, 1 for Films and 1 post with two tags (Sports and Health)

I can get the count of posts for every tag as below:

```<code>[
    {
        "name": "Sports",
        "posts": 2
    },
    {
        "name": "Films",
        "posts": 1
    },
    {
        "name": "Health",
        "posts": 1
    }

]
</code>```

My requirement is to count the objects separately for the combination of tags. So, the desirable output is:

```<code>[
    {
        "name": "Sports",
        "posts": 1
    },
    {
        "name": "Films",
        "posts": 1
    },
    {
        "name": "Sports & Health",
        "posts": 1
    }

]
</code>```

This is where I'm stuck. How do I combine the two tags and then count the number of post objects that have both these tags?

models.py

class Tag(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.title
```

<p><strong>serializers.py</strong></p>

<pre class="lang-py prettyprint-override"><code>class TagSerializer(serializers.ModelSerializer):

    posts = serializers.SerializerMethodField()

    class Meta:
        model = Tag
        fields = ('name', 'posts')

    def get_posts(self, obj):
        posts = obj.post_set.all().count()
        return posts

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'
</code>```

答:
use this in your serializers.py get_posts

Post.objects.filter(tags__in=[obj]).count()

instead of

obj.post_set.all().count()

Body:
In the example below, I have two models with a ManyToMany relation and I'm trying to count the number of posts related to the tags.

There are 3 tags: Sports, Films, Health

There are 3 posts: 1 for Sports, 1 for Films and 1 post with two tags (Sports and Health)

I can get the count of posts for every tag as below:

[
    {
        "name": "Sports",
        "posts": 2
    },
    {
        "name": "Films",
        "posts": 1
    },
    {
        "name": "Health",
        "posts": 1
    }

]

My requirement is to count the objects separately for the combination of tags. So, the desirable output is:

[
    {
        "name": "Sports",
        "posts": 1
    },
    {
        "name": "Films",
        "posts": 1
    },
    {
        "name": "Sports & Health",
        "posts": 1
    }

]

This is where I'm stuck. How do I combine the two tags and then count the number of post objects that have both these tags?

models.py

class Tag(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.title

serializers.py

class TagSerializer(serializers.ModelSerializer):

    posts = serializers.SerializerMethodField()

    class Meta:
        model = Tag
        fields = ('name', 'posts')

    def get_posts(self, obj):
        posts = obj.post_set.all().count()
        return posts

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'


问:
Get regex of words that starts with @ sign
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

```<code>/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi
</code>```

Examples that should be matched:

```<code>@abcdefjh
</code>```

Examples that shouldn't be matched:

```<code>abc@absdefgh
</code>```

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?

答:
This regex will match a word (consisted of word characters as in regular expressions) preceded by an '@' and composed of more than 6 characters.

```<code>@\w{6,}
</code>```

Body:
All answers that I found get rough solution for example this and this ( /\b@\w+\b/gi ) is cover not only the "@abcdef" but "abc@abcdf" too, but what I need is a regex that match all words that starts with "@" sign and more than 6 characters length and non of following solutions give me what I need

/@\b[a-zA-Z0-9]{5,}\b/gi
/\b@[a-zA-Z0-9]{5,}\b/gi

Examples that should be matched:

@abcdefjh

Examples that shouldn't be matched:

abc@absdefgh

Added:
PS: Is there a way to improve this question that it can be more helpful for not experienced users like me?

Body:
This regex will match a word (consisted of word characters as in regular expressions) preceded by an '@' and composed of more than 6 characters.

@\w{6,}


问:
TRK0005 error locating rc.exe building VC++ 2015 project
I have a VS 2015 C++ project (64-bit Windows 10 + Windows 10 SDK).

With the Project Properties > General > Target Platform Version set to "8.1", everything builds fine.

When I change it to "10.0.15063.0", I hit this error:

```<code>Error TRK0005 Failed to locate: "rc.exe". The system cannot find the file specified.
</code>```

I saw from other posts that the fix is to paste the exe to somewhere it can be found. I'm looking for something a bit more solid (e.g. version controlled).

When set to 8.1, the $(WindowsSDK_ExecutablePath) macro includes this path:

```<code>C:\Program Files (x86)\Windows Kits\8.1\bin\x86
</code>```

with rc.exe in it.

When set to 10.0.15063.0, none of the paths in the macro have an rc.exe inside them. If I add this path to the Executable Directories, the problem goes away:

```<code>C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64
</code>```

My questions:

Is what I'm seeing expected or should rc.exe be found out-the-box?

Is it safe for me to add this extra path or am I likely to break something?

Am I using the correct extra path? (The 8.1 path includes "x86".)

Thanks

答:
1) rc.exe should be found out of the box.
The issue may be related to a different Windows 10 SDK path schemes which was changed in newer Windows 10 SDKs.
Please, check, if VS2015 files point to the folder
C:\Program Files (x86)\Windows Kits\10\bin\x64
(You can see the value of the macro for $(WindowsSDK_ExecutablePath)).
Latest Windows 10 SDK are installed in parallel subfolders so you may install different Windows 10 SDK, with folders like:
C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64
C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64

If VS expects SDK in general folder - Windows Kits\10\bin\, you may copy rc.exe, rc.dll  there from bin\10.0.15063.0\ (from \x86 to \x86, from \x64 to \x64).

This is inconsistency in VS2015 / Win 10 SDK install.

2) If you put actual rc.exe path into the Project Properties > Configuration Properties > Executable Directories, at the end, it is generally safe. Paths are iterated from left to right, and the last one will be searched only if .exe was not found in the previous predefined ones.

3) VS may build .rc resource files always with 32-bit rc.exe from \x86 folder, depending on the variable in Executable Paths. It may be set to $(WindowsSDK_ExecutablePath).
This actually should not matter, as these are 32-bit / 64-bit versions of the compiler executables with equivalent functionality.
You can track which compiler .exe files MSBuild invokes in Output window, if increase verbosity:
Tools > Options > Projects and Solutions > Build and Run > MSBuild project build output verbosity > Detailed.

Body:
I have a VS 2015 C++ project (64-bit Windows 10 + Windows 10 SDK).

With the Project Properties > General > Target Platform Version set to "8.1", everything builds fine.

When I change it to "10.0.15063.0", I hit this error:

Error TRK0005 Failed to locate: "rc.exe". The system cannot find the file specified.

I saw from other posts that the fix is to paste the exe to somewhere it can be found. I'm looking for something a bit more solid (e.g. version controlled).

When set to 8.1, the $(WindowsSDK_ExecutablePath) macro includes this path:

C:\Program Files (x86)\Windows Kits\8.1\bin\x86

with rc.exe in it.

When set to 10.0.15063.0, none of the paths in the macro have an rc.exe inside them. If I add this path to the Executable Directories, the problem goes away:

C:\Program Files (x86)\Windows Kits\10\bin\10.0.15063.0\x64

My questions:

Is what I'm seeing expected or should rc.exe be found out-the-box?

Is it safe for me to add this extra path or am I likely to break something?

Am I using the correct extra path? (The 8.1 path includes "x86".)

Thanks


问:
Under the hood, how does rxjs listen for changes
Since browsers' DOM API works via an event loop and to listen for changes on the dom we register event handlers.

What does RXJS behind the scene implement for subscribers to listen for changes in data.

I could be entirely missing the plot here. (I use them day to day but would like to know under the hood how they work with the DOM APIs).

I understand observer pattern but that is a design abstraction, how the core RXJS operates with the DOM is what I am looking for.

答: The straight forward way would take a look at source code: fromEvent as you want to see DOM interaction and schedulers for DOM API(setInterval, for example)


答:
Given you are defining the dimensions explicitly, you can set the pseudo element with position:relative; top: -50% .

For this approach, remember to left-pad the label:

  input[type=checkbox] {
        cursor: pointer;
        font-size: 17px;
        visibility: hidden;
        transform: scale(1.2);
    }

    input[type=checkbox]:after {
        content: " ";
        background-color: #fff;
        display: inline-block;
        position:relative;
        top:-50%;
        left:-14px;
        color: #00BFF0;
        width: 14px;
        height: 18px;
        visibility: visible;
        border: 1px solid #FFF;
        padding: 0 3px;
        margin: 2px 0;
        border-radius: 8px;
        box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
    }

    input[type=checkbox]:checked:after {
        content: "\2714";
        display: unset;
        font-weight: bold;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid black;padding-left: 22px">

    <input type="checkbox">
    <span id="text">TEXTTEXTTEXTTEXT</span>
    </div></code>```

Title: How do I center a custom checkbox vertically in div?

Body:
I am trying to use flex to align elements vertically, but the custom checkbox is not aligned, the code below shows the problem clearly.Does anyone know what the problem is?

input[type=checkbox] {
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
  transform: scale(1.2);
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  color: #00BFF0;
  width: 14px;
  height: 18px;
  visibility: visible;
  border: 1px solid #FFF;
  padding: 0 3px;
  margin: 2px 0;
  border-radius: 8px;
  box-shadow: 0 0 15px 0 rgba(0, 0, 0, 0.09), 0 0 5px 0 rgba(0, 0, 0, 0.18);
}

input[type=checkbox]:checked:after {
  content: "\2714";
  display: unset;
  font-weight: bold;
}

  <input type="checkbox">
  TEXTTEXTTEXTTEXT

Body:
Given you are defining the dimensions explicitly, you can set the pseudo element with position:relative; top: -50% .

For this approach, remember to left-pad the label:

  input[type=checkbox] {
        cursor: pointer;
        font-size: 17px;
        visibility: hidden;
        transform: scale(1.2);
    }

    input[type=checkbox]:after {
        content: " ";
        background-color: #fff;
        display: inline-block;
        position:relative;
        top:-50%;
        left:-14px;
        color: #00BFF0;
        width: 14px;
        height: 18px;
        visibility: visible;
        border: 1px solid #FFF;
        padding: 0 3px;
        margin: 2px 0;
        border-radius: 8px;
        box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
    }

    input[type=checkbox]:checked:after {
        content: "\2714";
        display: unset;
        font-weight: bold;
    }

    <div style="display:inline-block; height:40px; display: flex;  align-items: center; border: 1px solid black;padding-left: 22px">

    <input type="checkbox">
    <span id="text">TEXTTEXTTEXTTEXT</span>
    </div>


问:
Can't get innerHTML of tag on IE8
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

```<code><html>
<head>
<script type="text/javascript">
function updatesidebar()
{
alert("Hello");
var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;

alert("Hello again");

}
</script>

</head>
<body>
<div id="main">

<div class="menu_main">

                      <ul class='mainmenu' id='root'>
<li><a href="/home" class="">Home</a></li>
<li><a href="/solutions" class="">Solutions</a>
</li><li><a href="/services" class="">Services</a></li>
<li><a href="/about-us" class="current_page_item">About Us</a></li>
<li><a href="/news" class="">News and Events</a></li>
<li><a href="/careers" class="">Careers</a></li>
<li><a href="/contact-us" class="">Contact Us</a></li>
</ul>

                </div>

</div>
<script type="text/javascript">
window.onload=updatesidebar();
</script>

</body>
</html>
</code>```

答: getElementsByClassName is not compatible in IE8. it's part of HTML5

Title: Can't get innerHTML of tag on IE8

Body:
I am trying to get the innerhtml of class name current_page_item[0]... And this is working  fine in FF and even in IE9 also. But in IE 8 it seems to be some javascript error in line" var classelem=document.getElementsByClassName('current_page_item')[0].innerHTML;.

I tried to put alert after the above line. But it is not displaying the message "Hello again".

Any idea how to solve the browser issue for this? Is it something that document.getElementsByClassName wont work in IE8?

Home

Solutions

Services

About Us

News and Events

Careers

Contact Us


问:
php download from url in multi chunk at the same time
Because of connection speed limit for each request, i can't download large file from my remote server(getting timeout), but when testing with multi connection at same time(test with download managers software) download speed incredibly and get completed.

I tested cUrl and fopen but none of this has multi chunk download at same time.

Tips: I don't need download multi file at same time, something like https://github.com/petewarden/ParallelCurl

答:
cUrl has an option called range that makes partial download of a file possible.
You can refer to this for more information about range and see a sample PHP cUrl request here

For running a multi_curl refer to this