问:
Push event not firing on send notification from server
I want to push notification from my server.for that i am using web push API for java , i am able to send the notification to endpoint url but on receiver side my service worker not executing push event,As I am using VAPID so no need to use gcm Id as per my understanding,here you are my service worker file.

```<code>'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
  outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
self.addEventListener('install', function(event){
 event.waitUntil(self.skipWaiting());
 console.log("activate");
});

self.addEventListener('activate', function(event){
event.waitUntil(self.clients.claim());
 console.log("install");
});

self.addEventListener('push', function(event) {
  console.log('Received push');
  let notificationTitle = 'Hello';
  const notificationOptions = {
    body: 'Thanks for sending this push msg.',
    icon: '/JMS/resources/images/icon.png',
    badge: '/JMS/resources/images/badge.png',
    tag: 'simple-push-demo-notification',
    data: {
      url: 'https://developers.google.com/web/fundamentals/getting-
      started/push-notifications/',
    },
  };

  if (event.data) {
    const dataText = event.data.text();
    notificationTitle = 'Received Payload';
    notificationOptions.body = `Push data: '${dataText}'`;
  }

    event.waitUntil(
    Promise.all([
      self.registration.showNotification(
        notificationTitle, notificationOptions),
    ])
  );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(
            clients.openWindow('https://www.auctiontiger.net')
          );
  let clickResponsePromise = Promise.resolve();
  if (event.notification.data && event.notification.data.url) {
    clickResponsePromise = clients.openWindow(event.notification.data.url);
  }

  event.waitUntil(
    Promise.all([
      clickResponsePromise
    ])
  );
});
</code>```

here you are my main.js file from where i am able to call to my local server.

```<code>'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}

function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}

    if (isSubscribed) {
     pushButton.textContent = 'Disable Push Messaging';
     } else {
     pushButton.textContent = 'Enable Push Messaging';
     }

     pushButton.disabled = false;
    }

  function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');

if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
subscriptionDetails.classList.remove('is-invisible');
 } else {
 subscriptionDetails.classList.add('is-invisible');
 }
 }

function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:applicationServerKey

  })
 .then(function(subscription) {
  updateSubscriptionOnServer(subscription);
  isSubscribed = true;
  updateBtn();
  initialiseUI();
  return sendSubscriptionToServer(subscription);
  })
   .catch(function(err) {
   console.log('Failed to subscribe the user: ', err);

   });
   }
function sendSubscriptionToServer(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
var auth = subscription.getKey ? subscription.getKey('auth') : '';

return fetch('/JMS/profile/subscription', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        endpoint: subscription.endpoint,
        // Take byte[] and turn it into a base64 encoded string suitable for
        // POSTing to a server over HTTP
        key:key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key)))
        : '',
        auth:auth ? btoa(String.fromCharCode.apply(null, new
        Uint8Array(auth))) : ''
    })
    });

     }

   function unsubscribeUser() {
   swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
   if (subscription) {
    return subscription.unsubscribe();
   }
   })
  .catch(function(error) {
  console.log('Error unsubscribing', error);
   })
  .then(function() {
  updateSubscriptionOnServer(null);

  console.log('User is unsubscribed.');
  isSubscribed = false;

  updateBtn();
  });
  }

   function initialiseUI() {
   pushButton.addEventListener('click', function() {
   pushButton.disabled = true;
   if (isSubscribed) {
    unsubscribeUser();
   } else {
  subscribeUser();
    }
    });

   // Set the initial subscription value
    swRegistration.pushManager.getSubscription()
    .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

      if (isSubscribed) {

        console.log('User IS subscribed.');
      } else {
     console.log('User is NOT subscribed.');
      }

       updateBtn();
      });
      }

    if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker and Push is supported');

    navigator.serviceWorker.register('sw.js')
    .then(function(swReg) {
    console.log('Service Worker is registered', swReg.scope);
    swReg.update();
    swRegistration = swReg;
    initialiseUI();
    })
    .catch(function(error) {
    console.error('Service Worker Error', error);
    });
    } else {
    console.warn('Push messaging is not supported');
    pushButton.textContent = 'Push Not Supported';
    }
</code>```

here is the URL for webpush API that i have used for my application,
[https://github.com/web-push-libs/webpush-java][1]
finally my server side code,

```<code>@RequestMapping(value = "profile/subscription", method = RequestMethod.POST,
headers = "Content-Type=application/json")
@ResponseBody
public String post(@RequestBody String body,byte[]
    payload,HttpServletResponse response)
            throws GeneralSecurityException, IOException, JoseException,
    ExecutionException, InterruptedException, ParseException, JSONException
    {
    String data="";
    org.json.JSONObject ob = new org.json.JSONObject(body);
    final int TTL = 255;
    payload= "hello".getBytes();
    com.demo.controller.PushService pushService = new
    com.demo.controller.PushService();
    nl.martijndwars.webpush.Notification notification =new
    nl.martijndwars.webpush.Notification(ob.getString("endpoint")
   ,new Subscription().getUserPublicKey((ob.getString("key"))),
    Base64.decode(ob.getString("auth")),
    payload,TTL);
    pushService.send(notification);
    org.json.JSONObject ob2 = new org.json.JSONObject(body);
    ob2.put("data", notification.getPayload());
    JSONArray arr= new JSONArray();
    arr.add(ob2);
    data=arr.toJSONString();
    response.setHeader("Service-Worker-Allowed", "/");
    return data;
   }
</code>```

actually I am fetching this from client browser and on server-side sending notification on the endpoint, and i am able to send the notification but my
service worker is not able to fire push event so i am not getting notification on my browser.

```<code>  {
  auth:"hcQQq+1FeDuSu7V0zd5DXA=="
  endpoint:"https://fcm.googleapis.com/fcm/send/
  cXgp0l3svNo:APA91bG8dDfZhrc0iaSyzvuV1BvnxXz9T-
  SmLCKOymKrEdwvrh0_SjzjnU3ORRKvW5QD-
  Zp196T5nAGPayR7EKu_Bkb0pQrSex7Q3DZSu54Lo83AEiUE6p-2Xn-nrquCymKVFt6Z4nY8"
  key:"BJv2qC3WSCsRszMi57vOBpFjnIpdJ/
  uXQQFj4d0XZD9lRuZKuBgJNVFra0SFEvRlQQ88eG8RWWs7sSvO9Pbdkwk="
  }
</code>```

Please help me to get out of this, any help would be greatly appreciated.Thank you in advance.

答: The issue might be due to some firewall blocking you from receiving the push notification. This was the case with me.</p>

Body:
I want to push notification from my server.for that i am using web push API for java , i am able to send the notification to endpoint url but on receiver side my service worker not executing push event,As I am using VAPID so no need to use gcm Id as per my understanding,here you are my service worker file.

'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
  outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
self.addEventListener('install', function(event){
 event.waitUntil(self.skipWaiting());
 console.log("activate");
});

self.addEventListener('activate', function(event){
event.waitUntil(self.clients.claim());
 console.log("install");
});

self.addEventListener('push', function(event) {
  console.log('Received push');
  let notificationTitle = 'Hello';
  const notificationOptions = {
    body: 'Thanks for sending this push msg.',
    icon: '/JMS/resources/images/icon.png',
    badge: '/JMS/resources/images/badge.png',
    tag: 'simple-push-demo-notification',
    data: {
      url: 'https://developers.google.com/web/fundamentals/getting-
      started/push-notifications/',
    },
  };

  if (event.data) {
    const dataText = event.data.text();
    notificationTitle = 'Received Payload';
    notificationOptions.body = `Push data: '${dataText}'`;
  }

    event.waitUntil(
    Promise.all([
      self.registration.showNotification(
        notificationTitle, notificationOptions),
    ])
  );
});

self.addEventListener('notificationclick', function(event) {
    event.notification.close();
    event.waitUntil(
            clients.openWindow('https://www.auctiontiger.net')
          );
  let clickResponsePromise = Promise.resolve();
  if (event.notification.data && event.notification.data.url) {
    clickResponsePromise = clients.openWindow(event.notification.data.url);
  }

  event.waitUntil(
    Promise.all([
      clickResponsePromise
    ])
  );
});

here you are my main.js file from where i am able to call to my local server.

'use strict';

const applicationServerPublicKey = 'BEl62iUYgUivxIkv69yViEuiBIa-Ib9-
SkvMeAtA3LFgDzkrxZJjSgSnfckjBJuBkr3qBUYIHBQFLXYp5Nksh8U';
const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}

function updateBtn() {
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}

    if (isSubscribed) {
     pushButton.textContent = 'Disable Push Messaging';
     } else {
     pushButton.textContent = 'Enable Push Messaging';
     }

     pushButton.disabled = false;
    }

  function updateSubscriptionOnServer(subscription) {
  // TODO: Send subscription to application server

const subscriptionJson = document.querySelector('.js-subscription-json');
const subscriptionDetails =
document.querySelector('.js-subscription-details');

if (subscription) {
subscriptionJson.textContent = JSON.stringify(subscription);
subscriptionDetails.classList.remove('is-invisible');
 } else {
 subscriptionDetails.classList.add('is-invisible');
 }
 }

function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey:applicationServerKey

  })
 .then(function(subscription) {
  updateSubscriptionOnServer(subscription);
  isSubscribed = true;
  updateBtn();
  initialiseUI();
  return sendSubscriptionToServer(subscription);
  })
   .catch(function(err) {
   console.log('Failed to subscribe the user: ', err);

   });
   }
function sendSubscriptionToServer(subscription) {
var key = subscription.getKey ? subscription.getKey('p256dh') : '';
var auth = subscription.getKey ? subscription.getKey('auth') : '';

return fetch('/JMS/profile/subscription', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        endpoint: subscription.endpoint,
        // Take byte[] and turn it into a base64 encoded string suitable for
        // POSTing to a server over HTTP
        key:key ? btoa(String.fromCharCode.apply(null, new Uint8Array(key)))
        : '',
        auth:auth ? btoa(String.fromCharCode.apply(null, new
        Uint8Array(auth))) : ''
    })
    });

     }

   function unsubscribeUser() {
   swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
   if (subscription) {
    return subscription.unsubscribe();
   }
   })
  .catch(function(error) {
  console.log('Error unsubscribing', error);
   })
  .then(function() {
  updateSubscriptionOnServer(null);

  console.log('User is unsubscribed.');
  isSubscribed = false;

  updateBtn();
  });
  }

   function initialiseUI() {
   pushButton.addEventListener('click', function() {
   pushButton.disabled = true;
   if (isSubscribed) {
    unsubscribeUser();
   } else {
  subscribeUser();
    }
    });

   // Set the initial subscription value
    swRegistration.pushManager.getSubscription()
    .then(function(subscription) {
    isSubscribed = !(subscription === null);

    updateSubscriptionOnServer(subscription);

      if (isSubscribed) {

        console.log('User IS subscribed.');
      } else {
     console.log('User is NOT subscribed.');
      }

       updateBtn();
      });
      }

    if ('serviceWorker' in navigator && 'PushManager' in window) {
    console.log('Service Worker and Push is supported');

    navigator.serviceWorker.register('sw.js')
    .then(function(swReg) {
    console.log('Service Worker is registered', swReg.scope);
    swReg.update();
    swRegistration = swReg;
    initialiseUI();
    })
    .catch(function(error) {
    console.error('Service Worker Error', error);
    });
    } else {
    console.warn('Push messaging is not supported');
    pushButton.textContent = 'Push Not Supported';
    }

here is the URL for webpush API that i have used for my application,
[https://github.com/web-push-libs/webpush-java][1]
finally my server side code,

@RequestMapping(value = "profile/subscription", method = RequestMethod.POST,
headers = "Content-Type=application/json")
@ResponseBody
public String post(@RequestBody String body,byte[]
    payload,HttpServletResponse response)
            throws GeneralSecurityException, IOException, JoseException,
    ExecutionException, InterruptedException, ParseException, JSONException
    {
    String data="";
    org.json.JSONObject ob = new org.json.JSONObject(body);
    final int TTL = 255;
    payload= "hello".getBytes();
    com.demo.controller.PushService pushService = new
    com.demo.controller.PushService();
    nl.martijndwars.webpush.Notification notification =new
    nl.martijndwars.webpush.Notification(ob.getString("endpoint")
   ,new Subscription().getUserPublicKey((ob.getString("key"))),
    Base64.decode(ob.getString("auth")),
    payload,TTL);
    pushService.send(notification);
    org.json.JSONObject ob2 = new org.json.JSONObject(body);
    ob2.put("data", notification.getPayload());
    JSONArray arr= new JSONArray();
    arr.add(ob2);
    data=arr.toJSONString();
    response.setHeader("Service-Worker-Allowed", "/");
    return data;
   }

actually I am fetching this from client browser and on server-side sending notification on the endpoint, and i am able to send the notification but my
service worker is not able to fire push event so i am not getting notification on my browser.

  {
  auth:"hcQQq+1FeDuSu7V0zd5DXA=="
  endpoint:"https://fcm.googleapis.com/fcm/send/
  cXgp0l3svNo:APA91bG8dDfZhrc0iaSyzvuV1BvnxXz9T-
  SmLCKOymKrEdwvrh0_SjzjnU3ORRKvW5QD-
  Zp196T5nAGPayR7EKu_Bkb0pQrSex7Q3DZSu54Lo83AEiUE6p-2Xn-nrquCymKVFt6Z4nY8"
  key:"BJv2qC3WSCsRszMi57vOBpFjnIpdJ/
  uXQQFj4d0XZD9lRuZKuBgJNVFra0SFEvRlQQ88eG8RWWs7sSvO9Pbdkwk="
  }

Please help me to get out of this, any help would be greatly appreciated.Thank you in advance.


来源: stackexchange

问:
winforms how to paint (fillRectangle) a single cell in TableLayoutPanel?
hi
in winforms how to paint (fillRectangle) a single cell in TableLayoutPanel ?
without using other panels please.</p>

答:
You have to subscribe to the CellPaint event.
As an example:</p>

```<code>    private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        if (e.Row == 0 && e.Column == 1)
        {
            e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You have to subscribe to the CellPaint event.
As an example:

    private void tableLayoutPanel_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        if (e.Row == 0 && e.Column == 1)
        {
            e.Graphics.FillRectangle(new SolidBrush(Color.Black), e.CellBounds);
        }
    }


问:
docker build with pip install overwrites existing packages
This is my Dockerfile:

```<code>FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /
</code>```

docker_with_pre_installed_packages has:

```<code>/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging
</code>```

requirements.txt:

```<code>my_package.redis-db
my_package.common.utils
</code>```

after running

```<code>docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common
</code>```

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

```<code>ImportError: No module named my_package.config
</code>```

Thanks!

答:
The problem was with the jenkins slave running this build.
I tried to run it on a new one and all got fixed</p>

ContentLicense: CC BY-SA 4.0

Body:
This is my Dockerfile:

FROM docker_with_pre_installed_packages:1.0
ADD requirements.txt .
RUN pip install -r requirements.txt
ADD app app
WORKDIR /

docker_with_pre_installed_packages has:

/usr/local/lib/python2.7/site-packages/my_packages/db
/usr/local/lib/python2.7/site-packages/my_packages/config
/usr/local/lib/python2.7/site-packages/my_packages/logging

requirements.txt:

my_package.redis-db
my_package.common.utils

after running

docker build -t test:1.0 .
docker run -it test:1.0 bash
cd /usr/local/lib/python2.7/site-packages/my_packages/
ls
__init__.py redis_db common

pip freeze still shows the old packages
and I can still see the dist-info directory
but when trying to run python and import something from the pre installed packages I getting:

ImportError: No module named my_package.config

Thanks!


问:
change (lack of) user input to default string value
This is probably a straight forward question but I don't have the Python fundamentals down yet (running before walking)

I want user inputs for the following (coordinate) variables:

source_x = input('enter blast x: ')
source_y = input('enter blast y: ')
source_z = input('enter blast z: ')
receiver_x = input('enter receiver x: ')
receiver_y = input('enter receiver y: ')
receiver_z = input('enter receiver z: ')
```

<p>When the user input is <kbd>Enter</kbd> for the <code>z</code> coordinate (or any other), the following error arises:</p>

<pre class="lang-py prettyprint-override"><code>    source_z = float(source_z)
ValueError: could not convert string to float: ''
</code>```

I understand the error, the Enter input was seen as a string, but is there a quick way to identify and convert the Enter input to (e.g.) a 0?

Just in case I want to undertake bulk imports and not stop my calculations further down the code.

kind regards

答:
The solution is to check the input value to see if it is composed of digits and then cast it to the desired type or assign a default value else:

import re

is_number = re.compile(r'^[-+]?[0-9]*\.?[0-9]+$')

src_x = input('enter blast x: ')
src_y = input('enter blast y: ')
src_z = input('enter blast z: ')

rcv_x = input('enter receiver x: ')
rcv_y = input('enter receiver y: ')
rcv_z = input('enter receiver z: ')

src_x = float(src_x) if is_number.match(src_x) else 0
src_y = float(src_y) if is_number.match(src_y) else 0
src_z = float(src_z) if is_number.match(src_z) else 0

rcv_x = float(rcv_x) if is_number.match(rcv_x) else 0
rcv_y = float(rcv_y) if is_number.match(rcv_y) else 0
rcv_z = float(rcv_z) if is_number.match(rcv_z) else 0
```

Body:
This is probably a straight forward question but I don't have the Python fundamentals down yet (running before walking)

I want user inputs for the following (coordinate) variables:

source_x = input('enter blast x: ')
source_y = input('enter blast y: ')
source_z = input('enter blast z: ')
receiver_x = input('enter receiver x: ')
receiver_y = input('enter receiver y: ')
receiver_z = input('enter receiver z: ')

When the user input is Enter for the z coordinate (or any other), the following error arises:

    source_z = float(source_z)
ValueError: could not convert string to float: ''

I understand the error, the Enter input was seen as a string, but is there a quick way to identify and convert the Enter input to (e.g.) a 0?

Just in case I want to undertake bulk imports and not stop my calculations further down the code.

kind regards


问:
jQuery not recognizing Symfony JSON?
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

```<code>$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));
</code>```

The above works fine and hits the partial. All that is in my partial is this:

```<code><?php echo $jsonSlots ?>
</code>```

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

```<code>$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});
</code>```

Any ideas why I can't get to the alert?

答:
you need is to amend your partial

```<code><?php $sf_data->getRaw('jsonSlots'); ?>
</code>```

or use a simpler way from the actions

```<code>$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
$this->renderText(json_encode($this->jsonQuery));
</code>```

Title: jQuery not recognizing Symfony JSON?

Body:
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:

$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));

The above works fine and hits the partial. All that is in my partial is this:

<?php echo $jsonSlots ?>

Now according to Firebug this gets populated properly. Below is a copy of the response

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:

[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]

I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag

$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
    alert(data);
});

Any ideas why I can't get to the alert?

Body:
you need is to amend your partial

<?php $sf_data->getRaw('jsonSlots'); ?>

or use a simpler way from the actions

$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
$this->renderText(json_encode($this->jsonQuery));


问:
Autodesk forge Markups Core
I have a markup extension in Autodesk Forge Viewer for 3D models. I have problems removing only one markup. I want to know if it is possible to show annotations in edit mode or delete markups in show mode. When I try to show markups in editing mode, I see a warning that "markups cant be showed in editing mode."
Does anyone know how to solve this problem?</p>

答:
Edit

And to remove a specific markup from a layer after they are loaded try:

```<code>markExt.svgLayersMap['layerId'].markups[index].destroy()
</code>```

Leave the editmode before showing markups - (in response to user input) you can programmatically re-enter editmode once the markups are shown:

```<code>ext.leaveEditMode()
ext.loadMarkups(asb,'233') //or ext.showMarkups(layerID)
ext.enterEditMode()
</code>```

And to remove markups try:

```<code>ext.markups[0].destroy()
</code>```

show annotations in edit mode

Not exactly sure what you are trying to achieve here? But you can create text markup programmatically - say for exp:

```<code>const styleObject = Autodesk.Viewing.Extensions.Markups.Core.Utils.createStyle(['font-size'], window.ext);
 styleObject['font-size'] = 100;
 (new Autodesk.Viewing.Extensions.Markups.Core.CreateText(window.ext, 2333, {x:20,y:20}, {x:100,y:100},'233', styleObject)).execute()
</code>```

or delete markups in show mode.
  And in show mode if the markups are loaded you will need to hide on their layer level and wouldn't be able to hide a specific markup - you may fine tune this by separating them to different layers

Title: Autodesk forge Markups Core

Body:
Edit

And to remove a specific markup from a layer after they are loaded try:

markExt.svgLayersMap['layerId'].markups[index].destroy()

Leave the editmode before showing markups - (in response to user input) you can programmatically re-enter editmode once the markups are shown:

ext.leaveEditMode()
ext.loadMarkups(asb,'233') //or ext.showMarkups(layerID)
ext.enterEditMode()

And to remove markups try:

ext.markups[0].destroy()

show annotations in edit mode

Not exactly sure what you are trying to achieve here? But you can create text markup programmatically - say for exp:

const styleObject = Autodesk.Viewing.Extensions.Markups.Core.Utils.createStyle(['font-size'], window.ext);
 styleObject['font-size'] = 100;
 (new Autodesk.Viewing.Extensions.Markups.Core.CreateText(window.ext, 2333, {x:20,y:20}, {x:100,y:100},'233', styleObject)).execute()

or delete markups in show mode.
  And in show mode if the markups are loaded you will need to hide on their layer level and wouldn't be able to hide a specific markup - you may fine tune this by separating them to different layers


问:
Force the source url to download automatically by adding the url headers
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

```<code>header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
</code>```

答:
A simple solution from the front end.

If the front end has a href and triggers it, this code will work for sure.

I tested in PHP itself, here is the code.

```<code>$url = 'http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf';
echo '<a download href="'. $url .'" target="_blank">click</a>';
</code>```

Incase the front end is redirecting the url instead of trigger, have to find out the solution.

Body:
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);

Body:
A simple solution from the front end.

If the front end has a href and triggers it, this code will work for sure.

I tested in PHP itself, here is the code.

$url = 'http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf';
echo '<a download href="'. $url .'" target="_blank">click</a>';

Incase the front end is redirecting the url instead of trigger, have to find out the solution.


问:
Spring Boot OAuth2 Security properties names in .properties files?
I'm currently learning and experimenting with the different Spring Boot Security OAuth2 packages and I'm really confused with the actual configuration properties names. I found on the internet and on multiple Spring Documentation pages different naming schemes for these properties. For example I found

```<code>security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri
spring.security.oauth2.resource.token-info-uri=xxx
spring.security.oauth2.resourceserver ...
...
</code>```

I'm trying to make sense of all this and would like to know what are the differences with all of them. Are they version related, package related, are they typos, are some names deprecated, ... ?

Regards

P.S. I'm currently using Spring Boot 2.2.4

答:
Spring Security OAuth & Spring Security

The Spring Security OAuth project is deprecated. The latest OAuth 2.0
  support is provided by Spring Security

The property entries starting with

```<code>security.oauth2.*
</code>```

are part of the deprecated Spring Security OAuth ( example ) and the properties starting with

```<code> spring.security.oauth2.*
</code>```

are part of the Spring Security ( The official documentation of current spring boot Security Properties )

Additional References

Spring Security OAuth 2.0 Roadmap Update

OAuth 2.0 Migration Guide

OAuth 2.0 Features Matrix

Body:
I'm currently learning and experimenting with the different Spring Boot Security OAuth2 packages and I'm really confused with the actual configuration properties names. I found on the internet and on multiple Spring Documentation pages different naming schemes for these properties. For example I found

security.oauth2.resource.token-info-uri=xxx
security.oauth2.client.resource.tokenInfoUri
spring.security.oauth2.resource.token-info-uri=xxx
spring.security.oauth2.resourceserver ...
...

I'm trying to make sense of all this and would like to know what are the differences with all of them. Are they version related, package related, are they typos, are some names deprecated, ... ?

Regards

P.S. I'm currently using Spring Boot 2.2.4

Body:
Spring Security OAuth & Spring Security

The Spring Security OAuth project is deprecated. The latest OAuth 2.0
  support is provided by Spring Security

The property entries starting with

security.oauth2.*

are part of the deprecated Spring Security OAuth ( example ) and the properties starting with

 spring.security.oauth2.*

are part of the Spring Security ( The official documentation of current spring boot Security Properties )

Additional References

Spring Security OAuth 2.0 Roadmap Update

OAuth 2.0 Migration Guide

OAuth 2.0 Features Matrix


问:
COPY command skipping files in snowflake
COPY command skipping files while loading data from an s3 bucket in snowflake. Is there anyway I can get to know the number of files that were processed from the entire list of files. My command looks something like below:</p>

```<code>   COPY INTO abcd.abcdefhg
   FROM 's3://dfsdc/asdfa/dfasdaf/sdfasd/'
   credentials = (AWS_KEY_ID = '********************' AWS_SECRET_KEY =
   '************')
   FILE_FORMAT = (
   COMPRESSION = 'GZIP'
   FIELD_DELIMITER = '|' RECORD_DELIMITER = '\n'
   SKIP_HEADER = 0
   FIELD_OPTIONALLY_ENCLOSED_BY = '"'
   TRIM_SPACE = FALSE
   ERROR_ON_COLUMN_COUNT_MISMATCH = TRUE
   ESCAPE = '\134'
   -- ESCAPE_UNENCLOSED_FIELD = 'NONE'
   ESCAPE_UNENCLOSED_FIELD=NONE
   DATE_FORMAT = 'AUTO' TIMESTAMP_FORMAT = 'AUTO'
   NULL_IF = ('')
    )
   ON_ERROR = CONTINUE;
</code>```

答:
If the file already loaded into target table that file won't be processed again until you use option force = true, Also you can validate the load status of the using metadata view available under each database.

After completion of copy command you will get load status of each file in result panel.

Body:
COPY command skipping files while loading data from an s3 bucket in snowflake. Is there anyway I can get to know the number of files that were processed from the entire list of files. My command looks something like below:

   COPY INTO abcd.abcdefhg
   FROM 's3://dfsdc/asdfa/dfasdaf/sdfasd/'
   credentials = (AWS_KEY_ID = '********************' AWS_SECRET_KEY =
   '************')
   FILE_FORMAT = (
   COMPRESSION = 'GZIP'
   FIELD_DELIMITER = '|' RECORD_DELIMITER = '\n'
   SKIP_HEADER = 0
   FIELD_OPTIONALLY_ENCLOSED_BY = '"'
   TRIM_SPACE = FALSE
   ERROR_ON_COLUMN_COUNT_MISMATCH = TRUE
   ESCAPE = '\134'
   -- ESCAPE_UNENCLOSED_FIELD = 'NONE'
   ESCAPE_UNENCLOSED_FIELD=NONE
   DATE_FORMAT = 'AUTO' TIMESTAMP_FORMAT = 'AUTO'
   NULL_IF = ('')
    )
   ON_ERROR = CONTINUE;


问:
CodeIgniter URL rewrite with Nginx
I'm trying to migrate a site under CodeIgniter from Apache to Nginx. My first tests show very good performances, so it worst the try.

But I can't find the correct Nginx configuration to replace those RewriteRules :

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

I found this recipe on Nginx website https://www.nginx.com/resources/wiki/start/topics/recipes/codeigniter/

```<code>location / {
        try_files $uri $uri/ /index.php;
}
</code>```

It works in most cases, except when I have a trailing slash. Meaning
 http://example.com/controller/param/

will call http://example.com/controller/function/index.php (and return a 404)

instead of http://example.com/index.php/controller/function/ ...as it usually do with Apache rewrite.

I tried to add a rewrite :

```<code>rewrite ^/(.*)/$ /$1 permanent;
</code>```

But it redirect POST to GET, so I loose all my post data...

Any clue ?

Thanks

答:
Check if this helps. Replace both occurrences of <source_directory>; with your correct value:

```<code>    server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         <source_directory>;
    rewrite_log  on;
    index index.html index.php;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    if ($host ~* ^www\.(.*))
    {
        set $host_without_www $1;
        rewrite ^/(.*)$ $scheme://$host_without_www/$1 permanent;
    }

    # canonicalize codeigniter url end points
    # if your default controller is something other than "welcome" you should change the following
    if ($request_uri ~* ^(/welcome(/index)?|/index(.php)?)/?$)
    {
        rewrite ^(.*)$ / permanent;
    }

    # removes trailing "index" from all controllers
    if ($request_uri ~* index/?$)
    {
        rewrite ^/(.*)/index/?$ /$1 permanent;
    }

    # removes trailing slashes (prevents SEO duplicate content issues)
    if (!-d $request_filename)
    {
        rewrite ^/(.+)/$ /$1 permanent;
    }

    # removes access to "system" folder, also allows a "System.php" controller
    if ($request_uri ~* ^/system)
    {
        rewrite ^/(.*)$ /index.php?/$1 last;
        break;
    }

    # unless the request is for a valid file (image, js, css, etc.), send to bootstrap
    if (!-e $request_filename)
    {
        rewrite ^/(.*)$ /index.php?/$1 last;
        break;
    }

    # use fastcgi for all php files
    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME <source_directory>$fastcgi_script_name;
        include fastcgi_params;
    }

    # deny access to apache .htaccess files
    location ~ /\.htaccess
    {
        deny all;
    }

    error_page 404 /404.html;
    location = /40x.html
    {
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html
    {
    }
}
</code>```

Title: CodeIgniter URL rewrite with Nginx

Body:
I'm trying to migrate a site under CodeIgniter from Apache to Nginx. My first tests show very good performances, so it worst the try.

But I can't find the correct Nginx configuration to replace those RewriteRules :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

I found this recipe on Nginx website https://www.nginx.com/resources/wiki/start/topics/recipes/codeigniter/

location / {
        try_files $uri $uri/ /index.php;
}

It works in most cases, except when I have a trailing slash. Meaning
 http://example.com/controller/param/

will call http://example.com/controller/function/index.php (and return a 404)

instead of http://example.com/index.php/controller/function/ ...as it usually do with Apache rewrite.

I tried to add a rewrite :

rewrite ^/(.*)/$ /$1 permanent;

But it redirect POST to GET, so I loose all my post data...

Any clue ?

Thanks

Body:
Check if this helps. Replace both occurrences of <source_directory>; with your correct value:

    server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  _;
    root         <source_directory>;
    rewrite_log  on;
    index index.html index.php;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    if ($host ~* ^www\.(.*))
    {
        set $host_without_www $1;
        rewrite ^/(.*)$ $scheme://$host_without_www/$1 permanent;
    }

    # canonicalize codeigniter url end points
    # if your default controller is something other than "welcome" you should change the following
    if ($request_uri ~* ^(/welcome(/index)?|/index(.php)?)/?$)
    {
        rewrite ^(.*)$ / permanent;
    }

    # removes trailing "index" from all controllers
    if ($request_uri ~* index/?$)
    {
        rewrite ^/(.*)/index/?$ /$1 permanent;
    }

    # removes trailing slashes (prevents SEO duplicate content issues)
    if (!-d $request_filename)
    {
        rewrite ^/(.+)/$ /$1 permanent;
    }

    # removes access to "system" folder, also allows a "System.php" controller
    if ($request_uri ~* ^/system)
    {
        rewrite ^/(.*)$ /index.php?/$1 last;
        break;
    }

    # unless the request is for a valid file (image, js, css, etc.), send to bootstrap
    if (!-e $request_filename)
    {
        rewrite ^/(.*)$ /index.php?/$1 last;
        break;
    }

    # use fastcgi for all php files
    location ~ \.php$
    {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME <source_directory>$fastcgi_script_name;
        include fastcgi_params;
    }

    # deny access to apache .htaccess files
    location ~ /\.htaccess
    {
        deny all;
    }

    error_page 404 /404.html;
    location = /40x.html
    {
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html
    {
    }
}


问:
How to check checkbox array values exist from database PHP Laravel?
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

```<code>public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}
</code>```

blade

```<code><div class="form-group">
    <label>Choose Country</label>
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>
</div>
</code>```

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

```<code>array_keys() expects parameter 1 to be array, object given
</code>```

Database :

Country Region Table :

Region Table :

Country Table :

答:
Use pluck instead of select in the query.

```<code>$country_region = DB::table('regions')
     ->join('country_region', 'regions.id', '=', 'country_region.region_id')
     ->join('countries', 'country_region.country_id', '=', 'countries.id')
     ->where('regions.id', '=', $id)
     ->get()
     ->pluck('countries.name', 'countries.id');
</code>```

Body:
I want to check either the countries exist in countries and the checkbox will be displayed. The values is directly from the database. I can't set the value at the input since it is array/multiple values. So, I want to check every array so that it will be a checkbox.

Controller :

public function edit($id)
{
    $region = Region::find($id);
    $countries = Country::all();
    $country_region = DB::table('regions')
        ->select('countries.id', 'countries.name')
        ->join('country_region', 'regions.id', '=', 'country_region.region_id')
        ->join('countries', 'country_region.country_id', '=', 'countries.id')
        ->where('regions.id', '=', $id)
        ->get();

    $items = array(
        'region' => $region,
        'countries' => $countries,
        'country_region' => $country_region,
    );

    return view('admin.region.edit')->with($items);
}

blade

    Choose Country
    <select id="test" type="checkbox" name="country_id[]">
        @foreach ($countries as $item)
        <option value="{{$item->id}}" selected @if (in_array($item->id, array_keys($country_region))) checked="checked"
            @endif>{{$item->name}}
        </option>
        @endforeach
    </select>

As you can see, I put php statement inside the blade to check either $country_region is exist in the countries or not. I got errors that related to the array such below :

array_keys() expects parameter 1 to be array, object given

Database :

Country Region Table :

Region Table :

Country Table :

Body:
Use pluck instead of select in the query.

$country_region = DB::table('regions')
     ->join('country_region', 'regions.id', '=', 'country_region.region_id')
     ->join('countries', 'country_region.country_id', '=', 'countries.id')
     ->where('regions.id', '=', $id)
     ->get()
     ->pluck('countries.name', 'countries.id');


问:
Cannon uninstall pip3, but pip3 --version shows it is existing
I installed conda and pip, also i have pip3. I installed jupyter notebook with pip, but when i started with jupyter notebook, i didnt have some packages, so i decided to uninstall pip and use jupyter from conda, because jupyter and terminal command 'python' didn't see some packages, that did have conda

i used:
pip uninstall pip

but nothing changes, 'python' and jupyter notebook is still working as he worked before
i tried to do pip3 uninstall pip3, but it says "Cannot uninstall requirement pip3, not installed"

Help me, please, how do i delete pip at all from Linux Mint?

pip3 --version shows "pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6)"

pip3 list also works

Maybe question is really stupid, but i`m new to programming, so i really don't understand, how it works, so hoping to your understanding.
Thanks

答:
I think this will work

```<code>sudo python -m pip uninstall pip
</code>```

if you are using python3-pip

```<code>sudo apt-get remove python3-pip
sudo apt-get --purge autoremove python3-pip
</code>```

Body:
I think this will work

sudo python -m pip uninstall pip

if you are using python3-pip

sudo apt-get remove python3-pip
sudo apt-get --purge autoremove python3-pip


问:
How to print the const in html tag in react js?
I have a localstorage value in const i need to use in html tag.How to do so?

My js code is:

```<code>componentDidMount() {
  const userName = localStorage.getItem('userName');
  console.log(userName);

}
</code>```

My Html code where i need to use is:

```<code><Dropdown.Toggle className="nav-link count-indicator bg-transparent">
                  <span className="profile-text"></span>
                  userName here
                </Dropdown.Toggle>
</code>```

答:
First of all you need to define the userName in your state, so that you can assign a value to it in componentDidmount. Then you can use it like this -

```<code>class App extends Component {
  constructor() {
    super();
    this.state = {
      userName: null
    };
  }

  componentDidMount() {
    this.setState({userName: localStorage.getItem('userName')})
    console.log(userName);
  }

  render() {
    return (
      <Dropdown.Toggle className="nav-link count-indicator bg-transparent">
        <span className="profile-text"></span>
        {this.state.userName}
      </Dropdown.Toggle>
    );
  }
}
</code>```

Body:
I have a localstorage value in const i need to use in html tag.How to do so?

My js code is:

componentDidMount() {
  const userName = localStorage.getItem('userName');
  console.log(userName);

}

My Html code where i need to use is:

<Dropdown.Toggle className="nav-link count-indicator bg-transparent">

                  userName here
                </Dropdown.Toggle>

Body:
First of all you need to define the userName in your state, so that you can assign a value to it in componentDidmount. Then you can use it like this -

class App extends Component {
  constructor() {
    super();
    this.state = {
      userName: null
    };
  }

  componentDidMount() {
    this.setState({userName: localStorage.getItem('userName')})
    console.log(userName);
  }

  render() {
    return (
      <Dropdown.Toggle className="nav-link count-indicator bg-transparent">
        <span className="profile-text"></span>
        {this.state.userName}
      </Dropdown.Toggle>
    );
  }
}


问:
Rounding 64 bit integers to 32 bit integers
I have a function that does rounding operation as shown below. It takes 64bit integer as input and gives 32bit integer as output. While converting, a factor of 0x40000000 is being added to the input. What is the reason behind it?</p>

```<code>int rounder(long long int in)
{
  INT64 out;
  if ((in >> 32) == 0x7FFFFFFF)
    out = in;
  else
    out = (INT64)0x40000000 + in;
  out = out >> 31;
  return (INT32)out;
}
</code>```

答: The input appears to be a 64-bit fixed point number with 31 fraction bits.  The 0x40000000 value is added to round the number up if it has a fractional part >= 0.5.  The if is used to avoid possible overflow when factoring in the rounding.

Body:
I have a function that does rounding operation as shown below. It takes 64bit integer as input and gives 32bit integer as output. While converting, a factor of 0x40000000 is being added to the input. What is the reason behind it?

int rounder(long long int in)
{
  INT64 out;
  if ((in >> 32) == 0x7FFFFFFF)
    out = in;
  else
    out = (INT64)0x40000000 + in;
  out = out >> 31;
  return (INT32)out;
}


问:
Help with image-resizing methods gdi
So I'm in need of some resizing.

I found two different methods.

One looks like this:

```<code>public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) {
        using(imageFile){
            Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight);

            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) {
                newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution);
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }
</code>```

And the other:

```<code>    public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) {
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        int NewHeight = originalImage.Height * width / originalImage.Width;
        if (NewHeight > maxHeight) {
            // Resize with height instead
            width = originalImage.Width * maxHeight / originalImage.Height;
            NewHeight = maxHeight;
        }

        System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

        return newImage;
    }
</code>```

I basically 'borrowed' both methods, and just changed bits and pieces.

However - using the first one, whenever I resize to a little smaller picture, the size of the file is actually larger then the original (!?)

And the second while greatly improving size looks terrible :/

I'm of course leaning on merely improving image quality in the first method, if possible, but I can't see how, everything looks to be 'high quality' from my point of view ?

答:
Regardless of the file size issues, I would definitely recommend using the first method, rather than the one with the GetThumbnailImage.

GetThumbnailImage will actually pull an embedded thumbnail out of the source image if one exists. Unfortunately, this means you're scaling from some unknown original file size and quality (compared to the original) if you're not anticipating and taking into account the embedded thumbnail. It also means that you'll get very different quality results on one run (with an embedded thumbnail) than you would on another run (with no embedded thumbnail).

I've used something similar to your first method numerous times and while I have seen what you're seeing on occasion, the results were just consistently better.

Title: Help with image-resizing methods gdi

Body:
So I'm in need of some resizing.

I found two different methods.

One looks like this:

public static Byte[] ResizeImageNew(System.Drawing.Image imageFile, int targetWidth, int targetHeight) {
        using(imageFile){
            Size newSize = CalculateDimensions(imageFile.Size, targetWidth, targetHeight);

            using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppRgb)) {
                newImage.SetResolution(imageFile.HorizontalResolution, imageFile.VerticalResolution);
                using (Graphics canvas = Graphics.FromImage(newImage)) {
                    canvas.SmoothingMode = SmoothingMode.AntiAlias;
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    canvas.DrawImage(imageFile, new Rectangle(new Point(0, 0), newSize));
                    MemoryStream m = new MemoryStream();
                    newImage.Save(m, ImageFormat.Jpeg);
                    return m.GetBuffer();
                }
            }
        }
    }

And the other:

    public static System.Drawing.Image ResizeImage(System.Drawing.Image originalImage, int width, int maxHeight) {
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        originalImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

        int NewHeight = originalImage.Height * width / originalImage.Width;
        if (NewHeight > maxHeight) {
            // Resize with height instead
            width = originalImage.Width * maxHeight / originalImage.Height;
            NewHeight = maxHeight;
        }

        System.Drawing.Image newImage = originalImage.GetThumbnailImage(width, NewHeight, null, IntPtr.Zero);

        return newImage;
    }

I basically 'borrowed' both methods, and just changed bits and pieces.

However - using the first one, whenever I resize to a little smaller picture, the size of the file is actually larger then the original (!?)

And the second while greatly improving size looks terrible :/

I'm of course leaning on merely improving image quality in the first method, if possible, but I can't see how, everything looks to be 'high quality' from my point of view ?


问:
Octopus Deploy: Slack Notifier step fails with "Could not create SSL/TLS secure channel"
We are using Octopus Deploy to deploy our application. After a successful deployment, we have an additional step of sending a notification to Slack with the deployment status.

However, this previously-working step is started failing a few days ago.  I have been so far unable to find the root cause of the failure.

We are getting this error in the Slack log:

```<code>Invoke-RestMethod : The request was aborted: Could not create SSL/TLS secure channel.
+     Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json - ...
Error
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException+ FullyQualifiedError IdWebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The remote script failed with exit code 1
</code>```

Things we've tried so far:

Verified the TLS version on the server.

Reviewed a few articles from the Internet to bypass SSL/TLS

Here's the PowerShell script that we are using:

```<code>[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json -Depth 4) -Uri $OctopusParameters['HookUrl']  -ContentType 'application/json'
</code>```

答:
I update the template with below code , update project step and it worked .</p>

```<code> add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12

Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json -Depth 4) -Uri $OctopusParameters['HookUrl']  -ContentType 'application/json'
</code>```

Body:
We are using Octopus Deploy to deploy our application. After a successful deployment, we have an additional step of sending a notification to Slack with the deployment status.

However, this previously-working step is started failing a few days ago.  I have been so far unable to find the root cause of the failure.

We are getting this error in the Slack log:

Invoke-RestMethod : The request was aborted: Could not create SSL/TLS secure channel.
+     Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json - ...
Error
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Error
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException+ FullyQualifiedError IdWebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The remote script failed with exit code 1

Things we've tried so far:

Verified the TLS version on the server.

Reviewed a few articles from the Internet to bypass SSL/TLS

Here's the PowerShell script that we are using:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json -Depth 4) -Uri $OctopusParameters['HookUrl']  -ContentType 'application/json'

Body:
I update the template with below code , update project step and it worked .

 add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
"@

[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Ssl3, [Net.SecurityProtocolType]::Tls, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls12

Invoke-RestMethod -Method POST -Body ($payload | ConvertTo-Json -Depth 4) -Uri $OctopusParameters['HookUrl']  -ContentType 'application/json'


问:
remainders for fractions in python
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

```<code>print(1%2)
=1

print(2%4)
=2
</code>```

答:
Understanding The Modulo Operator, %, and Its Mirror, //, and Their Usefulness

The modulo operator, %, gives the remainder of division. 1 % 2 would be like dividing 1 by 2, but stopping any further calculation because that's as far as we can go without using decimal notation, and keeping the part that wasn't divided (which is 1).

Using the modulo operator, %, doesn't conceptually take into account that 1/2 is equal to 2/4. With the expression op1 % op2, what op2 signifies is a range of values, while op1 signifies a value that can be reduced to a value within the range that op1 represents.

To show the usefulness of this in programming, I'll use a chess board as an example. Suppose I have a 1-dimensional array representing the board.  If at some line in my code I need to convert an array index (say 23) of a square to chess notation (file & rank --> h6 for instance), I could do something like this...

```<code>>>> board = ['br', 'bn', 'bb', 'bq', 'bk', 'bb', 'bn', 'br', # 8
...          'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', # 7
...          None, None, None, None, None, None, None, None, # 6
...          None, None, None, None, None, None, None, None, # 5
...          None, None, None, None, None, None, None, None, # 4
...          None, None, None, None, None, None, None, None, # 3
...          'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', # 2
...          'wr', 'wn', 'wb', 'wq', 'wk', 'wb', 'wn', 'wr'] # 1
...         # a     b     c     d     e     f      g     h
>>>
>>> def position(sq_index):
...    return { 'file': sq_index % 8, 'rank': 7 - sq_index // 8 }
...
>>> position(23)
{'file': 7, 'rank': 5}
>>>
>>> def chess_notation(pos):
...     alpha = 'abcdefgh'
...     return alpha[pos['file']] + str(pos['rank'] + 1) # + 1 because ranks
...                                                      # start at 1 in
...                                                      # notation.
...
>>> chess_notation(position(23))
'h6'
</code>```

(In chess, the columns on the x-axis of the board are referred to as 'files' and the y-axis rows are the 'ranks')

Note that the implementation for position() has sq_index % 8 ("sq_index modulo eight") in it to determine the file value. The files on a chess board go from 'a' to 'h' (columns 0 to 7). If we count squares left to right 0 to 7, we get to the end and then repeat our counting on the next rank. The number of squares we may have counted so far could be 9, but using 9 % 8, we know our finger is now on the 'b' file (9 % 8 = 1).

So no matter what index we have within 0 to 63, it can be reduced to a value between 0 and 7. If index n increments from 0 to 63 sequentially, n % 8 will produce 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, .. and so on.

The calculation to get the rank is a similar operation. We have sq_index // 8. The // operator (or "floor division operator") produces an integer result with the remainder discarded (essentially the opposite of %). This gives the same result we'd get if implemented as math.floor( 1 / 8 ). // is a Python 3 feature. With Python 3, 1 / 8 produces a float result, while 1 // 8 produces an integer value.

So, say we count squares again, 0 to 7. At each square n_sq // 8 produces the same value, 0. Then we continue counting up the next rank, 8 to 15. Each of those index values produces 1 (e.g. 11 // 8 = 1). And so on. The board array in the code has ranks numbered 8 to 1, so to convert to the right rank value it's 8 - (sq_index // 8).

Note: For Python 2 the // operator, and the / operator both produce an integer value. This difference between Python 2 and 3 can cause some confusion when migrating.

Title: remainders for fractions in python

Body:
I am not understanding remainders on fractions. how is there a remainder of 1 for 1/2 , and then a different remainder for the same fraction but un-simplified.

any help would be appreciated.

I can follow how 3%2= 1 , but I do not understand the below:

print(1%2)
=1

print(2%4)
=2

Body:
Understanding The Modulo Operator, %, and Its Mirror, //, and Their Usefulness

The modulo operator, %, gives the remainder of division. 1 % 2 would be like dividing 1 by 2, but stopping any further calculation because that's as far as we can go without using decimal notation, and keeping the part that wasn't divided (which is 1).

Using the modulo operator, %, doesn't conceptually take into account that 1/2 is equal to 2/4. With the expression op1 % op2, what op2 signifies is a range of values, while op1 signifies a value that can be reduced to a value within the range that op1 represents.

To show the usefulness of this in programming, I'll use a chess board as an example. Suppose I have a 1-dimensional array representing the board.  If at some line in my code I need to convert an array index (say 23) of a square to chess notation (file & rank --> h6 for instance), I could do something like this...

>>> board = ['br', 'bn', 'bb', 'bq', 'bk', 'bb', 'bn', 'br', # 8
...          'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', # 7
...          None, None, None, None, None, None, None, None, # 6
...          None, None, None, None, None, None, None, None, # 5
...          None, None, None, None, None, None, None, None, # 4
...          None, None, None, None, None, None, None, None, # 3
...          'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', # 2
...          'wr', 'wn', 'wb', 'wq', 'wk', 'wb', 'wn', 'wr'] # 1
...         # a     b     c     d     e     f      g     h
>>>
>>> def position(sq_index):
...    return { 'file': sq_index % 8, 'rank': 7 - sq_index // 8 }
...
>>> position(23)
{'file': 7, 'rank': 5}
>>>
>>> def chess_notation(pos):
...     alpha = 'abcdefgh'
...     return alpha[pos['file']] + str(pos['rank'] + 1) # + 1 because ranks
...                                                      # start at 1 in
...                                                      # notation.
...
>>> chess_notation(position(23))
'h6'

(In chess, the columns on the x-axis of the board are referred to as 'files' and the y-axis rows are the 'ranks')

Note that the implementation for position() has sq_index % 8 ("sq_index modulo eight") in it to determine the file value. The files on a chess board go from 'a' to 'h' (columns 0 to 7). If we count squares left to right 0 to 7, we get to the end and then repeat our counting on the next rank. The number of squares we may have counted so far could be 9, but using 9 % 8, we know our finger is now on the 'b' file (9 % 8 = 1).

So no matter what index we have within 0 to 63, it can be reduced to a value between 0 and 7. If index n increments from 0 to 63 sequentially, n % 8 will produce 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, .. and so on.

The calculation to get the rank is a similar operation. We have sq_index // 8. The // operator (or "floor division operator") produces an integer result with the remainder discarded (essentially the opposite of %). This gives the same result we'd get if implemented as math.floor( 1 / 8 ). // is a Python 3 feature. With Python 3, 1 / 8 produces a float result, while 1 // 8 produces an integer value.

So, say we count squares again, 0 to 7. At each square n_sq // 8 produces the same value, 0. Then we continue counting up the next rank, 8 to 15. Each of those index values produces 1 (e.g. 11 // 8 = 1). And so on. The board array in the code has ranks numbered 8 to 1, so to convert to the right rank value it's 8 - (sq_index // 8).

Note: For Python 2 the // operator, and the / operator both produce an integer value. This difference between Python 2 and 3 can cause some confusion when migrating.


问:
Pandas Count Group Number
Given the following dataframe:

```<code>df=pd.DataFrame({'col1':['A','A','A','A','A','A','B','B','B','B','B','B'],
                'col2':['x','x','y','z','y','y','x','y','y','z','z','x'],
                })
df

    col1    col2
0   A       x
1   A       x
2   A       y
3   A       z
4   A       y
5   A       y
6   B       x
7   B       y
8   B       y
9   B       z
10  B       z
11  B       x
</code>```

I'd like to create a new column, col3 which classifies the values in col2 sequentially, grouped by the values in col1:

```<code>    col1    col2    col3
0   A       x       x1
1   A       x       x1
2   A       y       y1
3   A       z       z1
4   A       y       y2
5   A       y       y2
6   B       x       x1
7   B       y       y1
8   B       y       y1
9   B       z       z1
10  B       z       z1
11  B       x       x2
</code>```

In the above example, col3[0:1] has a value of x1 because its the first group of x values in col2 for col1 = A. col3[4:5] has values of y2 because its the second group of y values in col2 for col1 = A etc...

I hope the description makes sense. I was unable to find an answer partially because I can't find an elegant way to articulate what I'm looking for.

答:
Here's my approach:

```<code>groups = (df.assign(s=df.groupby('col1')['col2']   # group col2 by col1
                    .shift().ne(df['col2'])        # check if col2 different from the previous (shift)
                    .astype(int)                   # convert to int
                   )   # the new column s marks the beginning of consecutive blocks with `1`
          .groupby(['col1','col2'])['s']           # group `s` by `col1` and `col2`
          .cumsum()                                # cumsum by group
          .astype(str)
         )

df['col3'] = df['col2'] + groups
</code>```

Output:

```<code>   col1 col2 col3
0     A    x   x1
1     A    x   x1
2     A    y   y1
3     A    z   z1
4     A    y   y2
5     A    y   y2
6     B    x   x1
7     B    y   y1
8     B    y   y1
9     B    z   z1
10    B    z   z1
11    B    x   x2
</code>```

Title: Pandas Count Group Number

Body:
Given the following dataframe:

df=pd.DataFrame({'col1':['A','A','A','A','A','A','B','B','B','B','B','B'],
                'col2':['x','x','y','z','y','y','x','y','y','z','z','x'],
                })
df

    col1    col2
0   A       x
1   A       x
2   A       y
3   A       z
4   A       y
5   A       y
6   B       x
7   B       y
8   B       y
9   B       z
10  B       z
11  B       x

I'd like to create a new column, col3 which classifies the values in col2 sequentially, grouped by the values in col1:

    col1    col2    col3
0   A       x       x1
1   A       x       x1
2   A       y       y1
3   A       z       z1
4   A       y       y2
5   A       y       y2
6   B       x       x1
7   B       y       y1
8   B       y       y1
9   B       z       z1
10  B       z       z1
11  B       x       x2

In the above example, col3[0:1] has a value of x1 because its the first group of x values in col2 for col1 = A. col3[4:5] has values of y2 because its the second group of y values in col2 for col1 = A etc...

I hope the description makes sense. I was unable to find an answer partially because I can't find an elegant way to articulate what I'm looking for.

Body:
Here's my approach:

groups = (df.assign(s=df.groupby('col1')['col2']   # group col2 by col1
                    .shift().ne(df['col2'])        # check if col2 different from the previous (shift)
                    .astype(int)                   # convert to int
                   )   # the new column s marks the beginning of consecutive blocks with `1`
          .groupby(['col1','col2'])['s']           # group `s` by `col1` and `col2`
          .cumsum()                                # cumsum by group
          .astype(str)
         )

df['col3'] = df['col2'] + groups

Output:

   col1 col2 col3
0     A    x   x1
1     A    x   x1
2     A    y   y1
3     A    z   z1
4     A    y   y2
5     A    y   y2
6     B    x   x1
7     B    y   y1
8     B    y   y1
9     B    z   z1
10    B    z   z1
11    B    x   x2


问:
fetch all rows from mysql db with php using aFetch($sql) problem
i inherited this code from some-one and this only returns the first row it finds:

```<code>function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}
</code>```

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks

答:
```<code>function aFetch($result = false) {
        if($result)
            return mysql_fetch_assoc($result);
        else
            return mysql_fetch_assoc($this->result);
    }
</code>```

you can use this function.

Body:
i inherited this code from some-one and this only returns the first row it finds:

function getMessages($userID, $from, $limit)
{
  $id = $_SESSION['user_id'];
  $sql = "SELECT * FROM rc_message_box_table WHERE profile_id_to = {$userID} AND rc_message_box_table.profile_id_from NOT IN (SELECT profile_id_block FROM rc_blocklist_table WHERE profile_id = {$id}) LIMIT {$from}, {$limit}";
  $row = $this->aFetch($sql);
  return $row;
}

function aFetch($sSql)
{
//print_r($sSql);
$aResults = array();
if(is_string($sSql))
{
      $fnSql = $this->query($sSql);
    }

   while($row = mysql_fetch_assoc($fnSql))
   {
  $aResults[] = $row;
   }
   return  $aResults;
}

how can i with this code return all rows where profile_id_to = {$userID} ??
thanks

Body:
function aFetch($result = false) {
        if($result)
            return mysql_fetch_assoc($result);
        else
            return mysql_fetch_assoc($this->result);
    }

you can use this function.


问:
Adding native swift code to NativeScript application
I'm trying to add native swift code to my NativeScript app. According to these instructions in the documentation I can just add a swift source file to App_Resources/iOS/src/ and then use any publicly exposed classes directly in my TypeScript code.
Unfortunately this just doesn't work. I'll just get Cannot find name 'TestClass' and that's it.

Steps to reproduce:

Get a fresh NS project with ios tns create my-app-name --template tns-template-blank-ts

Update: I actually created the App with vue init nativescript-vue/vue-cli-template testapp. That seems to have caused the problems.

Add a TestClass.swift to App_Resources/iOS/src/

import Foundation

public class TestClass: NSObject {
    @objc public func echo(param: String) -> String {
        return param
    }
}
```

Instantiate it in any TypeScript source file let instance = new TestClass()

Do tns debug ios

Compilation will fail with Cannot find name 'TestClass'

I have also tried generating TypeScript typings with TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios or or just delcaring it as any with declare let KeyCommander: any; to eliminate the possibility that this is a TS related problem. The first approach doesn't generate any typings for my custom class so the TypeScript code will still not compile. The second approach let's the TS code compile but crashes on execution with JS ERROR ReferenceError: Can't find variable: TestClass.

I have also verified that the swift file is indeed getting compiled by inserting a syntax error which will crash the build process.

My NativeScript version is 6.4.0.

What am I missing?

Update: I just realized I actually created the App with vue init nativescript-vue/vue-cli-template testapp. I verified that as mentioned Tyler Blake's answer in an app created with the tns cli the described process actually works. In an app I just freshly created with vue init it doesn't, the objc!nsswiftsupport.d.ts is not being generated.

The question now is: What's causing the difference?

答:
I followed your steps and I was able to get the typings to generate in objc!nsswiftsupport.d.ts. After you generate typings do you have that file with these contents?

```<code>declare class TestClass extends NSObject {

    static alloc(): TestClass; // inherited from NSObject

    static new(): TestClass; // inherited from NSObject

    echoWithParam(param: string): string;
}
</code>```

This shows that NS is able to pick up the Swift code.

All you need to do now is add tns-platform-declarations then in the references.d.ts file, add a line that points to the objc!nsswiftsupport.d.ts file. Then you'll get intellisense in your TS code.

Something like this:

/// <reference path="./typings/objc!nsswiftsupport.d.ts" />

Hope this helps!

Body:
I'm trying to add native swift code to my NativeScript app. According to these instructions in the documentation I can just add a swift source file to App_Resources/iOS/src/ and then use any publicly exposed classes directly in my TypeScript code.
Unfortunately this just doesn't work. I'll just get Cannot find name 'TestClass' and that's it.

Steps to reproduce:

Get a fresh NS project with ios tns create my-app-name --template tns-template-blank-ts

Update: I actually created the App with vue init nativescript-vue/vue-cli-template testapp. That seems to have caused the problems.

Add a TestClass.swift to App_Resources/iOS/src/

import Foundation

public class TestClass: NSObject {
    @objc public func echo(param: String) -> String {
        return param
    }
}

Instantiate it in any TypeScript source file let instance = new TestClass()

Do tns debug ios

Compilation will fail with Cannot find name 'TestClass'

I have also tried generating TypeScript typings with TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios or or just delcaring it as any with declare let KeyCommander: any; to eliminate the possibility that this is a TS related problem. The first approach doesn't generate any typings for my custom class so the TypeScript code will still not compile. The second approach let's the TS code compile but crashes on execution with JS ERROR ReferenceError: Can't find variable: TestClass.

I have also verified that the swift file is indeed getting compiled by inserting a syntax error which will crash the build process.

My NativeScript version is 6.4.0.

What am I missing?

Update: I just realized I actually created the App with vue init nativescript-vue/vue-cli-template testapp. I verified that as mentioned Tyler Blake's answer in an app created with the tns cli the described process actually works. In an app I just freshly created with vue init it doesn't, the objc!nsswiftsupport.d.ts is not being generated.

The question now is: What's causing the difference?

Body:
I followed your steps and I was able to get the typings to generate in objc!nsswiftsupport.d.ts. After you generate typings do you have that file with these contents?

declare class TestClass extends NSObject {

    static alloc(): TestClass; // inherited from NSObject

    static new(): TestClass; // inherited from NSObject

    echoWithParam(param: string): string;
}

This shows that NS is able to pick up the Swift code.

All you need to do now is add tns-platform-declarations then in the references.d.ts file, add a line that points to the objc!nsswiftsupport.d.ts file. Then you'll get intellisense in your TS code.

Something like this:

/// <reference path="./typings/objc!nsswiftsupport.d.ts" />

Hope this helps!


问:
Why text has underline with yellow color with big font size?
Screenshot of the code and it's result:

Hi, I have StatelessWidget which has Container returning in its build method and the Text widget as a child widget. But it's look and feel is not as expected. Why is the yellow underline and how can I remove it?

I tried replacing the Container with Stack, Column and Row nothing change.

答:
Every screen should have a scaffold widget</p>

```<code> @override
  Widget build(BuildContext context) {
    return Scaffold(
             body:Container(
                  child:Text("your text"),
           ),
        );
</code>```

Body:
Every screen should have a scaffold widget

 @override
  Widget build(BuildContext context) {
    return Scaffold(
             body:Container(
                  child:Text("your text"),
           ),
        );