问:
Bootstrap Modal Forms Posting Twice Django
I am following the instructions from django-bootstrap-modal-forms and what I am finding is that my form is posting or submitting twice when I submit the form.  First, the object was simply being created twice, I could see that from the admin.  Now it seems the form is creating the object, but also entering its validation state, which I obviously don't want if the form was successful, which it is.

Has anyone experienced this? I've done nothing more than what was outlined in the docs that I linked to and I cannot identify any reason why this should be submitting twice.

Here is my code:

home.html

```<code><a href="#" class="create-shipment dropdown-itemcreatenew" onclick="closeNav()">Shipment</a>

<div class="modal fade" tabindex="-1" role="dialog" id="modal">
  <div class="modal-dialog" role="document">
    <div class="modal-content">

    </div>
  </div>
</div>

<script>
$(document).ready(function() {

    $(".create-shipment").modalForm({
        formURL: "{% url 'CreateShipmentView' %}"
    });

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

views.py

```<code>class CreateShipmentView(BSModalCreateView):
    template_name = 'create_shipment.html'
    form_class = CreateShipmentForm
    success_message = 'Success: Shipment Has Been Created!'
    success_url = reverse_lazy('HomeView')
</code>```

create_shipment.html (template for modal form)

```<code>{% load crispy_forms_tags %}
<form method="post" action="">
  {% csrf_token %}

 <div class="modal-header">
    <h5 class="modal-title">Create New Shipment</h5>
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
  </div>

  <div class="modal-body">
    {{form|crispy}}
  </div>

  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="submit-btn btn btn-primary">Create</button>
  </div>

</form>
</code>```

forms.py

```<code>class CreateShipmentForm(BSModalForm):
    class Meta:
        model = Shipment
        fields = ['Reference_Number', 'Ultimate_Consignee']
</code>```

urls.py

```<code>url(r'^create_shipment/', views.CreateShipmentView.as_view(), name='CreateShipmentView'),
</code>```

Event Listeners on Submit Button

```<code> // Add click listener to the submitBtn
    var ajaxSubmit = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) {
        $(submitBtn).on("click", function () {
            // Check if form.is_valid() via ajax request when submitBtn is clicked
            isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm);
        });
    };

    // Check if form.is_valid() & either show errors or submit it
    var isFormValid = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn, callback) {
        $.ajax({
            type: $(modalForm).attr("method"),
            url: $(modalForm).attr("action"),
            // Serialize form data
            data: $(modalForm).serialize(),
            success: function (response) {
                if ($(response).find(errorClass).length > 0) {
                    // Form is not valid, update it with errors
                    $(modalID).find(modalContent).html(response);
                    $(modalForm).attr("action", formURL);
                    // Reinstantiate click listener on submitBtn
                    ajaxSubmit(modalID, modalContent, modalForm, formURL, errorClass, submitBtn);
                } else {
                    // Form is valid, submit it
                    callback(modalForm);
                }
            }
        });
    };
</code>```

答:
Update to this post: It seems like that the package was updated and the original issue was solved, thus links in this answer won't point you to the correct codes/comments anymore. If you are still experiencing the same problem, try upgrading the package first.

After reading the source code for the package, I believe that receiving two requests on the backend is normal.

Your code

$(document).ready(function() {

    $(".create-shipment").modalForm({
        formURL: "{% url 'CreateShipmentView' %}"
    });

});
```
<p>triggers the function <code>modalForm</code> where it takes your options (<code>formURL</code>) and assign the function <code>newForm</code> to a click event.</p>
<p>Then in the <code>newForm</code> function it calls the function <code>addListeners</code> to bind a click event to the submit button in the modal, and the event is called as following:</p>
<pre class="lang-js prettyprint-override"><code>isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm);
</code>```

Note that the last parameter submitForm points to the following function

var submitForm = function(modalForm) {
      $(modalForm).submit();
    };
```
<p>Finally in the function <code>isFormValid</code>, all the data you entered in the form will be posted to the url you defined in the <code>action</code> attribute for validation, and if there is no error, the form will be submitted to the very same url.</p>
<p>If you dig into the python code in this package, things become interesting. The <code>BSModalForm</code> is based on two classes in <code>mixins.py</code> and in here it says that when the request was made by anything other than ajax, save the instance created using the form data, or otherwise (if requested by ajax call) don't save the instance and return it. That's why it validated the form at first but should never save it (remember the first call was indeed originated by using the ajax call in jQuery).</p>
<p>You mentioned that the form was being saved twice - try to add a line at the beginning of the save function as</p>
<pre class="lang-py prettyprint-override"><code>print(request.is_ajax())
</code>```

and then check the output. it could be that the call failed to be sent as an AJAX call. (if that's the case, update your jquery version or use something else to make the call like axios)

If you don't like how things are happening, few options (package under MIT license):

Change the save function to validate the instance then save it as a normal django save function, but that involves changing some of the JS code.

Make an API endpoint to receive the data and communicate using json instead of returning html code every time (I guess this is also the reason why the author wrote the JS in the current way because you then face the rendering issue). Since currently you don't need to perform any other action after submitting the form, it doesn't make sense to return the instance anymore. (no need for DRF as there is a JsonResponse class built-in in django and if you only need this one endpoint)

Use BootStrap directly since the story here is rather simple: a modal on the page, a button to trigger the modal, a form in the modal and you can submit it. You might need to write some of your own JS for error displaying but it should still be easier than changing the existing package.

An example

# forms.py
from django import forms

# use django ModelForm for creating the form based on model
class CreateShipmentForm(forms.ModelForm):
    class Meta:
        model = Shipment
        fields = ['Reference_Number', 'Ultimate_Consignee']
```
<p>view for rendering the form (GET) and receiving form submissions (POST)</p>
<pre class="lang-py prettyprint-override"><code># views.py
from yourapp.forms import CreateShipmentForm
from django.shortcuts import render

def create_shipment_view(request):
    # http POST request means that the form was submitted
    if request.method == 'POST':
        # create the form and map the data to CreateShipmentForm
        shipment_form = CreateShipmentForm(request.POST)
        # based on your design of the form/modal, validate the data passed into the form
        if shipment_form.is_valid():
            # create a new shipment object
            new_shipment = shipment_form.save()
            # form processing is finished now do something to alert user, for example redirect the user to the success page
            return redirect('success')
        # if the form is not valid, then shipment_form.errors contain all the errors
    else:
        # for all other accessing methods including GET
        # create an empty form
        shipment_form = CreateShipmentForm()

    # if the request was POST, the form contains errors, if request was GET, it's an empty form
    return render(request, 'path/to/template.html', {
        'form': shipment_form
    })
</code>```

Finally in your template, you can just display the form as you would normally. If you don't know or need some other features for your form, keep using crispy forms.

check if shipment_form.errors in your template and display it in your template if you want to show errors to the users.

Body:
I am following the instructions from django-bootstrap-modal-forms and what I am finding is that my form is posting or submitting twice when I submit the form.  First, the object was simply being created twice, I could see that from the admin.  Now it seems the form is creating the object, but also entering its validation state, which I obviously don't want if the form was successful, which it is.

Has anyone experienced this? I've done nothing more than what was outlined in the docs that I linked to and I cannot identify any reason why this should be submitting twice.

Here is my code:

home.html

Shipment

views.py

class CreateShipmentView(BSModalCreateView):
    template_name = 'create_shipment.html'
    form_class = CreateShipmentForm
    success_message = 'Success: Shipment Has Been Created!'
    success_url = reverse_lazy('HomeView')

create_shipment.html (template for modal form)

{% load crispy_forms_tags %}
<form method="post" action="">
  {% csrf_token %}

Create New Shipment

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

    {{form|crispy}}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="button" class="submit-btn btn btn-primary">Create</button>

</form>

forms.py

class CreateShipmentForm(BSModalForm):
    class Meta:
        model = Shipment
        fields = ['Reference_Number', 'Ultimate_Consignee']

urls.py

url(r'^create_shipment/', views.CreateShipmentView.as_view(), name='CreateShipmentView'),

Event Listeners on Submit Button

 // Add click listener to the submitBtn
    var ajaxSubmit = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn) {
        $(submitBtn).on("click", function () {
            // Check if form.is_valid() via ajax request when submitBtn is clicked
            isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm);
        });
    };

    // Check if form.is_valid() & either show errors or submit it
    var isFormValid = function (modalID, modalContent, modalForm, formURL, errorClass, submitBtn, callback) {
        $.ajax({
            type: $(modalForm).attr("method"),
            url: $(modalForm).attr("action"),
            // Serialize form data
            data: $(modalForm).serialize(),
            success: function (response) {
                if ($(response).find(errorClass).length > 0) {
                    // Form is not valid, update it with errors
                    $(modalID).find(modalContent).html(response);
                    $(modalForm).attr("action", formURL);
                    // Reinstantiate click listener on submitBtn
                    ajaxSubmit(modalID, modalContent, modalForm, formURL, errorClass, submitBtn);
                } else {
                    // Form is valid, submit it
                    callback(modalForm);
                }
            }
        });
    };

Body:
Update to this post: It seems like that the package was updated and the original issue was solved, thus links in this answer won't point you to the correct codes/comments anymore. If you are still experiencing the same problem, try upgrading the package first.

After reading the source code for the package, I believe that receiving two requests on the backend is normal.

Your code

$(document).ready(function() {

    $(".create-shipment").modalForm({
        formURL: "{% url 'CreateShipmentView' %}"
    });

});

triggers the function modalForm where it takes your options (formURL) and assign the function newForm to a click event.

Then in the newForm function it calls the function addListeners to bind a click event to the submit button in the modal, and the event is called as following:

isFormValid(modalID, modalContent, modalForm, formURL, errorClass, submitBtn, submitForm);

Note that the last parameter submitForm points to the following function

var submitForm = function(modalForm) {
      $(modalForm).submit();
    };

Finally in the function isFormValid, all the data you entered in the form will be posted to the url you defined in the action attribute for validation, and if there is no error, the form will be submitted to the very same url.

If you dig into the python code in this package, things become interesting. The BSModalForm is based on two classes in mixins.py and in here it says that when the request was made by anything other than ajax, save the instance created using the form data, or otherwise (if requested by ajax call) don't save the instance and return it. That's why it validated the form at first but should never save it (remember the first call was indeed originated by using the ajax call in jQuery).

You mentioned that the form was being saved twice - try to add a line at the beginning of the save function as

print(request.is_ajax())

and then check the output. it could be that the call failed to be sent as an AJAX call. (if that's the case, update your jquery version or use something else to make the call like axios)

If you don't like how things are happening, few options (package under MIT license):

Change the save function to validate the instance then save it as a normal django save function, but that involves changing some of the JS code.

Make an API endpoint to receive the data and communicate using json instead of returning html code every time (I guess this is also the reason why the author wrote the JS in the current way because you then face the rendering issue). Since currently you don't need to perform any other action after submitting the form, it doesn't make sense to return the instance anymore. (no need for DRF as there is a JsonResponse class built-in in django and if you only need this one endpoint)

Use BootStrap directly since the story here is rather simple: a modal on the page, a button to trigger the modal, a form in the modal and you can submit it. You might need to write some of your own JS for error displaying but it should still be easier than changing the existing package.

An example

# forms.py
from django import forms

# use django ModelForm for creating the form based on model
class CreateShipmentForm(forms.ModelForm):
    class Meta:
        model = Shipment
        fields = ['Reference_Number', 'Ultimate_Consignee']

view for rendering the form (GET) and receiving form submissions (POST)

# views.py
from yourapp.forms import CreateShipmentForm
from django.shortcuts import render

def create_shipment_view(request):
    # http POST request means that the form was submitted
    if request.method == 'POST':
        # create the form and map the data to CreateShipmentForm
        shipment_form = CreateShipmentForm(request.POST)
        # based on your design of the form/modal, validate the data passed into the form
        if shipment_form.is_valid():
            # create a new shipment object
            new_shipment = shipment_form.save()
            # form processing is finished now do something to alert user, for example redirect the user to the success page
            return redirect('success')
        # if the form is not valid, then shipment_form.errors contain all the errors
    else:
        # for all other accessing methods including GET
        # create an empty form
        shipment_form = CreateShipmentForm()

    # if the request was POST, the form contains errors, if request was GET, it's an empty form
    return render(request, 'path/to/template.html', {
        'form': shipment_form
    })

Finally in your template, you can just display the form as you would normally. If you don't know or need some other features for your form, keep using crispy forms.

check if shipment_form.errors in your template and display it in your template if you want to show errors to the users.


来源: stackexchange

问:
How do I Rewrite URL from some-sub-domain.some-domain.com to some-domain.com/some-sub-domain
I want to rewrite my URL, so that I can reach the folder which is seen by the clients as sub-domain. Client will put the following in the URL Bar:

```<code>abc.def.com
</code>```

and by URL rewrite it will be gone to

```<code>def.com/abc
</code>```

silently. Please tell me how can I do that ?

答:
There is a very few change in your RewriteRule to work this well

```<code> RewriteCond %{HTTP_HOST} ^(?:www\.)?([^\.]+)\.your_domain\.com [NC]
 RewriteRule ^(.*)$ /%1/$1 [L]
</code>```

You should use $ in the RewriteRule. Hope this helpful for you.

ContentLicense: CC BY-SA 3.0

Body:
I want to rewrite my URL, so that I can reach the folder which is seen by the clients as sub-domain. Client will put the following in the URL Bar:

abc.def.com

and by URL rewrite it will be gone to

def.com/abc

silently. Please tell me how can I do that ?

Body:
There is a very few change in your RewriteRule to work this well

 RewriteCond %{HTTP_HOST} ^(?:www\.)?([^\.]+)\.your_domain\.com [NC]
 RewriteRule ^(.*)$ /%1/$1 [L]

You should use $ in the RewriteRule. Hope this helpful for you.


问:
Concatenate two numpy arrays so that index order keeps the same?
Assume I have two numpy arrays as follows:

```<code>{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}
</code>```

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

```<code>array([1, 0, 1, 0, 1, 0, 0 ,0])
</code>```

But that's what I get:

```<code>np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])
</code>```

(Each array contains only unique values, if this helps.)

How can this be done?

答:
Your description of merging is a bit unclear.  But here's something that makes sense

```<code>In [399]: dd ={0: np.array([ 2, 4, 8, 9, 12]),
     ...: 1: np.array([ 1, 3, 5])}

In [403]: res = np.zeros(13, int)
In [404]: res[dd[0]] = 0
In [405]: res[dd[1]] = 1
In [406]: res
Out[406]: array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0])
</code>```

Or to make the assignments clearer:

```<code>In [407]: res = np.zeros(13, int)
In [408]: res[dd[0]] = 2
In [409]: res[dd[1]] = 1
In [410]: res
Out[410]: array([0, 1, 2, 1, 2, 1, 0, 0, 2, 2, 0, 0, 2])
</code>```

Otherwise the talk index positions doesn't make a whole lot of sense.

ContentLicense: CC BY-SA 4.0

Body:
Assume I have two numpy arrays as follows:

{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

array([1, 0, 1, 0, 1, 0, 0 ,0])

But that's what I get:

np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])

(Each array contains only unique values, if this helps.)

How can this be done?

Body:
Your description of merging is a bit unclear.  But here's something that makes sense

In [399]: dd ={0: np.array([ 2, 4, 8, 9, 12]),
     ...: 1: np.array([ 1, 3, 5])}

In [403]: res = np.zeros(13, int)
In [404]: res[dd[0]] = 0
In [405]: res[dd[1]] = 1
In [406]: res
Out[406]: array([0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0])

Or to make the assignments clearer:

In [407]: res = np.zeros(13, int)
In [408]: res[dd[0]] = 2
In [409]: res[dd[1]] = 1
In [410]: res
Out[410]: array([0, 1, 2, 1, 2, 1, 0, 0, 2, 2, 0, 0, 2])

Otherwise the talk index positions doesn't make a whole lot of sense.


问:
Drone CI failing on clone step
I'm running on a machine in docker-compose the following:

gitlab

drone (server)

drone (agent)

and when I trigger a build (or triggered by git push), drone keeps on failing on the issue:

```<code>git init
Initialized empty Git repository in /drone/src/.git/
git remote add origin http://my-git/amaziagur/location-service.git
git fetch --no-tags origin +refs/heads/master:
fatal: unable to access 'http://my-git/amaziagur/location-service.git/': Couldn't resolve host 'my-git'
exit status 128
</code>```

here is the docker-compose.yml:

```<code>version: '2'
services:
  #PROXY
  gitlab:
    image: 'gitlab/gitlab-ce:9.1.0-ce.0'
    restart: always
    hostname: 'my-git'
    links:
      - postgresql:postgresql
      - redis:redis
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        postgresql['enable'] = false
        gitlab_rails['db_username'] = "gitlab"
        gitlab_rails['db_password'] = "gitlab"
        gitlab_rails['db_host'] = "postgresql"
        gitlab_rails['db_port'] = "5432"
        gitlab_rails['db_database'] = "gitlabhq_production"
        gitlab_rails['db_adapter'] = 'postgresql'
        gitlab_rails['db_encoding'] = 'utf8'
        redis['enable'] = false
        gitlab_rails['redis_host'] = 'redis'
        gitlab_rails['redis_port'] = '6379'
        external_url 'http://my-git'
        gitlab_rails['gitlab_shell_ssh_port'] = 30022
    ports:
      # both ports must match the port from external_url above
      - "80:80"
      # the mapped port must match ssh_port specified above.
      - "30022:22"
  # the following are hints on what volumes to mount if you want to persist data
    volumes:
     - /data/gitlab/config:/etc/gitlab:rw
     - /data/gitlab/logs:/var/log/gitlab:rw
     - /data/gitlab/data:/var/opt/gitlab:rw

  postgresql:
    restart: always
    image: postgres:9.6.2-alpine
    environment:
      - POSTGRES_USER=gitlab
      - POSTGRES_PASSWORD=gitlab
      - POSTGRES_DB=gitlabhq_production
  # the following are hints on what volumes to mount if you want to persist data
    volumes:
     - /home/foresight/postgresql:/var/lib/postgresql:rw

  redis:
    restart: always
    image: redis:3.0.7-alpine
  # DRONE
  drone-server:
    image: drone/drone:0.7.3
    ports:
      - "8000:8000"
    networks:
      - drone
      - gitlab
    links:
     - gitlab
    volumes:
      - /home/drone:/var/lib/drone/
    environment:
      #@@@@@
      DRONE_OPEN: "true"
      DRONE_HOST: "http://10.0.0.200:8000"
      DRONE_ADMIN: amaziagur
      DRONE_GITLAB: "true"
      DRONE_GITLAB_URL: "http://10.0.0.200"
      DRONE_GITLAB_CLIENT: "secret"
      DRONE_GITLAB_SECRET: "secret"
      DRONE_SECRET: "my_secret"
      #@@@@@@@
  drone-agent:
    image: drone/drone:0.7.3
    command: agent
    depends_on:
      - drone-server
    networks:
      - drone
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      DRONE_SERVER: ws://drone-server:8000/ws/broker
      DRONE_DEBUG: "true"
      DRONE_SECRET: "our_secret_4ever_and_ever"

networks:
  drone:
    driver: bridge
  gitlab:
    driver: bridge
</code>```

Both are installed on the same machine, and I can't figure out what I'm doing wrong, what is the reason that the drone keeps not recognizing the git host.

I already added the mapping in my local /etc/hosts and on /etc/resolve.conf tips that I found around the web.
Can someone help?

答:
As this is the highest ranking question for this issue I thought to round this up.

The previously mentioned issue has the response you need, but it isn't immediately clear, as it is in the github mentions log and the originally linked issue was closed without a solution.

Solution

You can pass DRONE_RUNNER_NETWORKS= to the agent (or
  the server if you are not using agents). When Drone spawns containers
  it will attach all containers to the specified network.

Source: https://discourse.drone.io/t/gitea-drone-traefik-agent-cannot-reach-git-repo/4170/2?u=bradrydzewski

Note that you also want to add the networks to your runner in docker-compose: https://docs.docker.com/compose/networking/#specify-custom-networks - otherwise the initial pings will fail and no further runners will be spawned.

An example for a full drone docker runner:

```<code>drone-runner-docker:
  volumes:
      - '/var/run/docker.sock:/var/run/docker.sock'
  environment:
      - DRONE_RPC_PROTO=http
      - DRONE_RPC_HOST=172.20.0.19
      - DRONE_RPC_SECRET=SECRET
      - DRONE_RUNNER_CAPACITY=2
      - DRONE_RUNNER_NAME=drone-runner-docker
      - DRONE_RUNNER_NETWORKS=droneio_network,another_network
  networks:
      droneio_network:
      another_network:
  ports:
      - '3000'
  restart: always
  image: 'drone/drone-runner-docker:latest'
</code>```

Refer to the drone docs for explanation of the variables.

Make sure the names you provide in the environment for DRONE_RUNNER_NETWORKS are the actual network names from docker network ls. (if spawned via docker-compose they usually have the folder name infront, e.g. foldername_default)

Title: Drone CI failing on clone step

Body:
I'm running on a machine in docker-compose the following:

gitlab

drone (server)

drone (agent)

and when I trigger a build (or triggered by git push), drone keeps on failing on the issue:

git init
Initialized empty Git repository in /drone/src/.git/
git remote add origin http://my-git/amaziagur/location-service.git
git fetch --no-tags origin +refs/heads/master:
fatal: unable to access 'http://my-git/amaziagur/location-service.git/': Couldn't resolve host 'my-git'
exit status 128

here is the docker-compose.yml:

version: '2'
services:
  #PROXY
  gitlab:
    image: 'gitlab/gitlab-ce:9.1.0-ce.0'
    restart: always
    hostname: 'my-git'
    links:
      - postgresql:postgresql
      - redis:redis
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        postgresql['enable'] = false
        gitlab_rails['db_username'] = "gitlab"
        gitlab_rails['db_password'] = "gitlab"
        gitlab_rails['db_host'] = "postgresql"
        gitlab_rails['db_port'] = "5432"
        gitlab_rails['db_database'] = "gitlabhq_production"
        gitlab_rails['db_adapter'] = 'postgresql'
        gitlab_rails['db_encoding'] = 'utf8'
        redis['enable'] = false
        gitlab_rails['redis_host'] = 'redis'
        gitlab_rails['redis_port'] = '6379'
        external_url 'http://my-git'
        gitlab_rails['gitlab_shell_ssh_port'] = 30022
    ports:
      # both ports must match the port from external_url above
      - "80:80"
      # the mapped port must match ssh_port specified above.
      - "30022:22"
  # the following are hints on what volumes to mount if you want to persist data
    volumes:
     - /data/gitlab/config:/etc/gitlab:rw
     - /data/gitlab/logs:/var/log/gitlab:rw
     - /data/gitlab/data:/var/opt/gitlab:rw

  postgresql:
    restart: always
    image: postgres:9.6.2-alpine
    environment:
      - POSTGRES_USER=gitlab
      - POSTGRES_PASSWORD=gitlab
      - POSTGRES_DB=gitlabhq_production
  # the following are hints on what volumes to mount if you want to persist data
    volumes:
     - /home/foresight/postgresql:/var/lib/postgresql:rw

  redis:
    restart: always
    image: redis:3.0.7-alpine
  # DRONE
  drone-server:
    image: drone/drone:0.7.3
    ports:
      - "8000:8000"
    networks:
      - drone
      - gitlab
    links:
     - gitlab
    volumes:
      - /home/drone:/var/lib/drone/
    environment:
      #@@@@@
      DRONE_OPEN: "true"
      DRONE_HOST: "http://10.0.0.200:8000"
      DRONE_ADMIN: amaziagur
      DRONE_GITLAB: "true"
      DRONE_GITLAB_URL: "http://10.0.0.200"
      DRONE_GITLAB_CLIENT: "secret"
      DRONE_GITLAB_SECRET: "secret"
      DRONE_SECRET: "my_secret"
      #@@@@@@@
  drone-agent:
    image: drone/drone:0.7.3
    command: agent
    depends_on:
      - drone-server
    networks:
      - drone
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      DRONE_SERVER: ws://drone-server:8000/ws/broker
      DRONE_DEBUG: "true"
      DRONE_SECRET: "our_secret_4ever_and_ever"

networks:
  drone:
    driver: bridge
  gitlab:
    driver: bridge

Both are installed on the same machine, and I can't figure out what I'm doing wrong, what is the reason that the drone keeps not recognizing the git host.

I already added the mapping in my local /etc/hosts and on /etc/resolve.conf tips that I found around the web.
Can someone help?

Body:
As this is the highest ranking question for this issue I thought to round this up.

The previously mentioned issue has the response you need, but it isn't immediately clear, as it is in the github mentions log and the originally linked issue was closed without a solution.

Solution

You can pass DRONE_RUNNER_NETWORKS= to the agent (or
  the server if you are not using agents). When Drone spawns containers
  it will attach all containers to the specified network.

Source: https://discourse.drone.io/t/gitea-drone-traefik-agent-cannot-reach-git-repo/4170/2?u=bradrydzewski

Note that you also want to add the networks to your runner in docker-compose: https://docs.docker.com/compose/networking/#specify-custom-networks - otherwise the initial pings will fail and no further runners will be spawned.

An example for a full drone docker runner:

drone-runner-docker:
  volumes:
      - '/var/run/docker.sock:/var/run/docker.sock'
  environment:
      - DRONE_RPC_PROTO=http
      - DRONE_RPC_HOST=172.20.0.19
      - DRONE_RPC_SECRET=SECRET
      - DRONE_RUNNER_CAPACITY=2
      - DRONE_RUNNER_NAME=drone-runner-docker
      - DRONE_RUNNER_NETWORKS=droneio_network,another_network
  networks:
      droneio_network:
      another_network:
  ports:
      - '3000'
  restart: always
  image: 'drone/drone-runner-docker:latest'

Refer to the drone docs for explanation of the variables.

Make sure the names you provide in the environment for DRONE_RUNNER_NETWORKS are the actual network names from docker network ls. (if spawned via docker-compose they usually have the folder name infront, e.g. foldername_default)


问:
Access static json file in google app engine 2.7 standard environment - IOError(2, 'No such file or directory')
We are trying to access .json file inside our python code in Google App Engine.

Here is our app.yaml

```<code>service: worker
instance_class: F2
runtime: python27
api_version: 1
threadsafe: true
automatic_scaling:
  max_instances: 100
  min_pending_latency: 200ms  # default value
  max_pending_latency: automatic

handlers:

- url: /stylesheets
  static_dir: stylesheets

- url: /images
  static_dir: images

- url: /javascripts
  static_dir: javascripts

- url: /(.*\.(gif|png|jpg|json))$
  static_files: static/\1
  upload: static/.*\.(gif|png|jpg|json)$
  application_readable: true

- url: /static
  static_dir: static
  application_readable: true

- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /.*
  script: worker.app
  login: admin

libraries:
- name: webapp2
  version: "2.5.2"
- name: jinja2
  version: latest
</code>```

We are using it in our application like this.

```<code> path = os.path.join(os.path.dirname(__file__)[0], '/static/google_web_app_script_credentials.json')
 flow = InstalledAppFlow.from_client_secrets_file(path,self.GOOGLESHEETS_SCOPES )
</code>```

But we are receiving the error.

```<code>IOError(2, 'No such file or directory')
</code>```

We have tried various options of changing path including path = os.path.join(os.path.dirname(file)[0], '../static/google_web_app_script_credentials.json')

When we go to the GCP console -> Debug and review the current code we are able to see the .json file under static folder. This means that the file is there, we are not able to get the application to read it. This service is as "worker".

答:
From your App Engine app, you don't have access to your static files.  Move the file to another location within your project, and you will then be able to access it.

Even more importantly, you don't want to store credentials in your static folder!  Anyone on the web will be able to access them via the URL!

Body:
We are trying to access .json file inside our python code in Google App Engine.

Here is our app.yaml

service: worker
instance_class: F2
runtime: python27
api_version: 1
threadsafe: true
automatic_scaling:
  max_instances: 100
  min_pending_latency: 200ms  # default value
  max_pending_latency: automatic

handlers:

- url: /stylesheets
  static_dir: stylesheets

- url: /images
  static_dir: images

- url: /javascripts
  static_dir: javascripts

- url: /(.*\.(gif|png|jpg|json))$
  static_files: static/\1
  upload: static/.*\.(gif|png|jpg|json)$
  application_readable: true

- url: /static
  static_dir: static
  application_readable: true

- url: /favicon\.ico
  static_files: favicon.ico
  upload: favicon\.ico

- url: /.*
  script: worker.app
  login: admin

libraries:
- name: webapp2
  version: "2.5.2"
- name: jinja2
  version: latest

We are using it in our application like this.

 path = os.path.join(os.path.dirname(__file__)[0], '/static/google_web_app_script_credentials.json')
 flow = InstalledAppFlow.from_client_secrets_file(path,self.GOOGLESHEETS_SCOPES )

But we are receiving the error.

IOError(2, 'No such file or directory')

We have tried various options of changing path including path = os.path.join(os.path.dirname(file)[0], '../static/google_web_app_script_credentials.json')

When we go to the GCP console -> Debug and review the current code we are able to see the .json file under static folder. This means that the file is there, we are not able to get the application to read it. This service is as "worker".


问:
ensure that the two rows In my bootstrap table are always side by side regardless of the length of text
I have a Bootstrap panel with text within a table. One side of the text is links and the other is descriptions. What I notice is that I have to fake the length of the text sometimes to ensure that the text will appear next to the link/description.

How can I efficiently set up these rows so that the text will always be next to the designated link or description regardless of the length of the text? I need it to be flexible enough to still display on same line but obviously a different row

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Plan

      Set project strategy, tactics and timing
      Project Brief

      Choose the right channel for your communication
      Channel Guidelines

      Add your project to the calendar

      Communications Calendar Intake

      Submit outbound call/text programs
      website to test

      Review vendor guidelines and share communication requirements with vendors
      Vendor Guidelines

```

答:
The approach you used wouldn't work on all screen resolutions... a better way is to use vertical-align:middle;

I have duplicated the 2 rows without the  that you had added... These are colored green, and it is where I have used vertical-align property also;

working snippet below:

.table thead td {
  background-color: lightgreen;
  vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h4>Plan</h4>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>Set project strategy, tactics and timing</th>
          <th>Project Brief</th>
        </tr>
        <tr>
          <th>Choose the right channel for your communication</th>
          <th>Channel Guidelines                       </th>
        </tr>
        <tr>
          <th>Choose the right channel for your communication</th>
          <td>Channel Guidelines
          </td>
        </tr>
        <tr>
          <th>Add your project to the calendar<br><br></th>
          <th>Communications Calendar Intake </th>
        </tr>
        <tr>
          <th>Submit outbound call/text programs </th>
          <th>website to test</th>
        </tr>
        <tr>
          <th>Review vendor guidelines and share communication requirements with vendors</th>
          <th style="margin-left: 100px;">Vendor Guidelines                      </th>
        </tr>
        <tr>
          <th>Review vendor guidelines and share communication requirements with vendors</th>
          <td style="margin-left: 100px;">Vendor Guidelines
          </td>
        </tr>
      </thead>
    </table>
  </div>
</div></code>```

Body:
The approach you used wouldn't work on all screen resolutions... a better way is to use vertical-align:middle;

I have duplicated the 2 rows without the &zwnj; that you had added... These are colored green, and it is where I have used vertical-align property also;

working snippet below:

.table thead td {
  background-color: lightgreen;
  vertical-align: middle;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h4>Plan</h4>
    </div>
    <table class="table">
      <thead>
        <tr>
          <th>Set project strategy, tactics and timing</th>
          <th><a href="" target="_blank">Project Brief</a></th>
        </tr>
        <tr>
          <th>Choose the right channel for your communication</th>
          <th><a href="" target="_blank">Channel Guidelines</a> &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj;&zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj;&zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; </th>
        </tr>
        <tr>
          <th>Choose the right channel for your communication</th>
          <td><a href="" target="_blank">Channel Guidelines</a>
          </td>
        </tr>
        <tr>
          <th>Add your project to the calendar<br><br></th>
          <th><a href="" target="_blank">Communications Calendar Intake</a> </th>
        </tr>
        <tr>
          <th>Submit outbound call/text programs </th>
          <th><a href="" target="_blank">website to test</a></th>
        </tr>
        <tr>
          <th>Review vendor guidelines and share communication requirements with vendors</th>
          <th style="margin-left: 100px;"><a href="" target="_blank">Vendor Guidelines</a> &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj;&zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj;&zwnj; &zwnj; &zwnj; &zwnj; &zwnj; &zwnj;</th>
        </tr>
        <tr>
          <th>Review vendor guidelines and share communication requirements with vendors</th>
          <td style="margin-left: 100px;"><a href="" target="_blank">Vendor Guidelines</a>
          </td>
        </tr>
      </thead>
    </table>
  </div>
</div>


问:
How to make a Azure SQL Exec or select another table/procedure in another Azure SQL
I've two Azure SQL Servers, each one contains one database, I need to exec Selects or Stored procedures between them.

For example:

Server1.database.windows.net DB: local1
Server2.database.windows.net DB: remote1

in Server1: Select * from Server2.remote1.dbo.Orders and this query return a list of orders.

in Server2: Exec Server1.local1.dbo.ProcedureOrders and this execute a stored procedure in Server1

First of all, is this possible? If yes, how?

答:
You can use elastic queries to query tables across different databases in different logical servers and even when they belong to different subscriptions. You can find and example here.

You can also run transactions across databases on different logical servers as announced in this article.


问:
Are small http requests faster?
I'm implementing an autocomplete-style search in my webapp. Every character that the user types will trigger a search request to the server. The requests and responses must be fast. Milliseconds matter.

As part of the app, I'm considering adding a custom request header. Unfortunately, this extra header will take another 150 bytes. The request itself will be only a short URL, plus a few bytes in the POST body, plus standard headers send automatically by the browser.

Will the custom header affect the speed much?

On one hand, it seems obvious that it would. A bigger request will take longer for the browser to process and send.

On the other hand, the speed difference might be negligible. There might be a lot of other network overhead along the way.

(I'm not concerned about the time it takes the server to process the header. It's definitely going to be well less than a millisecond.)

答:
Will the custom header affect the speed much?

The usual answer: what happened when you tested it?

No. It won't affect it much unless your code is really, really slow (and you've said that's not the case). Even with HTTP/2 reusing a connection, the performance should be dominated by the network RTT. The time taken to transfer the data will be small.

Title: Are small http requests faster?


问:
how to upload a image file to specific drive location and store the path to database
I want to upload an image to a disk drive location in future it may be server drive location and it will display the same on a webpage using file path location that should be fetched from the database.

I tried to upload the images to the project directory, but the image file is not getting uploaded. However, when I refresh the project directory it will appear there.

The path I provided is a project location directory.

```<code>@MultipartConfig

//@WebServlet("/NewAddProject")

public class NewAddProject extends HttpServlet {

private File file;

boolean flag1 = false, flag2 = false, flag3 = false;
String p_id;
String img_sr_no;
String project_name = null;
String project_type = null;
String project_location = null;
String project_photo = null;
String project_ststus = null;
javax.servlet.http.Part img1part;
Part imgpart;
String imgName = null;
// String pdfName = null;
String content_type1;
String store_id;
String created_date;
PreparedStatement pst;
int i;
/**
 * @see HttpServlet#HttpServlet()
 */
public NewAddProject() {
    super();
    // TODO Auto-generated constructor stub
}
public void init() {
    myOldFilePath = getServletContext().getInitParameter("file-upload");
    if (!new File(myOldFilePath).exists()) {
        (new File(myOldFilePath)).mkdir();
    }
    filePath = myOldFilePath + "\\" + "NewProjectDetails" + "\\";
    File directory1 = new File(filePath);
    if (directory1.exists()) {} else {
        directory1.mkdir();
    }
    System.out.println(filePath);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    java.io.PrintWriter out = response.getWriter();

    String imagePath = "D:\\JAVA PROJECTS 2019\\RealValueProperties\\RealValueProperties_04_03_2019\\RealValueProperties\\WebContent\\projectimages\\images\\img";

    String absolutePathToImages = request.getSession().getServletContext().getRealPath("/projectimages/");
    final String DIRECTORY_PATH = absolutePathToImages + "images" + File.separator + "";
    project_name = request.getParameter("project_name");
    System.out.println(project_name);
    project_type = request.getParameter("property_type");
    System.out.println(project_type);
    project_location = request.getParameter("project_location");
    System.out.println(project_location);
    project_ststus = request.getParameter("project_ststus");
    System.out.println(project_ststus);
    imgpart = request.getPart("project_image"); // for image

    if (imgpart != null) {
        try {
            imgName = imgpart.getSubmittedFileName();
            imgName = GetImageID.getImageID() + imgName;
            System.out.println("image name" + imgName);
            flag1 = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("path: " + filePath);

    imgpart.write(imagePath + imgName);

    //      imgpart.write(new File(DIRECTORY_PATH) + File.separator + "img" + File.separator + imgName);
    System.out.println("uploaded : " + DIRECTORY_PATH);
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded...");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/realvalueproperties", "root", "");
        System.out.println("Connected...");
        String query2 = "INSERT into addnewproject ( p_id, project_name, project_type, " +
            "project_location, project_image,project_ststus)" + "values(?,?,?,?,?,?)";
        PreparedStatement pst2 = conn.prepareStatement(query2);
        pst2.setString(1, null);
        pst2.setString(2, project_name);
        pst2.setString(3, project_type);
        pst2.setString(4, project_location);
        //          pst2.setString(5, filePath + imgName);
        pst2.setString(5, "projectimages/images/img" + imgName);
        pst2.setString(6, project_ststus);
        int i = pst2.executeUpdate();
        if (i > 0) {
            System.out.println("Insered to dbt ");
            response.sendRedirect("add_new_projects.jsp");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            conn.close();
            // response.sendRedirect("student_home.jsp");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}
</code>```

I expect that the image file should be uploaded to the particular drive location. It may be local or server drive location. That path should be stored in a database and displayed the same on the web page.

答:
All you need to do is open eclipse
then go to Windows Tab click Preferences
then expand General then click on Workspace
then check :

Refresh using native hooks and pooling

Refresh on Access

click Apply then ok

Body:
I want to upload an image to a disk drive location in future it may be server drive location and it will display the same on a webpage using file path location that should be fetched from the database.

I tried to upload the images to the project directory, but the image file is not getting uploaded. However, when I refresh the project directory it will appear there.

The path I provided is a project location directory.

@MultipartConfig

//@WebServlet("/NewAddProject")

public class NewAddProject extends HttpServlet {

private File file;

boolean flag1 = false, flag2 = false, flag3 = false;
String p_id;
String img_sr_no;
String project_name = null;
String project_type = null;
String project_location = null;
String project_photo = null;
String project_ststus = null;
javax.servlet.http.Part img1part;
Part imgpart;
String imgName = null;
// String pdfName = null;
String content_type1;
String store_id;
String created_date;
PreparedStatement pst;
int i;
/**
 * @see HttpServlet#HttpServlet()
 */
public NewAddProject() {
    super();
    // TODO Auto-generated constructor stub
}
public void init() {
    myOldFilePath = getServletContext().getInitParameter("file-upload");
    if (!new File(myOldFilePath).exists()) {
        (new File(myOldFilePath)).mkdir();
    }
    filePath = myOldFilePath + "\\" + "NewProjectDetails" + "\\";
    File directory1 = new File(filePath);
    if (directory1.exists()) {} else {
        directory1.mkdir();
    }
    System.out.println(filePath);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    java.io.PrintWriter out = response.getWriter();

    String imagePath = "D:\\JAVA PROJECTS 2019\\RealValueProperties\\RealValueProperties_04_03_2019\\RealValueProperties\\WebContent\\projectimages\\images\\img";

    String absolutePathToImages = request.getSession().getServletContext().getRealPath("/projectimages/");
    final String DIRECTORY_PATH = absolutePathToImages + "images" + File.separator + "";
    project_name = request.getParameter("project_name");
    System.out.println(project_name);
    project_type = request.getParameter("property_type");
    System.out.println(project_type);
    project_location = request.getParameter("project_location");
    System.out.println(project_location);
    project_ststus = request.getParameter("project_ststus");
    System.out.println(project_ststus);
    imgpart = request.getPart("project_image"); // for image

    if (imgpart != null) {
        try {
            imgName = imgpart.getSubmittedFileName();
            imgName = GetImageID.getImageID() + imgName;
            System.out.println("image name" + imgName);
            flag1 = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("path: " + filePath);

    imgpart.write(imagePath + imgName);

    //      imgpart.write(new File(DIRECTORY_PATH) + File.separator + "img" + File.separator + imgName);
    System.out.println("uploaded : " + DIRECTORY_PATH);
    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver loaded...");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/realvalueproperties", "root", "");
        System.out.println("Connected...");
        String query2 = "INSERT into addnewproject ( p_id, project_name, project_type, " +
            "project_location, project_image,project_ststus)" + "values(?,?,?,?,?,?)";
        PreparedStatement pst2 = conn.prepareStatement(query2);
        pst2.setString(1, null);
        pst2.setString(2, project_name);
        pst2.setString(3, project_type);
        pst2.setString(4, project_location);
        //          pst2.setString(5, filePath + imgName);
        pst2.setString(5, "projectimages/images/img" + imgName);
        pst2.setString(6, project_ststus);
        int i = pst2.executeUpdate();
        if (i > 0) {
            System.out.println("Insered to dbt ");
            response.sendRedirect("add_new_projects.jsp");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            conn.close();
            // response.sendRedirect("student_home.jsp");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
}

I expect that the image file should be uploaded to the particular drive location. It may be local or server drive location. That path should be stored in a database and displayed the same on the web page.


问:
How do I call a function immediately upon an iPhone app resuming from a saved state?

User has my app open.

They hit the home button, resulting in my app closing and going into a "saved state".

Users uses his device for other things.

User opens up my app again, resuming from where he left off.

How, in my code, do I detect that the user has resumed from the saved state? Is there a specific iOS4 multitasking NSNotification that I can attach to?

答:
AppDelegate.m:</p>

```<code>- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"Application did enter background.");
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"Application did become active.");
}
</code>```

Body:
AppDelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"Application did enter background.");
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    NSLog(@"Application did become active.");
}


问:
Order Boxplots by their Means
How do you go about changing the order or boxplots so that they are ordered greatest to least by their means.

This is my attempt of reordering the boxplots by their means:

```<code>url <- "http://www.cse.lehigh.edu/~brian/course/2020/datascience/student-teacher-ratios.csv"
df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean))
with(df_ratios, boxplot(student_ratio~s2))
</code>```

答:
A solution using the ggplots2 and forcats packages, assuming you mean that they should be ordered according by the median.</p>

```<code>library(ggplot2)
library(forcats)

ggplot(df_ratios, aes(x = fct_reorder(region, student_ratio, .fun = median), y = student_ratio)) + geom_boxplot()
</code>```

Title: Order Boxplots by their Means

Body:
How do you go about changing the order or boxplots so that they are ordered greatest to least by their means.

This is my attempt of reordering the boxplots by their means:

url <- "http://www.cse.lehigh.edu/~brian/course/2020/datascience/student-teacher-ratios.csv"
df_ratios <- read.csv(url, header=T)
s2 <- with(df_ratios, reorder(region, -student_ratio, mean))
with(df_ratios, boxplot(student_ratio~s2))

Body:
A solution using the ggplots2 and forcats packages, assuming you mean that they should be ordered according by the median.

library(ggplot2)
library(forcats)

ggplot(df_ratios, aes(x = fct_reorder(region, student_ratio, .fun = median), y = student_ratio)) + geom_boxplot()


问:
Rust NdArray Distance Matrix
I am trying to write a a function that calculates distance matrices using ndarray:

```<code>extern crate ndarray;

use ndarray::{s, Array2, ArrayView1, indices_of, azip, array};
use ndarray::parallel::par_azip;
use std::f64;

type M = Array2<f64>;

fn main() {
    // make some arbitrary data
    let points = array!([0.,23.], [12., 13.], [15., 2.], [16., 145.], [42., 11.], [12., 12.], [11., 12.], [56., 18.], [34., 12.]);
    // calculate matrix
    let dist_arr = dist_to_mat(&points, &l2);
    println!("{}", dist_arr.mapv(|x| (100. * x).round() / 100.))
}

// as an example, use l2 distance
fn l2(x: &ArrayView1<f64>, y: &ArrayView1<f64>) -> f64 {
    let diff = x - y;
    let result = (&diff * &diff).sum();
    return result.sqrt()
}

pub fn dist_to_mat(
    points: &Array2<f64>,
    dist_fn: &dyn Fn(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
) -> M {
    // initialize array
    let mut distances = Array2::zeros((points.nrows(), points.nrows()));
    let idx = indices_of(&distances);
    // helper function to get the entries of points
    let func = |i: usize, j: usize| -> f64 {
        dist_fn(&points.slice(s![i, ..]), &points.slice(s![j, ..]))
    };
    // apply function to matrix with index array in lock-step
    par_azip!((c in &mut distances, (i,j) in idx){*c = func(i,j)}); // <- error here; works if par_azip is replaced with azip.
    return distances
}
</code>```

While this works fine with the single-threaded azip, with par_azip I get the error:

`dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely

`dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely

help: within `[closure@<::ndarray::zip::zipmacro::azip macros>:23:6: 23:7 func:&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]]`, the trait `std::marker::Sync` is not implemented for `dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]`
note: required because it appears within the type `&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]`
note: required because it appears within the type `[closure@<::ndarray::zip::zipmacro::azip macros>:23:6: 23:7 func:&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]]`rustc(E0277)
<::ndarray::parallel::zipmacro::par_azip macros>(1, 50): `dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely
```

Which object cannot be shared between threads safely: the return value of dist_fun or dist_fun? How do I fix this?

答:
Fixed it. see <-

```<code>extern crate ndarray;

use ndarray::{s, Array2, ArrayView1, indices_of, azip, array};
use ndarray::parallel::par_azip;
use std::f64;

type M = Array2<f64>;

fn main() {
    // make some arbitrary data
    let points = array!([0.,23.], [12., 13.], [15., 2.], [16., 145.], [42., 11.], [12., 12.], [11., 12.], [56., 18.], [34., 12.]);
    // calculate matrix
    let dist_arr = dist_to_mat(&points, &l2);
    println!("{}", dist_arr.mapv(|x| (100. * x).round() / 100.))
}

// as an example, use l2 distance
fn l2(x: &ArrayView1<f64>, y: &ArrayView1<f64>) -> f64 {
    let diff = x - y;
    let result = (&diff * &diff).sum();
    return result.sqrt()
}

pub fn dist_to_mat(
    points: &Array2<f64>,
    dist_fn: &fn(&ArrayView1<f64>, &ArrayView1<f64>) -> f64, // <- different signature
) -> M {
    // initialize array
    let mut distances = Array2::zeros((points.nrows(), points.nrows()));
    let idx = indices_of(&distances);
    // helper function to get the entries of points
    let func = |i: usize, j: usize| -> f64 {
        dist_fn(&points.slice(s![i, ..]), &points.slice(s![j, ..]))
    };
    // apply function to matrix with index array in lock-step
    par_azip!((c in &mut distances, (i,j) in idx){*c = func(i,j)});
    return distances
}
</code>```

Title: Rust NdArray Distance Matrix

Body:
I am trying to write a a function that calculates distance matrices using ndarray:

extern crate ndarray;

use ndarray::{s, Array2, ArrayView1, indices_of, azip, array};
use ndarray::parallel::par_azip;
use std::f64;

type M = Array2<f64>;

fn main() {
    // make some arbitrary data
    let points = array!([0.,23.], [12., 13.], [15., 2.], [16., 145.], [42., 11.], [12., 12.], [11., 12.], [56., 18.], [34., 12.]);
    // calculate matrix
    let dist_arr = dist_to_mat(&points, &l2);
    println!("{}", dist_arr.mapv(|x| (100. * x).round() / 100.))
}

// as an example, use l2 distance
fn l2(x: &ArrayView1<f64>, y: &ArrayView1<f64>) -> f64 {
    let diff = x - y;
    let result = (&diff * &diff).sum();
    return result.sqrt()
}

pub fn dist_to_mat(
    points: &Array2<f64>,
    dist_fn: &dyn Fn(&ArrayView1<f64>, &ArrayView1<f64>) -> f64,
) -> M {
    // initialize array
    let mut distances = Array2::zeros((points.nrows(), points.nrows()));
    let idx = indices_of(&distances);
    // helper function to get the entries of points
    let func = |i: usize, j: usize| -> f64 {
        dist_fn(&points.slice(s![i, ..]), &points.slice(s![j, ..]))
    };
    // apply function to matrix with index array in lock-step
    par_azip!((c in &mut distances, (i,j) in idx){*c = func(i,j)}); // <- error here; works if par_azip is replaced with azip.
    return distances
}

While this works fine with the single-threaded azip, with par_azip I get the error:

`dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely

`dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely

help: within `[closure@<::ndarray::zip::zipmacro::azip macros>:23:6: 23:7 func:&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]]`, the trait `std::marker::Sync` is not implemented for `dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64`
note: required because it appears within the type `[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]`
note: required because it appears within the type `&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]`
note: required because it appears within the type `[closure@<::ndarray::zip::zipmacro::azip macros>:23:6: 23:7 func:&[closure@src/main.rs:27:16: 29:6 dist_fn:&&dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64, points:&&ndarray::ArrayBase<ndarray::OwnedRepr<f64>, ndarray::Dim<[usize; 2]>>]]`rustc(E0277)
<::ndarray::parallel::zipmacro::par_azip macros>(1, 50): `dyn for<'r, 's, 't0, 't1> std::ops::Fn(&'r ndarray::ArrayBase<ndarray::ViewRepr<&'s f64>, ndarray::Dim<[usize; 1]>>, &'t0 ndarray::ArrayBase<ndarray::ViewRepr<&'t1 f64>, ndarray::Dim<[usize; 1]>>) -> f64` cannot be shared between threads safely

Which object cannot be shared between threads safely: the return value of dist_fun or dist_fun? How do I fix this?

Body:
Fixed it. see <-

extern crate ndarray;

use ndarray::{s, Array2, ArrayView1, indices_of, azip, array};
use ndarray::parallel::par_azip;
use std::f64;

type M = Array2<f64>;

fn main() {
    // make some arbitrary data
    let points = array!([0.,23.], [12., 13.], [15., 2.], [16., 145.], [42., 11.], [12., 12.], [11., 12.], [56., 18.], [34., 12.]);
    // calculate matrix
    let dist_arr = dist_to_mat(&points, &l2);
    println!("{}", dist_arr.mapv(|x| (100. * x).round() / 100.))
}

// as an example, use l2 distance
fn l2(x: &ArrayView1<f64>, y: &ArrayView1<f64>) -> f64 {
    let diff = x - y;
    let result = (&diff * &diff).sum();
    return result.sqrt()
}

pub fn dist_to_mat(
    points: &Array2<f64>,
    dist_fn: &fn(&ArrayView1<f64>, &ArrayView1<f64>) -> f64, // <- different signature
) -> M {
    // initialize array
    let mut distances = Array2::zeros((points.nrows(), points.nrows()));
    let idx = indices_of(&distances);
    // helper function to get the entries of points
    let func = |i: usize, j: usize| -> f64 {
        dist_fn(&points.slice(s![i, ..]), &points.slice(s![j, ..]))
    };
    // apply function to matrix with index array in lock-step
    par_azip!((c in &mut distances, (i,j) in idx){*c = func(i,j)});
    return distances
}


问:
I am having trouble to make a Angular Http Request to my own Spring boot server
I am learning Front End with Angular and Back End with Spring Boot right now and I am having issues when I try to fetch data from the Back End.

Angular Code:

```<code>ngOnInit() {

    this.http.get('http://127.0.0.1:8081/products').toPromise().then((data) => {
      console.log(data);
    });
  }

</code>```

The Back End is working just fine, because I tried getting data with Postman and it works just fine.

Also copied the URL(http://127.0.0.1:8081/products) directly into my browser and it works just fine.

But when i try to request data from for example from JSONPlaceholder it works fine with the angular http get function.

```<code>ngOnInit() {

    this.http.get('http://jsonplaceholder.typicode.com/todos/1').toPromise().then((data) => {
      console.log(data);
    });
  }
</code>```

result of the JSONPlaceholder request:

```<code>{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}
</code>```

I hope this extra information helps you to help me.

Last but not least the error message I get:

答:
Thanks for all the help guys, and I found the answer for all the people having a similar problem.

So basically i forgot to add this annotation to the rest controller in the back end.

```<code>@CrossOrigin(origins = "*", maxAge = 3600)
</code>```

Body:
I am learning Front End with Angular and Back End with Spring Boot right now and I am having issues when I try to fetch data from the Back End.

Angular Code:

ngOnInit() {

    this.http.get('http://127.0.0.1:8081/products').toPromise().then((data) => {
      console.log(data);
    });
  }

The Back End is working just fine, because I tried getting data with Postman and it works just fine.

Also copied the URL(http://127.0.0.1:8081/products) directly into my browser and it works just fine.

But when i try to request data from for example from JSONPlaceholder it works fine with the angular http get function.

ngOnInit() {

    this.http.get('http://jsonplaceholder.typicode.com/todos/1').toPromise().then((data) => {
      console.log(data);
    });
  }

result of the JSONPlaceholder request:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

I hope this extra information helps you to help me.

Last but not least the error message I get:

Body:
Thanks for all the help guys, and I found the answer for all the people having a similar problem.

So basically i forgot to add this annotation to the rest controller in the back end.

@CrossOrigin(origins = "*", maxAge = 3600)


问:
AddStackExchangeRedisCache and heroku Redis connection strings
I'm trying to get my dotnet core application to connect to a Heroku Redis instance with Stack Exchange Redis Cache. So far I have:

```<code>services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = Configuration["REDIS_URL"].Replace("redis://","");
});
</code>```

The error I'm getting is:

```<code>StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s). UnableToConnect on
</code>```

How can I get the connection string so that StackExchange likes it?

答:
Got it:</p>

```<code>services.AddStackExchangeRedisCache(options =>
{
    var tokens = Configuration["REDIS_URL"].Split(':', '@');
    options.ConfigurationOptions = ConfigurationOptions.Parse(string.Format("{0}:{1},password={2}", tokens[3], tokens[4], tokens[2]));
});
</code>```

Body:
I'm trying to get my dotnet core application to connect to a Heroku Redis instance with Stack Exchange Redis Cache. So far I have:

services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = Configuration["REDIS_URL"].Replace("redis://","");
});

The error I'm getting is:

StackExchange.Redis.RedisConnectionException: It was not possible to connect to the redis server(s). UnableToConnect on

How can I get the connection string so that StackExchange likes it?

Body:
Got it:

services.AddStackExchangeRedisCache(options =>
{
    var tokens = Configuration["REDIS_URL"].Split(':', '@');
    options.ConfigurationOptions = ConfigurationOptions.Parse(string.Format("{0}:{1},password={2}", tokens[3], tokens[4], tokens[2]));
});


问:
TYPO3 Extbase - Paginate through a large table (100000 records)
I have a fairly large table with about 100000 records. If I don't set the limit in the repository

Repository:

```<code>public function paginateRequest() {

$query = $this->createQuery();
$result = $query->setLimit(1000)->execute();
//$result = $query->execute();
return $result;

}

/**
 * action list
 *
 * @return void
 */
public function listAction() {

$this->view->assign('records', $this->leiRepository->paginateRequest());

//$this->view->assign('records', $this->leiRepository->findAll());

}
</code>```

... the query and the page breaks although I'm using f:widget.paginate . As per the docs https://fluidtypo3.org/viewhelpers/fluid/master/Widget/PaginateViewHelper.html I was hoping that I can render only the itemsPerPage and 'parginate' through the records ...

List.hmtl

```<code><f:if condition="{records}">
<f:widget.paginate objects="{records}" as="paginatedRecords" configuration="{itemsPerPage: 100, insertAbove: 0, insertBelow: 1, maximumNumberOfLinks: 10}">
    <f:for each="{paginatedRecords}" as="record">
        <tr>
            <td><f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.name}</f:link.action></td>
            <td><f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.lei}</f:link.action></td>
        </tr>
    </f:for>
</f:widget.paginate>
</code>```

Model:

class Lei extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {

```<code>...
/**
 * abc
 *
 * @lazy
 * @var string
 */
protected $abc = '';
...
</code>```

答:
I use in TYPO3 9.5. The next function in repository:

```<code>public function paginated($page = 1, $size = 9){
    $query = $this->createQuery();
    $begin = ($page-1) * $size;
    $query->setOffset($begin);
    $query->setLimit($size);
    return $query->execute();
}
</code>```

And in the controller I am using arguments as parameter to send the page to load in a Rest action.

```<code>public function listRestAction()
{

    $arguments = $this->request->getArguments();
    $totalElements = $this->repository->total();
    $pages = ceil($totalElements/9);
    $next_page = '';
    $prev_page = '';
    #GET Page to load
    if($arguments['page'] AND $arguments['page'] != ''){
        $page_to_load = $arguments['page'];
    } else {
        $page_to_load = 1;
    }
    #Configuration of pagination
    if($page_to_load == $pages){
        $prev = $page_to_load - 1;
        $prev_page = "http://example.com/rest/news/page/$prev";
    } elseif($page_to_load == 1){
        $next = $page_to_load + 1;
        $next_page = "http://example.com/rest/news/page/$next";
    } else {
        $prev = $page_to_load - 1;
        $prev_page = "http://example.com/rest/news/page/$prev";
        $next = $page_to_load + 1;
        $next_page = "http://example.com/rest/news/page/$next";
    }

    $jsonPreparedElements = array();
    $jsonPreparedElements['info']['count'] = $totalElements;
    $jsonPreparedElements['info']['pages'] = $pages;
    $jsonPreparedElements['info']['next'] = $next_page;
    $jsonPreparedElements['info']['prev'] = $prev_page;
    $result = $this->repository->paginated($page_to_load);
    $collection_parsed_results = array();
    foreach ($result as $news) {
        array_push($collection_parsed_results, $news->parsedArray());
    }
    $jsonPreparedElements['results'] = $collection_parsed_results;
    $this->view->assign('value', $jsonPreparedElements);
}
</code>```

The result of this, is a JSON like this:

```<code>{
"info": {
    "count": 25,
    "pages": 3,
    "next": "",
    "prev": "http://example.com/rest/news/page/2"
},
"results": [
    { ....}
] }
</code>```

Body:
I have a fairly large table with about 100000 records. If I don't set the limit in the repository

Repository:

public function paginateRequest() {

$query = $this->createQuery();
$result = $query->setLimit(1000)->execute();
//$result = $query->execute();
return $result;

}

/**
 * action list
 *
 * @return void
 */
public function listAction() {

$this->view->assign('records', $this->leiRepository->paginateRequest());

//$this->view->assign('records', $this->leiRepository->findAll());

}

... the query and the page breaks although I'm using f:widget.paginate . As per the docs https://fluidtypo3.org/viewhelpers/fluid/master/Widget/PaginateViewHelper.html I was hoping that I can render only the itemsPerPage and 'parginate' through the records ...

List.hmtl

<f:if condition="{records}">
<f:widget.paginate objects="{records}" as="paginatedRecords" configuration="{itemsPerPage: 100, insertAbove: 0, insertBelow: 1, maximumNumberOfLinks: 10}">
    <f:for each="{paginatedRecords}" as="record">

            <f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.name}</f:link.action>
            <f:link.action action="show" pageUid="43" arguments="{record:record}"> {record.lei}</f:link.action>

    </f:for>
</f:widget.paginate>

Model:

class Lei extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {

...
/**
 * abc
 *
 * @lazy
 * @var string
 */
protected $abc = '';
...

Body:
I use in TYPO3 9.5. The next function in repository:

public function paginated($page = 1, $size = 9){
    $query = $this->createQuery();
    $begin = ($page-1) * $size;
    $query->setOffset($begin);
    $query->setLimit($size);
    return $query->execute();
}

And in the controller I am using arguments as parameter to send the page to load in a Rest action.

public function listRestAction()
{

    $arguments = $this->request->getArguments();
    $totalElements = $this->repository->total();
    $pages = ceil($totalElements/9);
    $next_page = '';
    $prev_page = '';
    #GET Page to load
    if($arguments['page'] AND $arguments['page'] != ''){
        $page_to_load = $arguments['page'];
    } else {
        $page_to_load = 1;
    }
    #Configuration of pagination
    if($page_to_load == $pages){
        $prev = $page_to_load - 1;
        $prev_page = "http://example.com/rest/news/page/$prev";
    } elseif($page_to_load == 1){
        $next = $page_to_load + 1;
        $next_page = "http://example.com/rest/news/page/$next";
    } else {
        $prev = $page_to_load - 1;
        $prev_page = "http://example.com/rest/news/page/$prev";
        $next = $page_to_load + 1;
        $next_page = "http://example.com/rest/news/page/$next";
    }

    $jsonPreparedElements = array();
    $jsonPreparedElements['info']['count'] = $totalElements;
    $jsonPreparedElements['info']['pages'] = $pages;
    $jsonPreparedElements['info']['next'] = $next_page;
    $jsonPreparedElements['info']['prev'] = $prev_page;
    $result = $this->repository->paginated($page_to_load);
    $collection_parsed_results = array();
    foreach ($result as $news) {
        array_push($collection_parsed_results, $news->parsedArray());
    }
    $jsonPreparedElements['results'] = $collection_parsed_results;
    $this->view->assign('value', $jsonPreparedElements);
}

The result of this, is a JSON like this:

{
"info": {
    "count": 25,
    "pages": 3,
    "next": "",
    "prev": "http://example.com/rest/news/page/2"
},
"results": [
    { ....}
] }


问:
Logstash Kafka input cannot connect
I am trying to build a pipeline based on this tutorial where Kafka reads from a file with a File Source connector. Using these Docker images for the Elastic Stack, I want to register Logstash as a consumer for the "quickstart-data" topic but I have failed for the moment.

Here is my logstash.conf file:

```<code>input {
  kafka {
    bootstrap_servers => 'localhost:9092'
    topics => 'quickstart-data'
  }
}

output {
  elasticsearch {
    hosts => [ 'elasticsearch']
    user => 'elastic'
    password => 'changeme'
  }
  stdout {}
}
</code>```

The connection to Elasticsearch works because I tested it with a heartbeat input.
The message error I get is the following:
Connection to node -1 could not be established. Broker may not be available.
Give up sending metadata request since no node is available

Any ideas?

答:
There may be a better way to do it but here how I correct the issue:

Change my Zookeeper & Kafka images to Confluent images

zookeeper:
    image: confluentinc/cp-zookeeper:latest
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    networks:
      - stack
  kafka:
    image: confluentinc/cp-kafka:latest
    ports:
      - "9092:9092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    depends_on:
      - zookeeper
    networks:
      - stack
```

<ol start="2">
<li>Logstash configuration (Please note that port is 2902):</li>
</ol>

<pre class="lang-yml prettyprint-override"><code>input {
    stdin{}
    kafka {
        id => "my_kafka_1"
        bootstrap_servers => "kafka:29092"
        topics => "test"
    }
}
</code>```

Title: Logstash Kafka input cannot connect

Body:
I am trying to build a pipeline based on this tutorial where Kafka reads from a file with a File Source connector. Using these Docker images for the Elastic Stack, I want to register Logstash as a consumer for the "quickstart-data" topic but I have failed for the moment.

Here is my logstash.conf file:

input {
  kafka {
    bootstrap_servers => 'localhost:9092'
    topics => 'quickstart-data'
  }
}

output {
  elasticsearch {
    hosts => [ 'elasticsearch']
    user => 'elastic'
    password => 'changeme'
  }
  stdout {}
}

The connection to Elasticsearch works because I tested it with a heartbeat input.
The message error I get is the following:
Connection to node -1 could not be established. Broker may not be available.
Give up sending metadata request since no node is available

Any ideas?

Body:
There may be a better way to do it but here how I correct the issue:

Change my Zookeeper & Kafka images to Confluent images

zookeeper:
    image: confluentinc/cp-zookeeper:latest
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000
    networks:
      - stack
  kafka:
    image: confluentinc/cp-kafka:latest
    ports:
      - "9092:9092"
    environment:
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
    depends_on:
      - zookeeper
    networks:
      - stack

Logstash configuration (Please note that port is 2902):

input {
    stdin{}
    kafka {
        id => "my_kafka_1"
        bootstrap_servers => "kafka:29092"
        topics => "test"
    }
}


问:
Runtime error "load of null pointer of type char" while using char** in C
I am having problems using this pointer to pointers to chars that represents an array of strings.

I should dereference it with some offset i to get the i-th string, then, dereference the result with some other offset j to get the j-th character of such string.

In my understanding, and assuming the indices are inbound, I could do that in several syntactic ways, so for example, to get the 6th character of the second string:

```<code>char* myFun(char** strs, int size){
    char a;
    int i=2,j=6;
    a=strs[i][j];
    a=*(strs[i]+j);
    a=(*strs+i)[j];
    a=*(*(strs+i)+j);
}
</code>```

However, I am getting a runtime error runtime error: load of null pointer of type 'char' on the line of the for loop on the following code, perhaps, the error is not the one that I suspect, but that is the reason I ask you for help.

```<code>char * myFn(char ** strs, int strsSize){
    if(*strs=NULL || strsSize==0){
        printf("empty first string, or empty array of strings\n");
        return NULL;
    }
    int i,pf_s=1;
    char * pf_str=(char*)calloc(pf_s,sizeof(char));
    for(i=0;*(strs[0]+i)!='\0';++i){//       <-------- runtime error
        if(!(i<pf_s-2)){
            pf_s=pf_s*2;
            pf_str=(char*)realloc(pf_str,2*pf_s*sizeof(char));
        }
        *(pf_str+i)=(*strs)[i];
    }
    pf_str[i]='\0';
    pf_str=(char*)realloc(pf_str,i+1*sizeof(char));
    printf("%s\n",pf_str);
    return pf_str;
}
</code>```

答:
In the second line of code, NULL is being assigned to *strs, instead of comparing *strs against NULL.

Change this:

```<code>if(*strs=NULL || strsSize==0){
</code>```

Into this:

```<code>if(*strs==NULL || strsSize==0){
</code>```

Body:
I am having problems using this pointer to pointers to chars that represents an array of strings.

I should dereference it with some offset i to get the i-th string, then, dereference the result with some other offset j to get the j-th character of such string.

In my understanding, and assuming the indices are inbound, I could do that in several syntactic ways, so for example, to get the 6th character of the second string:

char* myFun(char** strs, int size){
    char a;
    int i=2,j=6;
    a=strs[i][j];
    a=*(strs[i]+j);
    a=(*strs+i)[j];
    a=*(*(strs+i)+j);
}

However, I am getting a runtime error runtime error: load of null pointer of type 'char' on the line of the for loop on the following code, perhaps, the error is not the one that I suspect, but that is the reason I ask you for help.

char * myFn(char ** strs, int strsSize){
    if(*strs=NULL || strsSize==0){
        printf("empty first string, or empty array of strings\n");
        return NULL;
    }
    int i,pf_s=1;
    char * pf_str=(char*)calloc(pf_s,sizeof(char));
    for(i=0;*(strs[0]+i)!='\0';++i){//       <-------- runtime error
        if(!(i<pf_s-2)){
            pf_s=pf_s*2;
            pf_str=(char*)realloc(pf_str,2*pf_s*sizeof(char));
        }
        *(pf_str+i)=(*strs)[i];
    }
    pf_str[i]='\0';
    pf_str=(char*)realloc(pf_str,i+1*sizeof(char));
    printf("%s\n",pf_str);
    return pf_str;
}

Body:
In the second line of code, NULL is being assigned to *strs, instead of comparing *strs against NULL.

Change this:

if(*strs=NULL || strsSize==0){

Into this:

if(*strs==NULL || strsSize==0){


问:
ESLint - Override rules from eslint-plugin-prettier
I am using ESLint with the prettier plugin and configuration:

// eslintrc.js
extends: [
  `eslint:recommended`,
  `plugin:react/recommended`,
  `plugin:@typescript-eslint/recommended`,
  `plugin:prettier/recommended`,
  `prettier/react`,
  `prettier/@typescript-eslint`
]
```
<p>This works great, but I would like to disable a certain prettier rule, which is removing "unneeded" parentheses (removing them actually breaks my code):</p>
<pre class="lang-js prettyprint-override"><code>// Replace `(state.counter)` with `state.counter` eslint(prettier/prettier)
return <div>{(state.counter)}</div>
</code>```

As you can see from the message above, it doesn't state which rule exactly is causing this behavior and therefore I don't know which one to override.

I have tried to override all rules found in eslint-prettier-config, but nothing worked and I don't want to keep using // eslint-disable-next-line prettier/prettier.

答:
It is not currently possible to disable that specific rule from prettier through configuration, but to override rules in eslint that come from the extends block, you can either write in the rule like this:

"rules": {
  "prettier/prettier": "off"
  "@typescript-eslint/no-use-before-define": [
    "error",
    { "functions": false, "variables": true, "classes": true },
  ],
}
```

<p>Or to only override it for a specific file pattern you can override it in the <code>overrides</code> block.</p>

<pre class="lang-js prettyprint-override"><code>"overrides": [
  {
    "files": ["*.html"],
    "rules": {
      "prettier/prettier": "off",
      "@typescript-eslint/unbound-method": "off"
    }
  }
]
</code>```

Here I am showing both the config you were looking for, and an inherited rule from a nested package to show future visitors how to do it.

Body:
I am using ESLint with the prettier plugin and configuration:

// eslintrc.js
extends: [
  `eslint:recommended`,
  `plugin:react/recommended`,
  `plugin:@typescript-eslint/recommended`,
  `plugin:prettier/recommended`,
  `prettier/react`,
  `prettier/@typescript-eslint`
]

This works great, but I would like to disable a certain prettier rule, which is removing "unneeded" parentheses (removing them actually breaks my code):

// Replace `(state.counter)` with `state.counter` eslint(prettier/prettier)
return
{(state.counter)}

As you can see from the message above, it doesn't state which rule exactly is causing this behavior and therefore I don't know which one to override.

I have tried to override all rules found in eslint-prettier-config, but nothing worked and I don't want to keep using // eslint-disable-next-line prettier/prettier.

Body:
It is not currently possible to disable that specific rule from prettier through configuration, but to override rules in eslint that come from the extends block, you can either write in the rule like this:

"rules": {
  "prettier/prettier": "off"
  "@typescript-eslint/no-use-before-define": [
    "error",
    { "functions": false, "variables": true, "classes": true },
  ],
}

Or to only override it for a specific file pattern you can override it in the overrides block.

"overrides": [
  {
    "files": ["*.html"],
    "rules": {
      "prettier/prettier": "off",
      "@typescript-eslint/unbound-method": "off"
    }
  }
]

Here I am showing both the config you were looking for, and an inherited rule from a nested package to show future visitors how to do it.


问:
onchange function not running for some reason
I have a read-only textbox (sum) and whenever its value changes, I want a second read-only textbox (totalcost) to update its value.

Here's what I have, but for some reason it's not working. All of the references are correct, am I missing something basic?

```<code>jQuery(function($) {
  $('input[name="totalCPC"]').on('change', function() {
    var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
    var cpc = parseFloat($('input[id="sum"]').val());
    var noc = parseFloat($('input[id="numberofclickstextbox"]').val());
    $('#totalcost').val(function() {
      return ((noc * cpc) *pc).toFixed(2);
      });
  });
});
</code>```

答:
You need to trigger change event </p>

```<code>$('#totalcost').val(function() {
  return ((noc * cpc) *pc).toFixed(2);
}).trigger('change');
</code>```

Body:
I have a read-only textbox (sum) and whenever its value changes, I want a second read-only textbox (totalcost) to update its value.

Here's what I have, but for some reason it's not working. All of the references are correct, am I missing something basic?

jQuery(function($) {
  $('input[name="totalCPC"]').on('change', function() {
    var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
    var cpc = parseFloat($('input[id="sum"]').val());
    var noc = parseFloat($('input[id="numberofclickstextbox"]').val());
    $('#totalcost').val(function() {
      return ((noc * cpc) *pc).toFixed(2);
      });
  });
});

Body:
You need to trigger change event

$('#totalcost').val(function() {
  return ((noc * cpc) *pc).toFixed(2);
}).trigger('change');


问:
Openpyxl: use excel theme colors in chart
I'm trying to use Excel's theme colors in a chart created by openpyxl.  I want to have theme colors so that the entire workbook's colors can be updated when the user loads a new theme.

Openpyxl has functionality to color the series bars in a bar chart with rgb values as shown below.

```<code>import openpyxl
wb = openpyxl.load_workbook('myBook.xlsx')
ws = wb["chartSheet"]
chart = openpyxl.chart.BarChart()
chart.type = "col"
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)

chart.series[0].graphicalProperties.solidFill = 'FFFF66'

ws.add_chart(chart, "B2")
</code>```

For styling the fill color of a cell, there is an openpyxl.styles.colors.Color object that allows you to define colors in terms of a theme, like this: openpyxl.styles.colors.Color(theme=7)

However, the object that is used for bar chart styling is an openpyxl.drawing.colors object which only accepts rgb values.

It's definitely possible within the Excel application to style bars with a theme color.  Theoretically, I could use some post-production script to edit the raw xml of the excel file after being saved, but that would be pretty inefficient.

Is there any way to accomplish this within openpyxl?

答:
In openpyxl, it is actually called a "style", rather than a theme, when changing the chart as a whole.

Using the example provided here, I highlighted the modification of the <chartnumber>.style value.

from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference

wb = Workbook(write_only=True)
ws = wb.create_sheet()

rows = [
    ('Number', 'Batch 1', 'Batch 2'),
    (2, 10, 30),
    (3, 40, 60),
    (4, 50, 70),
    (5, 20, 10),
    (6, 10, 40),
    (7, 50, 30),
]

for row in rows:
    ws.append(row)

chart1 = BarChart()
chart1.type = "col"
chart1.style = 10 #Style Modification
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'

data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")

from copy import deepcopy

chart2 = deepcopy(chart1)
chart2.style = 11 #Style Modification
chart2.type = "bar"
chart2.title = "Horizontal Bar Chart"

ws.add_chart(chart2, "G10")

chart3 = deepcopy(chart1)
chart3.type = "col"
chart3.style = 12 #Style Modification
chart3.grouping = "stacked"
chart3.overlap = 100
chart3.title = 'Stacked Chart'

ws.add_chart(chart3, "A27")

chart4 = deepcopy(chart1)
chart4.type = "bar"
chart4.style = 13 #Style Modification
chart4.grouping = "percentStacked"
chart4.overlap = 100
chart4.title = 'Percent Stacked Chart'

ws.add_chart(chart4, "G27")

wb.save("bar.xlsx")
```

Output

Body:
I'm trying to use Excel's theme colors in a chart created by openpyxl.  I want to have theme colors so that the entire workbook's colors can be updated when the user loads a new theme.

Openpyxl has functionality to color the series bars in a bar chart with rgb values as shown below.

import openpyxl
wb = openpyxl.load_workbook('myBook.xlsx')
ws = wb["chartSheet"]
chart = openpyxl.chart.BarChart()
chart.type = "col"
data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)

chart.series[0].graphicalProperties.solidFill = 'FFFF66'

ws.add_chart(chart, "B2")

For styling the fill color of a cell, there is an openpyxl.styles.colors.Color object that allows you to define colors in terms of a theme, like this: openpyxl.styles.colors.Color(theme=7)

However, the object that is used for bar chart styling is an openpyxl.drawing.colors object which only accepts rgb values.

It's definitely possible within the Excel application to style bars with a theme color.  Theoretically, I could use some post-production script to edit the raw xml of the excel file after being saved, but that would be pretty inefficient.

Is there any way to accomplish this within openpyxl?

Body:
In openpyxl, it is actually called a "style", rather than a theme, when changing the chart as a whole.

Using the example provided here, I highlighted the modification of the <chartnumber>.style value.

from openpyxl import Workbook
from openpyxl.chart import BarChart, Series, Reference

wb = Workbook(write_only=True)
ws = wb.create_sheet()

rows = [
    ('Number', 'Batch 1', 'Batch 2'),
    (2, 10, 30),
    (3, 40, 60),
    (4, 50, 70),
    (5, 20, 10),
    (6, 10, 40),
    (7, 50, 30),
]

for row in rows:
    ws.append(row)

chart1 = BarChart()
chart1.type = "col"
chart1.style = 10 #Style Modification
chart1.title = "Bar Chart"
chart1.y_axis.title = 'Test number'
chart1.x_axis.title = 'Sample length (mm)'

data = Reference(ws, min_col=2, min_row=1, max_row=7, max_col=3)
cats = Reference(ws, min_col=1, min_row=2, max_row=7)
chart1.add_data(data, titles_from_data=True)
chart1.set_categories(cats)
chart1.shape = 4
ws.add_chart(chart1, "A10")

from copy import deepcopy

chart2 = deepcopy(chart1)
chart2.style = 11 #Style Modification
chart2.type = "bar"
chart2.title = "Horizontal Bar Chart"

ws.add_chart(chart2, "G10")

chart3 = deepcopy(chart1)
chart3.type = "col"
chart3.style = 12 #Style Modification
chart3.grouping = "stacked"
chart3.overlap = 100
chart3.title = 'Stacked Chart'

ws.add_chart(chart3, "A27")

chart4 = deepcopy(chart1)
chart4.type = "bar"
chart4.style = 13 #Style Modification
chart4.grouping = "percentStacked"
chart4.overlap = 100
chart4.title = 'Percent Stacked Chart'

ws.add_chart(chart4, "G27")

wb.save("bar.xlsx")

Output