问:
PubSubClient Not Showing Received Messages Using Callback()
I am facing a problem in receiving the message by nodemcu whenever subscribe() is called. publish() is working fine while sending the message. Broker is mosquitto. I have even used callback() but no response. Here is the code. It actually reads the card tag, sends it to broker and based on the card tag sent, another client on linux sends back a message which I am receiving using subscribe() method, but I am not able to retrieve the message. Any help.

```<code>#include<Esp.h>
#define SS_PIN 4  //D2
#define RST_PIN 5 //D1
#include<SPI.h>
#include<MFRC522.h>
#include<ESP8266WiFi.h>
#include<PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

int y=HIGH;
int z=HIGH;
String p;
String w;
String l;
String data = "";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char* ssid = "Nahi Milega Password";
const char* wifi_password = "qazwsxedc789000123";
const char* mqtt_server = "192.168.1.103";
const char* mqtt_topic = "Data";
const char* mqtt_topic2 = "Data2";
const char* mqtt_topic3 = "Data3";

//const char* mqtt_username = "RFID";
//const char* mqtt_password = "datarfid";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "NodeMCU";
WiFiClient wifiClient;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int statuss = 0;
int out = 0;
void callback(char* topic, byte* payload, unsigned int length);
bool initcard();
PubSubClient client(wifiClient); // 1883 is the listener port for the Broker

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);// Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  ESP.wdtEnable(4);
  client.setServer(mqtt_server,1883);
  client.setCallback(callback);
  ESP.wdtDisable();
  pinMode(2,INPUT);
  pinMode(3,OUTPUT);
  pinMode(0,INPUT);
  pinMode(16,OUTPUT);
  pinMode(15,OUTPUT);
  pinMode(10,OUTPUT);
  mfrc522.PCD_Init();// Initiate MFRC522
    WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 if (client.connect(clientID)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }
}
void loop()
{
    client.loop();
  // Look for new cards
  digitalWrite(3,LOW);
  digitalWrite(16,LOW);
  digitalWrite(15,LOW);
  digitalWrite(10,HIGH);
  while(!initcard())ESP.wdtFeed();
  //Show UID on serial monitor
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  content.toUpperCase();
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+="}";
  Serial.println(data);
  char c[25];
  for (int q=0;q<25;q++)
  c[q]=data[q];
  client.connect("First");
  client.publish(mqtt_topic2,c);
  client.subscribe(mqtt_topic3);
  memset(&c[0], 0, sizeof(c));
  Serial.println("Exited from loop 1");
  data ="";
  Serial.println(w);
  if((w=="b")||(w=="c"))
  { w="";
  client.connect(clientID);
  Serial.println("Reached in loop2");
  y=digitalRead(2);
  z=digitalRead(0);
  Serial.println();
  digitalWrite(10,LOW);
while((y==HIGH) && (z==HIGH))
{
   y=digitalRead(2);
   z=digitalRead(0);
   digitalWrite(3,HIGH);
   ESP.wdtFeed();
   if((y==LOW)||(z==LOW))
   {
   if (y==LOW)
   {p="Home";
   digitalWrite(16,HIGH);}
   else{
   p="Market";
   digitalWrite(15,HIGH);}
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+=",";
  data+="\'";
  data+="Purpose";
  data+="\'";
  data+=":";
  data+="\'";
  data+=p;
  data+="\'";
  data+="}";
  Serial.println(data);
   char c[100];
   for (int q=0;q<data.length();q++)
   c[q]=data[q];
  digitalWrite(3,LOW);
  if (client.publish(mqtt_topic,c)) {
      Serial.println("Button pushed and message sent!");
    }
     else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID);
      delay(1000); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic,c);
    }
  data="";
  memset(&c[0], 0, sizeof(c));
  delay(1000);
   break;
   }
  }
 }
}

void callback(char* topic, byte* payload, unsigned int length) {
 w="";
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
  char receivedChar = (char)payload[i];
  w+=receivedChar;
  Serial.print(w);
 }
 Serial.println();}

bool initcard()
{
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    false;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return false;
  }
  return true;
  }
</code>```

答:
This should work:-</p>

```<code>#include<Esp.h>
#define SS_PIN 4  //D2
#define RST_PIN 5 //D1
#include<SPI.h>
#include<MFRC522.h>
#include<ESP8266WiFi.h>
#include<PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

int y=HIGH;
int z=HIGH;
String p;
String w;
String l;
String data = "";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char* ssid = "Nahi Milega Password";
const char* wifi_password = "qazwsxedc789000123";
const char* mqtt_server = "192.168.1.103";
const char* mqtt_topic = "Data";
const char* mqtt_topic2 = "Data2";
const char* mqtt_topic3 = "Data3";

//const char* mqtt_username = "RFID";
//const char* mqtt_password = "datarfid";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "NodeMCU";
WiFiClient wifiClient;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int statuss = 0;
int out = 0;
void callback(char* topic, byte* payload, unsigned int length);
bool initcard();
PubSubClient client(wifiClient); // 1883 is the listener port for the Broker

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);// Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  ESP.wdtEnable(4);
  client.setServer(mqtt_server,1883);
  client.setCallback(callback);
  ESP.wdtDisable();
  pinMode(2,INPUT);
  pinMode(3,OUTPUT);
  pinMode(0,INPUT);
  pinMode(16,OUTPUT);
  pinMode(15,OUTPUT);
  pinMode(10,OUTPUT);
  mfrc522.PCD_Init();// Initiate MFRC522
    WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 if (client.connect(clientID)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }
}
void loop()
{
    client.loop();
  // Look for new cards
  digitalWrite(3,LOW);
  digitalWrite(16,LOW);
  digitalWrite(15,LOW);
  digitalWrite(10,HIGH);
  while(!initcard())ESP.wdtFeed();
  //Show UID on serial monitor
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  content.toUpperCase();
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+="}";
  Serial.println(data);
  char c[25];
  for (int q=0;q<25;q++)
  c[q]=data[q];
  client.connect("First");
  client.publish(mqtt_topic2,c);
  client.subscribe(mqtt_topic3);
  memset(&c[0], 0, sizeof(c));
  Serial.println("Exited from loop 1");
  data ="";
  Serial.println(w);
  if((w=="b")||(w=="c"))
  { w="";
  client.connect(clientID);
  Serial.println("Reached in loop2");
  y=digitalRead(2);
  z=digitalRead(0);
  Serial.println();
  digitalWrite(10,LOW);
while((y==HIGH) && (z==HIGH))
{
   y=digitalRead(2);
   z=digitalRead(0);
   digitalWrite(3,HIGH);
   ESP.wdtFeed();
   if((y==LOW)||(z==LOW))
   {
   if (y==LOW)
   {p="Home";
   digitalWrite(16,HIGH);}
   else{
   p="Market";
   digitalWrite(15,HIGH);}
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+=",";
  data+="\'";
  data+="Purpose";
  data+="\'";
  data+=":";
  data+="\'";
  data+=p;
  data+="\'";
  data+="}";
  Serial.println(data);
   char c[100];
   for (int q=0;q<data.length();q++)
   c[q]=data[q];
  digitalWrite(3,LOW);
  if (client.publish(mqtt_topic,c)) {
      Serial.println("Button pushed and message sent!");
    }
     else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID);
      delay(1000); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic,c);
    }
  data="";
  memset(&c[0], 0, sizeof(c));
  delay(1000);
   break;
   }
  }
 }
}

void callback(char* topic, byte* payload, unsigned int length) {
 w="";
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
 }
 Serial.println();
 }

bool initcard()
{
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    false;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return false;
  }
  return true;
  }
</code>```

Body:
I am facing a problem in receiving the message by nodemcu whenever subscribe() is called. publish() is working fine while sending the message. Broker is mosquitto. I have even used callback() but no response. Here is the code. It actually reads the card tag, sends it to broker and based on the card tag sent, another client on linux sends back a message which I am receiving using subscribe() method, but I am not able to retrieve the message. Any help.

#include<Esp.h>
#define SS_PIN 4  //D2
#define RST_PIN 5 //D1
#include<SPI.h>
#include<MFRC522.h>
#include<ESP8266WiFi.h>
#include<PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

int y=HIGH;
int z=HIGH;
String p;
String w;
String l;
String data = "";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char* ssid = "Nahi Milega Password";
const char* wifi_password = "qazwsxedc789000123";
const char* mqtt_server = "192.168.1.103";
const char* mqtt_topic = "Data";
const char* mqtt_topic2 = "Data2";
const char* mqtt_topic3 = "Data3";

//const char* mqtt_username = "RFID";
//const char* mqtt_password = "datarfid";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "NodeMCU";
WiFiClient wifiClient;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int statuss = 0;
int out = 0;
void callback(char* topic, byte* payload, unsigned int length);
bool initcard();
PubSubClient client(wifiClient); // 1883 is the listener port for the Broker

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);// Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  ESP.wdtEnable(4);
  client.setServer(mqtt_server,1883);
  client.setCallback(callback);
  ESP.wdtDisable();
  pinMode(2,INPUT);
  pinMode(3,OUTPUT);
  pinMode(0,INPUT);
  pinMode(16,OUTPUT);
  pinMode(15,OUTPUT);
  pinMode(10,OUTPUT);
  mfrc522.PCD_Init();// Initiate MFRC522
    WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 if (client.connect(clientID)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }
}
void loop()
{
    client.loop();
  // Look for new cards
  digitalWrite(3,LOW);
  digitalWrite(16,LOW);
  digitalWrite(15,LOW);
  digitalWrite(10,HIGH);
  while(!initcard())ESP.wdtFeed();
  //Show UID on serial monitor
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  content.toUpperCase();
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+="}";
  Serial.println(data);
  char c[25];
  for (int q=0;q<25;q++)
  c[q]=data[q];
  client.connect("First");
  client.publish(mqtt_topic2,c);
  client.subscribe(mqtt_topic3);
  memset(&c[0], 0, sizeof(c));
  Serial.println("Exited from loop 1");
  data ="";
  Serial.println(w);
  if((w=="b")||(w=="c"))
  { w="";
  client.connect(clientID);
  Serial.println("Reached in loop2");
  y=digitalRead(2);
  z=digitalRead(0);
  Serial.println();
  digitalWrite(10,LOW);
while((y==HIGH) && (z==HIGH))
{
   y=digitalRead(2);
   z=digitalRead(0);
   digitalWrite(3,HIGH);
   ESP.wdtFeed();
   if((y==LOW)||(z==LOW))
   {
   if (y==LOW)
   {p="Home";
   digitalWrite(16,HIGH);}
   else{
   p="Market";
   digitalWrite(15,HIGH);}
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+=",";
  data+="\'";
  data+="Purpose";
  data+="\'";
  data+=":";
  data+="\'";
  data+=p;
  data+="\'";
  data+="}";
  Serial.println(data);
   char c[100];
   for (int q=0;q<data.length();q++)
   c[q]=data[q];
  digitalWrite(3,LOW);
  if (client.publish(mqtt_topic,c)) {
      Serial.println("Button pushed and message sent!");
    }
     else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID);
      delay(1000); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic,c);
    }
  data="";
  memset(&c[0], 0, sizeof(c));
  delay(1000);
   break;
   }
  }
 }
}

void callback(char* topic, byte* payload, unsigned int length) {
 w="";
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
  char receivedChar = (char)payload[i];
  w+=receivedChar;
  Serial.print(w);
 }
 Serial.println();}

bool initcard()
{
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    false;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return false;
  }
  return true;
  }

Body:
This should work:-

#include<Esp.h>
#define SS_PIN 4  //D2
#define RST_PIN 5 //D1
#include<SPI.h>
#include<MFRC522.h>
#include<ESP8266WiFi.h>
#include<PubSubClient.h>
#include <Wire.h>
#include <Adafruit_INA219.h>

int y=HIGH;
int z=HIGH;
String p;
String w;
String l;
String data = "";
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char* ssid = "Nahi Milega Password";
const char* wifi_password = "qazwsxedc789000123";
const char* mqtt_server = "192.168.1.103";
const char* mqtt_topic = "Data";
const char* mqtt_topic2 = "Data2";
const char* mqtt_topic3 = "Data3";

//const char* mqtt_username = "RFID";
//const char* mqtt_password = "datarfid";
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
const char* clientID = "NodeMCU";
WiFiClient wifiClient;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int statuss = 0;
int out = 0;
void callback(char* topic, byte* payload, unsigned int length);
bool initcard();
PubSubClient client(wifiClient); // 1883 is the listener port for the Broker

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);// Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  ESP.wdtEnable(4);
  client.setServer(mqtt_server,1883);
  client.setCallback(callback);
  ESP.wdtDisable();
  pinMode(2,INPUT);
  pinMode(3,OUTPUT);
  pinMode(0,INPUT);
  pinMode(16,OUTPUT);
  pinMode(15,OUTPUT);
  pinMode(10,OUTPUT);
  mfrc522.PCD_Init();// Initiate MFRC522
    WiFi.begin(ssid, wifi_password);

  // Wait until the connection has been confirmed before continuing
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 if (client.connect(clientID)) {
    Serial.println("Connected to MQTT Broker!");
  }
  else {
    Serial.println("Connection to MQTT Broker failed...");
  }
}
void loop()
{
    client.loop();
  // Look for new cards
  digitalWrite(3,LOW);
  digitalWrite(16,LOW);
  digitalWrite(15,LOW);
  digitalWrite(10,HIGH);
  while(!initcard())ESP.wdtFeed();
  //Show UID on serial monitor
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? "0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  content.toUpperCase();
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+="}";
  Serial.println(data);
  char c[25];
  for (int q=0;q<25;q++)
  c[q]=data[q];
  client.connect("First");
  client.publish(mqtt_topic2,c);
  client.subscribe(mqtt_topic3);
  memset(&c[0], 0, sizeof(c));
  Serial.println("Exited from loop 1");
  data ="";
  Serial.println(w);
  if((w=="b")||(w=="c"))
  { w="";
  client.connect(clientID);
  Serial.println("Reached in loop2");
  y=digitalRead(2);
  z=digitalRead(0);
  Serial.println();
  digitalWrite(10,LOW);
while((y==HIGH) && (z==HIGH))
{
   y=digitalRead(2);
   z=digitalRead(0);
   digitalWrite(3,HIGH);
   ESP.wdtFeed();
   if((y==LOW)||(z==LOW))
   {
   if (y==LOW)
   {p="Home";
   digitalWrite(16,HIGH);}
   else{
   p="Market";
   digitalWrite(15,HIGH);}
  data+="{";
  data+="\'";
  data+="ID";
  data+="\'";
  data+=":";
  data+="\'";
  data+=content;
  data+="\'";
  data+=",";
  data+="\'";
  data+="Purpose";
  data+="\'";
  data+=":";
  data+="\'";
  data+=p;
  data+="\'";
  data+="}";
  Serial.println(data);
   char c[100];
   for (int q=0;q<data.length();q++)
   c[q]=data[q];
  digitalWrite(3,LOW);
  if (client.publish(mqtt_topic,c)) {
      Serial.println("Button pushed and message sent!");
    }
     else {
      Serial.println("Message failed to send. Reconnecting to MQTT Broker and trying again");
      client.connect(clientID);
      delay(1000); // This delay ensures that client.publish doesn't clash with the client.connect call
      client.publish(mqtt_topic,c);
    }
  data="";
  memset(&c[0], 0, sizeof(c));
  delay(1000);
   break;
   }
  }
 }
}

void callback(char* topic, byte* payload, unsigned int length) {
 w="";
 Serial.print("Message arrived [");
 Serial.print(topic);
 Serial.print("] ");
 for (int i=0;i<length;i++) {
    Serial.print((char)payload[i]);
 }
 Serial.println();
 }

bool initcard()
{
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    false;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return false;
  }
  return true;
  }


来源: stackexchange

问:
MS ACCESS Lock a table during update, blocking
How can I lock a table preventing other users querying it while I update its contents?

Currently my data is updated by wiping the table and re-populating it (i know, its not the best way to update data, but the source data has no unique key to do a record by record update and this is the only way). There exists the unlikely, but possible scenario where a user my access the table in the middle of the update and catch it while it is empty thus returning bad info.

Is there at the SQL (or code) level a way to create a blocking statement that will wait for a DB update to complete prior to querying?

答:
Access has very little locking capabilities. Unless you're storing your data in a different backend, you only can set a database-wide lock or no lock at all.

There is some locking capability setting table locks when the table structure of a table is being changed, but as far as I can find, that's not available to the user (neither through the GUI nor through VBA)

Note that both ADO and DAO support locking (in ADO by setting the IsolationLevel, in DAO by setting dbDenyRead + dbDenyWrite when executing the query), but in my short testing, these options do absolutely nothing in Access.

ContentLicense: CC BY-SA 3.0


问:
Owncloud has no installation cadidate, how do I fix?
I am trying to install Owncloud server on a fresh install of Ubuntu 16.04 and have been following these instructions from Digital Ocean and it has gone flawlessly up until the command

```<code>$ sudo apt-get install owncloud
</code>```

So I tried running

```<code>$ sudo apt-get install owncloud-files
</code>```

Which something installed, but it didn't do the installer as expected per the Digital Ocean instructions

To be clear, I have done all of the steps leading up to the install of owncloud.

```<code>$ sudo curl https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/Release.key | sudo apt-key add -
[sudo] password for user:
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100  4502  100  4502    0     0   3847      0  0:00:01  0:00:01 --:--:--  3847
OK

$ echo 'deb https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/ /' | sudo tee /etc/apt/sources.list.d/owncloud.list
deb https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/ /

$ sudo apt-get update
Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Get:2 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:4 http://dl.google.com/linux/chrome/deb stable Release
Get:5 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Hit:6 http://ppa.launchpad.net/certbot/certbot/ubuntu xenial InRelease
Ign:7 http://download.opensuse.org/repositories/isv:/ownCloud:/desktop/Ubuntu_16.04  InRelease
Get:9 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Hit:10 http://download.opensuse.org/repositories/isv:/ownCloud:/desktop/Ubuntu_16.04  Release
Get:11 http://security.ubuntu.com/ubuntu xenial-security/main amd64 DEP-11 Metadata [60.3 kB]
Get:12 http://us.archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages [644 kB]
Get:14 http://security.ubuntu.com/ubuntu xenial-security/main DEP-11 64x64 Icons [57.6 kB]
Get:15 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 DEP-11 Metadata [49.6 kB]
Get:16 http://security.ubuntu.com/ubuntu xenial-security/universe DEP-11 64x64 Icons [80.0 kB]
Get:17 http://us.archive.ubuntu.com/ubuntu xenial-updates/main i386 Packages [611 kB]
Get:18 http://us.archive.ubuntu.com/ubuntu xenial-updates/main amd64 DEP-11 Metadata [305 kB]
Ign:19 https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04  InRelease
Get:20 http://us.archive.ubuntu.com/ubuntu xenial-updates/main DEP-11 64x64 Icons [213 kB]
Get:21 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages [540 kB]
Get:22 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe i386 Packages [516 kB]
Get:23 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 DEP-11 Metadata [173 kB]
Get:24 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe DEP-11 64x64 Icons [240 kB]
Get:25 http://us.archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 DEP-11 Metadata [5,888 B]
Get:26 http://us.archive.ubuntu.com/ubuntu xenial-backports/main amd64 DEP-11 Metadata [3,328 B]
Get:27 http://us.archive.ubuntu.com/ubuntu xenial-backports/universe amd64 DEP-11 Metadata [4,584 B]
Hit:28 https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04  Release
Fetched 3,809 kB in 1s (1,932 kB/s)
Reading package lists... Done

$ sudo apt-get install owncloud
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package owncloud is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  owncloud-files

E: Package 'owncloud' has no installation candidate
</code>```

That is everything that happens when I follow the steps, it still says there is no 'owncloud' installation candidate.

答:
The problem here is that ownCloud recently dropped the owncloud meta-package (that can be harmful in environments with multiple applications hosted simultaneously). The difference with the owncloud-files package is described in the docs:

owncloud-files (recommended): This package installs only ownCloud. It does not install Apache, a database, or any PHP dependencies.

owncloud: This package installs ownCloud, complete with all dependencies.

So, basically, you downloaded and installed ownCloud on your system (you'll see it living under your /var/www/owncloud dir.) - but now it's missing its dependencies. You'll need to install them manually; you can see a list in: https://doc.owncloud.org/server/10.0/admin_manual/installation/source_installation.html#install-the-required-packages:

```<code>sudo apt install -y apache2 mariadb-server libapache2-mod-php7.0 \
    php7.0-gd php7.0-json php7.0-mysql php7.0-curl \
    php7.0-intl php7.0-mcrypt php-imagick \
    php7.0-zip php7.0-xml php7.0-mbstring
</code>```

After the installation, you'll be prompted with the apache wizard you were missing from the DigitalOcean tutorial. From there you'll be able to customize the server installation. In case you need more info on how to complete the process, see: configuring the apache server and completing the installation

Body:
I am trying to install Owncloud server on a fresh install of Ubuntu 16.04 and have been following these instructions from Digital Ocean and it has gone flawlessly up until the command

$ sudo apt-get install owncloud

So I tried running

$ sudo apt-get install owncloud-files

Which something installed, but it didn't do the installer as expected per the Digital Ocean instructions

To be clear, I have done all of the steps leading up to the install of owncloud.

$ sudo curl https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/Release.key | sudo apt-key add -
[sudo] password for user:
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100  4502  100  4502    0     0   3847      0  0:00:01  0:00:01 --:--:--  3847
OK

$ echo 'deb https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/ /' | sudo tee /etc/apt/sources.list.d/owncloud.list
deb https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04/ /

$ sudo apt-get update
Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Get:2 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Hit:3 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:4 http://dl.google.com/linux/chrome/deb stable Release
Get:5 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Hit:6 http://ppa.launchpad.net/certbot/certbot/ubuntu xenial InRelease
Ign:7 http://download.opensuse.org/repositories/isv:/ownCloud:/desktop/Ubuntu_16.04  InRelease
Get:9 http://us.archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Hit:10 http://download.opensuse.org/repositories/isv:/ownCloud:/desktop/Ubuntu_16.04  Release
Get:11 http://security.ubuntu.com/ubuntu xenial-security/main amd64 DEP-11 Metadata [60.3 kB]
Get:12 http://us.archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages [644 kB]
Get:14 http://security.ubuntu.com/ubuntu xenial-security/main DEP-11 64x64 Icons [57.6 kB]
Get:15 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 DEP-11 Metadata [49.6 kB]
Get:16 http://security.ubuntu.com/ubuntu xenial-security/universe DEP-11 64x64 Icons [80.0 kB]
Get:17 http://us.archive.ubuntu.com/ubuntu xenial-updates/main i386 Packages [611 kB]
Get:18 http://us.archive.ubuntu.com/ubuntu xenial-updates/main amd64 DEP-11 Metadata [305 kB]
Ign:19 https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04  InRelease
Get:20 http://us.archive.ubuntu.com/ubuntu xenial-updates/main DEP-11 64x64 Icons [213 kB]
Get:21 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages [540 kB]
Get:22 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe i386 Packages [516 kB]
Get:23 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 DEP-11 Metadata [173 kB]
Get:24 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe DEP-11 64x64 Icons [240 kB]
Get:25 http://us.archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 DEP-11 Metadata [5,888 B]
Get:26 http://us.archive.ubuntu.com/ubuntu xenial-backports/main amd64 DEP-11 Metadata [3,328 B]
Get:27 http://us.archive.ubuntu.com/ubuntu xenial-backports/universe amd64 DEP-11 Metadata [4,584 B]
Hit:28 https://download.owncloud.org/download/repositories/stable/Ubuntu_16.04  Release
Fetched 3,809 kB in 1s (1,932 kB/s)
Reading package lists... Done

$ sudo apt-get install owncloud
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package owncloud is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  owncloud-files

E: Package 'owncloud' has no installation candidate

That is everything that happens when I follow the steps, it still says there is no 'owncloud' installation candidate.

Body:
The problem here is that ownCloud recently dropped the owncloud meta-package (that can be harmful in environments with multiple applications hosted simultaneously). The difference with the owncloud-files package is described in the docs:

owncloud-files (recommended): This package installs only ownCloud. It does not install Apache, a database, or any PHP dependencies.

owncloud: This package installs ownCloud, complete with all dependencies.

So, basically, you downloaded and installed ownCloud on your system (you'll see it living under your /var/www/owncloud dir.) - but now it's missing its dependencies. You'll need to install them manually; you can see a list in: https://doc.owncloud.org/server/10.0/admin_manual/installation/source_installation.html#install-the-required-packages:

sudo apt install -y apache2 mariadb-server libapache2-mod-php7.0 \
    php7.0-gd php7.0-json php7.0-mysql php7.0-curl \
    php7.0-intl php7.0-mcrypt php-imagick \
    php7.0-zip php7.0-xml php7.0-mbstring

After the installation, you'll be prompted with the apache wizard you were missing from the DigitalOcean tutorial. From there you'll be able to customize the server installation. In case you need more info on how to complete the process, see: configuring the apache server and completing the installation


问:
Class template for cache aligned memory usage in C++
(to provide the information you need to understand my question is a lot, however it is already compressed)

i try to implement a class template to allocate and access data cache aligned. This works very good, however trying to implement support for arrays is a problem.

Semantically the code shall provide this mapping in memory for a single element like this:

```<code>cache_aligned<element_type>* my_el =
          new(cache_line_size) cache_aligned<element_type>();
| element | buffer |
</code>```

the access (so far) looks like this:

```<code>*my_el; // returns cache_aligned<element_type>
**my_el; //returns element_type
*my_el->member_of_element();
</code>```

HOWEVER for an array, i'd like to have this:

```<code> cache_aligned<element_type>* my_el_array =
         new(cache_line_size)  cache_aligned<element_type()[N];
 | element 0 | buffer | element 1 | buffer | ... | element (N-1) | buffer |
</code>```

So far i have the following code

```<code>template <typename T>
class cache_aligned {
    private:
        T instance;
    public:
        cache_aligned()
        {}
        cache_aligned(const T& other)
        :instance(other.instance)
        {}
        static void* operator new (size_t size, uint c_line_size) {
             return c_a_malloc(size, c_line_size);
        }
        static void* operator new[] (size_t size, uint c_line_size) {
             int num_el = (size - sizeof(cache_aligned<T>*)
                              / sizeof(cache_aligned<T>);
             return c_a_array(sizeof(cache_aligned<T>), num_el, c_line_size);
        }
        static void operator delete (void* ptr) {
             free_c_a(ptr);
        }
        T* operator-> () {
             return &instance;
        }
        T& operator * () {
             return instance;
        }
};
</code>```

the functions cache_aligned_malloc

```<code>void* c_a_array(uint size, ulong num_el, uint c_line_size) {
    void* mem = malloc((size + c_line_size) * num_el + sizeof(void*));
    void** ptr = (void**)((long)mem + sizeof(void*));
    ptr[-1] = mem;
    return ptr;
}

void free_c_a(void ptr) {
    free(((void**)ptr)[-1]);
}
</code>```

The problem is here, the access to the data should work like this:

```<code>my_el_array[i]; // returns cache_aligned<element_type>
*(my_el_array[i]); // returns element_type
my_el_array[i]->member_of_element();
</code>```

My ideas to solve it, are:

(1) something similar to this, to overload sizeof operator:

```<code>static size_t operator sizeof () {
   return sizeof(cache_aligned<T>) + c_line_size;
}
</code>```

--> not possible since overloading sizeof operator is illegal

(2) something like this, to overload the operator [] for the pointer type:

```<code>static T& operator [] (uint index, cache_aligned<T>* ptr) {
    return ptr + ((sizeof(cache_aligned<T>) + c_line_size) * index);
}
</code>```

--> not possible in C++, anyway

(3) totally trivial solution

```<code>template <typename T> cache_aligned {
    private:
          T instance;
          bool buffer[CACHE_LINE_SIZE];
          // CACHE_LINE_SIZE defined as macro
    public:
          // trivial operators and methods ;)
};
</code>```

--> i don't know whether this is reliable, actually i'm using gcc-4.5.1 in linux ...

(4) Replacing T instance; by T* instance_ptr; in the class template and using the operator [] to calculate the position of the element, like this:

| pointer-to-instance | ----> | element 0 | buffer | ... | element (N-1) | buffer |

this is not the intended semantic, since the instance of the class template becomes the bottleneck when calculating the address of the elements.

Thanks for reading! I dont' know how to shorten the problem. It would be great, if you can help! Any work around would help a lot.

I know alignment is an extension in C++0x. However, in gcc it is not available yet.

Greetz, sema

答:
When c_line_size is compile time integral constant then of course better pad the cache_aligned with char array depending on sizeof T.

You can also check if 2 T-s fit onto one cache line and lower the alignment requirement accordingly.

Do not expect miracles from such an optimization. I think 2 times better performance for some algorithms is the ceiling that you can squeeze out from avoiding cache line splits.

Body:
(to provide the information you need to understand my question is a lot, however it is already compressed)

i try to implement a class template to allocate and access data cache aligned. This works very good, however trying to implement support for arrays is a problem.

Semantically the code shall provide this mapping in memory for a single element like this:

cache_aligned<element_type>* my_el =
          new(cache_line_size) cache_aligned<element_type>();
| element | buffer |

the access (so far) looks like this:

*my_el; // returns cache_aligned<element_type>
**my_el; //returns element_type
*my_el->member_of_element();

HOWEVER for an array, i'd like to have this:

 cache_aligned<element_type>* my_el_array =
         new(cache_line_size)  cache_aligned<element_type()[N];
 | element 0 | buffer | element 1 | buffer | ... | element (N-1) | buffer |

So far i have the following code

template <typename T>
class cache_aligned {
    private:
        T instance;
    public:
        cache_aligned()
        {}
        cache_aligned(const T& other)
        :instance(other.instance)
        {}
        static void* operator new (size_t size, uint c_line_size) {
             return c_a_malloc(size, c_line_size);
        }
        static void* operator new[] (size_t size, uint c_line_size) {
             int num_el = (size - sizeof(cache_aligned<T>*)
                              / sizeof(cache_aligned<T>);
             return c_a_array(sizeof(cache_aligned<T>), num_el, c_line_size);
        }
        static void operator delete (void* ptr) {
             free_c_a(ptr);
        }
        T* operator-> () {
             return &instance;
        }
        T& operator * () {
             return instance;
        }
};

the functions cache_aligned_malloc

void* c_a_array(uint size, ulong num_el, uint c_line_size) {
    void* mem = malloc((size + c_line_size) * num_el + sizeof(void*));
    void** ptr = (void**)((long)mem + sizeof(void*));
    ptr[-1] = mem;
    return ptr;
}

void free_c_a(void ptr) {
    free(((void**)ptr)[-1]);
}

The problem is here, the access to the data should work like this:

my_el_array[i]; // returns cache_aligned<element_type>
*(my_el_array[i]); // returns element_type
my_el_array[i]->member_of_element();

My ideas to solve it, are:

(1) something similar to this, to overload sizeof operator:

static size_t operator sizeof () {
   return sizeof(cache_aligned<T>) + c_line_size;
}

--> not possible since overloading sizeof operator is illegal

(2) something like this, to overload the operator [] for the pointer type:

static T& operator [] (uint index, cache_aligned<T>* ptr) {
    return ptr + ((sizeof(cache_aligned<T>) + c_line_size) * index);
}

--> not possible in C++, anyway

(3) totally trivial solution

template <typename T> cache_aligned {
    private:
          T instance;
          bool buffer[CACHE_LINE_SIZE];
          // CACHE_LINE_SIZE defined as macro
    public:
          // trivial operators and methods ;)
};

--> i don't know whether this is reliable, actually i'm using gcc-4.5.1 in linux ...

(4) Replacing T instance; by T* instance_ptr; in the class template and using the operator [] to calculate the position of the element, like this:

| pointer-to-instance | ----> | element 0 | buffer | ... | element (N-1) | buffer |

this is not the intended semantic, since the instance of the class template becomes the bottleneck when calculating the address of the elements.

Thanks for reading! I dont' know how to shorten the problem. It would be great, if you can help! Any work around would help a lot.

I know alignment is an extension in C++0x. However, in gcc it is not available yet.

Greetz, sema

ContentLicense: CC BY-SA 2.5


问:
Check if two products are in same order in Woocommerce email notifications
I am trying to add additional text to email for completed order if order contains two specfic product IDs. Here is my code so far:

```<code>function advmi_check_order_product_id($order_id)
{
    $order = new WC_Order($order_id);
    $items = $order->get_items();
    foreach($items as $item) {
        $product_id = $item['product_id'];
        if (($product_id == 56943 && $product_id == 95956 && 'completed' == $order->status )) {
            echo '<p>Added Text for both products in the order</p><p>Text </p>';
        }
        elseif ($product_id == 56943 && 'completed' == $order->status) {
            echo '<p>Text for only 56943 </p><p>Text </p>';
}
        }
</code>```

I also need the order status to be completed.

I am stuck - Any help on this please?

I am using WC Version: 2.6.14

答:
Update 2 - Added Compatibility WC from version 2.4 to 3.2+

Here is the correct way to make your code works (in woocommerce 2.6.x and above), keeping your function, that you will use in a second custom hooked function to get the display in email notifications:

```<code>// Your conditional function that output a custom text
// The argument needed is the WC_Order object (instead of the Order ID)
function advmi_check_order_product_id( $order )
{
    $has_product1 = $has_product2 = false; // Initializing
    // Added Compatibility WC from version 2.4 to 3.2+ (Get The order ID)
    ## $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
    ## $order = new WC_Order($order_id); // Get the WC_Order object

    foreach( $order->get_items() as $item ) {
        // Added Compatibility WC from version 2.4 to 3.2+
        $product_id = method_exists( $item, 'get_product_id' ) ? $item->get_product_id() : $item['product_id'];
        if( 56943 == $product_id ) $has_product1 = true;
        if( 95956 == $product_id ) $has_product2 = true;
    }

    if ( $has_product1 && $has_product2 ) {
        echo '<p>'.__('Added Text for both products in the order').'</p>
            <p>'.__('Text').'</p>';
    }
    elseif ( $has_product1 && ! $has_product2 ) {
        echo '<p>'.__('Text for only 56943').'</p>
            <p>'.__('Text').'</p>';
    }
}

// The email function hooked that display the text
add_action( 'woocommerce_email_order_details', 'add_text_conditionally', 10, 4 );
function add_text_conditionally( $order, $sent_to_admin, $plain_text, $email ) {
    // For customer completed orders status only
    if ( $sent_to_admin || ! $order->has_status('completed') ) return;
    advmi_check_order_product_id( $order );
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works on versions 2.6.14 and 3.2.3…

Body:
I am trying to add additional text to email for completed order if order contains two specfic product IDs. Here is my code so far:

function advmi_check_order_product_id($order_id)
{
    $order = new WC_Order($order_id);
    $items = $order->get_items();
    foreach($items as $item) {
        $product_id = $item['product_id'];
        if (($product_id == 56943 && $product_id == 95956 && 'completed' == $order->status )) {
            echo '
Added Text for both products in the order

Text
';
        }
        elseif ($product_id == 56943 && 'completed' == $order->status) {
            echo '
Text for only 56943

Text
';
}
        }

I also need the order status to be completed.

I am stuck - Any help on this please?

I am using WC Version: 2.6.14

Body:
Update 2 - Added Compatibility WC from version 2.4 to 3.2+

Here is the correct way to make your code works (in woocommerce 2.6.x and above), keeping your function, that you will use in a second custom hooked function to get the display in email notifications:

// Your conditional function that output a custom text
// The argument needed is the WC_Order object (instead of the Order ID)
function advmi_check_order_product_id( $order )
{
    $has_product1 = $has_product2 = false; // Initializing
    // Added Compatibility WC from version 2.4 to 3.2+ (Get The order ID)
    ## $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
    ## $order = new WC_Order($order_id); // Get the WC_Order object

    foreach( $order->get_items() as $item ) {
        // Added Compatibility WC from version 2.4 to 3.2+
        $product_id = method_exists( $item, 'get_product_id' ) ? $item->get_product_id() : $item['product_id'];
        if( 56943 == $product_id ) $has_product1 = true;
        if( 95956 == $product_id ) $has_product2 = true;
    }

    if ( $has_product1 && $has_product2 ) {
        echo '<p>'.__('Added Text for both products in the order').'</p>
            <p>'.__('Text').'</p>';
    }
    elseif ( $has_product1 && ! $has_product2 ) {
        echo '<p>'.__('Text for only 56943').'</p>
            <p>'.__('Text').'</p>';
    }
}

// The email function hooked that display the text
add_action( 'woocommerce_email_order_details', 'add_text_conditionally', 10, 4 );
function add_text_conditionally( $order, $sent_to_admin, $plain_text, $email ) {
    // For customer completed orders status only
    if ( $sent_to_admin || ! $order->has_status('completed') ) return;
    advmi_check_order_product_id( $order );
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works on versions 2.6.14 and 3.2.3…


问:
How do you invoke a Runnable using Spring Framework?
I have a service that needs to invoke a runnable class.

Here are the lines of code that are being used in my service.

```<code>@Autowired
private LinkBrc2MemberProfile brcTask;

// Background Task.
SimpleAsyncTaskExecutor sate = new SimpleAsyncTaskExecutor();
sate.createThread(new LinkBrc2MemberProfile(user));
</code>```

Here is my Runnable class

```<code>@Service
public class LinkBrc2MemberProfile implements Runnable {

    private final Logger log = LoggerFactory.getLogger(LinkBrc2MemberProfile.class);

    @Autowired
    private LoyaltyDao dao;

    private Member member;

    public LinkBrc2MemberProfile() {
        super();
    }

    public LinkBrc2MemberProfile(Member member) {
        this.member = member;
    }

    public void run() {
        log.debug("*** Member User Name: " + member.getString("USER_NAME"));
        String emailAddress = member.getString("USER_NAME");
        Map<String, Object> map = dao.findBrcByEmailAddress( emailAddress );
        log.debug("==========================================================");

        if( ! map.isEmpty() ) {
            try {
                //a.CUSTOMER_ID, a.EMAIL_ADDRESS, b.card_no
                String customerId    = (String) map.get("CUSTOMER_ID");
                String brcCardNumber = (String) map.get("CARD_NO");

                log.debug("\ncustomerId: " + customerId + " brcCardNumber: " + brcCardNumber);
                if(!brcCardNumber.equals("")) {
                    // Add the Be Rewarded Card.
                    HashMap<String, String> userAttributes = new HashMap<String, String>();
                    String brcNumber = member.getString("BREWARDED_CARD_NO");
                    if (brcNumber.equals("")) {
                       userAttributes.put("BREWARDED_CARD_NO", brcCardNumber);
                       try {
                          member.putAll(userAttributes);
                       } catch (Exception e) {
                          String errorMessage = "Unable to save user's BRC information due to: " + e.getMessage();
                          log.error("{}", errorMessage);
                       }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }
</code>```

I'm not seeing any errors in the log but at the same time it does not appear to be invoking the Runnable class.  Am I missing an annotation somewhere?  Are there any good examples that you can point me to, the only ones I have found use XML files to configure the runnable class I would like to use annotations.  Thanks in Advance.

I've updated my service to do the following.

Please help, my DAO is NULL so it looks like my @Autowired in my Runnable class is not wiring it in.

I've added the following bean to my bean-config.xml file.

```<code><bean id="brcType" class="com.ws.ocp.service.LinkBrc2MemberProfile" scope="prototype"/>
</code>```

I removed my @Autowired annotation and added the following to my service class.

```<code>ClassPathResource rsrc = new ClassPathResource("bean-config.xml");
XmlBeanFactory factory = new XmlBeanFactory(rsrc);
LinkBrc2MemberProfile brcTask = (LinkBrc2MemberProfile) factory.getBean("brcType");

SimpleAsyncTaskExecutor sate = new SimpleAsyncTaskExecutor();
// Set Member attribute
brcTask.setMember(user);
// Executer
sate.execute(brcTask);
</code>```

Why is my dao still null?

答:
To answer your question of how to properly use a Prototype-Bean, this is my favorite way:

```<code>@Component
abstract class MyBean {
    /* Factory method that will be installed by Spring */
    @Lookup
    protected abstract YourPrototypeBean createBean();

    void someCode() {
        YourPrototypeBean bean = createBean();
    }
}
</code>```

Since it's a factory method, you can create as many instances as you like.

Body:
I have a service that needs to invoke a runnable class.

Here are the lines of code that are being used in my service.

@Autowired
private LinkBrc2MemberProfile brcTask;

// Background Task.
SimpleAsyncTaskExecutor sate = new SimpleAsyncTaskExecutor();
sate.createThread(new LinkBrc2MemberProfile(user));

Here is my Runnable class

@Service
public class LinkBrc2MemberProfile implements Runnable {

    private final Logger log = LoggerFactory.getLogger(LinkBrc2MemberProfile.class);

    @Autowired
    private LoyaltyDao dao;

    private Member member;

    public LinkBrc2MemberProfile() {
        super();
    }

    public LinkBrc2MemberProfile(Member member) {
        this.member = member;
    }

    public void run() {
        log.debug("*** Member User Name: " + member.getString("USER_NAME"));
        String emailAddress = member.getString("USER_NAME");
        Map<String, Object> map = dao.findBrcByEmailAddress( emailAddress );
        log.debug("==========================================================");

        if( ! map.isEmpty() ) {
            try {
                //a.CUSTOMER_ID, a.EMAIL_ADDRESS, b.card_no
                String customerId    = (String) map.get("CUSTOMER_ID");
                String brcCardNumber = (String) map.get("CARD_NO");

                log.debug("\ncustomerId: " + customerId + " brcCardNumber: " + brcCardNumber);
                if(!brcCardNumber.equals("")) {
                    // Add the Be Rewarded Card.
                    HashMap<String, String> userAttributes = new HashMap<String, String>();
                    String brcNumber = member.getString("BREWARDED_CARD_NO");
                    if (brcNumber.equals("")) {
                       userAttributes.put("BREWARDED_CARD_NO", brcCardNumber);
                       try {
                          member.putAll(userAttributes);
                       } catch (Exception e) {
                          String errorMessage = "Unable to save user's BRC information due to: " + e.getMessage();
                          log.error("{}", errorMessage);
                       }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }
    }

I'm not seeing any errors in the log but at the same time it does not appear to be invoking the Runnable class.  Am I missing an annotation somewhere?  Are there any good examples that you can point me to, the only ones I have found use XML files to configure the runnable class I would like to use annotations.  Thanks in Advance.

I've updated my service to do the following.

Please help, my DAO is NULL so it looks like my @Autowired in my Runnable class is not wiring it in.

I've added the following bean to my bean-config.xml file.

<bean id="brcType" class="com.ws.ocp.service.LinkBrc2MemberProfile" scope="prototype"/>

I removed my @Autowired annotation and added the following to my service class.

ClassPathResource rsrc = new ClassPathResource("bean-config.xml");
XmlBeanFactory factory = new XmlBeanFactory(rsrc);
LinkBrc2MemberProfile brcTask = (LinkBrc2MemberProfile) factory.getBean("brcType");

SimpleAsyncTaskExecutor sate = new SimpleAsyncTaskExecutor();
// Set Member attribute
brcTask.setMember(user);
// Executer
sate.execute(brcTask);

Why is my dao still null?

Body:
To answer your question of how to properly use a Prototype-Bean, this is my favorite way:

@Component
abstract class MyBean {
    /* Factory method that will be installed by Spring */
    @Lookup
    protected abstract YourPrototypeBean createBean();

    void someCode() {
        YourPrototypeBean bean = createBean();
    }
}

Since it's a factory method, you can create as many instances as you like.


问:
How can I populate the following objects in multiple input fields?
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

```
</div>
</div>
</p>

<p>My console perfectly returns </p>

``` * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4
```

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

答:
I am taking this approach (different for loop from yours) because I need to capture the input box;

luckily you have it as 1,2,3,4,5;

so I am using the index in interation; this index-in-iteration is difficult in a for-in structure;

hope this helps u.

```<code>for(i=1;i<=swatches.length;i++) {
    if (swatches.hasOwnProperty(swatch) && swatches[swatch]) let hexValue =  swatches[swatch].getHex();
    if (hexValue != undefined) {
        document.getElementById(i).value = hexValue;
    }
}
</code>```

Body:
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

My console perfectly returns

 * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

Body:
I am taking this approach (different for loop from yours) because I need to capture the input box;

luckily you have it as 1,2,3,4,5;

so I am using the index in interation; this index-in-iteration is difficult in a for-in structure;

hope this helps u.

for(i=1;i<=swatches.length;i++) {
    if (swatches.hasOwnProperty(swatch) && swatches[swatch]) let hexValue =  swatches[swatch].getHex();
    if (hexValue != undefined) {
        document.getElementById(i).value = hexValue;
    }
}


问:
Scraping a dynamic weather slideshow
I am making a weather page and I would need to screen scape the radar image on http://www.weather.bm/radarMobile.asp just the radar images. Fatherstorm has help me before and given me a php script it worked but with some bugs.

```<code>$localOffset = "+2 Hours"; //change this to your local offset from the image times you need. for me (CST) it's 2 hours.....
$start=  strtotime("-90 Minutes " . $localOffset); // go back 90 minutes (The limit of the available images)
$start=($start-($start % (600))+(60*6)); //go to the next earlier 6 minute mark (all images appear to be at the 6 minute mark))appear to be at the 6 minute mark))
for($x=1;$x<=9;$x++){
$DateTime = date("Y-m-d-Hi", $start); // set the image time we want.
$fName = ("http://www.weather.bm/images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-  $DateTime.jpg"); // set the filename
echo" $min <img src='$fName' alt='$fName'/><br/>"; // echo (or add to a stack or variable...) your image node
$start+=(600);//add 10 minutes     }
</code>```

Here are the problems:
most of the time some images and discription is not showing due to different time.
the script has 10 images but some times the site only displays 9 or 8.

I need a script that could scrape the images put it in a div ul li so I can animate it like in the original site(I mean the slideshow effect) or make it's path absolute don't know how it would help but I sure want to know how to do that also. The weather sites images is in a javascript array which I am not familliar.

I need the whole script so I can study it before using it so I can learn in the process.

答: I've already given you a working answer. You are unable to use it because you seemingly don't comprehend how PHP works. If so, you should consider paying a freelancer to do your coding and script setup. Stackoverflow is not a for-free coding forum - and people are much less inclined to help if people don't even bother to upvote or accept answers.</p>

ContentLicense: CC BY-SA 4.0

Title: Scraping a dynamic weather slideshow

Body:
I am making a weather page and I would need to screen scape the radar image on http://www.weather.bm/radarMobile.asp just the radar images. Fatherstorm has help me before and given me a php script it worked but with some bugs.

$localOffset = "+2 Hours"; //change this to your local offset from the image times you need. for me (CST) it's 2 hours.....
$start=  strtotime("-90 Minutes " . $localOffset); // go back 90 minutes (The limit of the available images)
$start=($start-($start % (600))+(60*6)); //go to the next earlier 6 minute mark (all images appear to be at the 6 minute mark))appear to be at the 6 minute mark))
for($x=1;$x<=9;$x++){
$DateTime = date("Y-m-d-Hi", $start); // set the image time we want.
$fName = ("http://www.weather.bm/images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-  $DateTime.jpg"); // set the filename
echo" $min
"; // echo (or add to a stack or variable...) your image node
$start+=(600);//add 10 minutes     }

Here are the problems:
most of the time some images and discription is not showing due to different time.
the script has 10 images but some times the site only displays 9 or 8.

I need a script that could scrape the images put it in a div ul li so I can animate it like in the original site(I mean the slideshow effect) or make it's path absolute don't know how it would help but I sure want to know how to do that also. The weather sites images is in a javascript array which I am not familliar.

I need the whole script so I can study it before using it so I can learn in the process.


问:
can some one help me calculating time difference between two Date Stamps?
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

```<code>    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt
</code>```

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

答:
Mainly, as Patrick wrote, the format string was wrong. You can check how a format string is written here. Also, the variables d1 and d2 were used before they were declared, and subtraction of dates usually works in the way of difference = older_date - newer_date. In short:

```<code>import datetime as dt

date_format = "%Y-%m-%d %H:%M:%S"

d1=('2017-01-06T02:23:44.000-0500')
d2=('2017-01-19T17:30:21.000-0500')

x1 = d1.replace('T', ' ').split('.')[0]
x2 = d2.replace('T', ' ').split('.')[0]

start_dt = dt.datetime.strptime(x1, date_format)
end_dt = dt.datetime.strptime(x2, date_format)

x = end_dt - start_dt
print(x)
</code>```

Prints:

```<code>13 days, 15:06:37
</code>```

The splitting for x1 and x2 is personal taste, slicing off at indices just asks for the code to be broken during format change or with a different locale.

Body:
My date formats are like this:
(u'Task', u'2017-01-06T02:23:44.000-0500') .. stage 1
(u'Task', u'2017-01-06T05:27:10.000-0500') .. stage 2
(u'Task', u'2017-01-10T14:42:44.000-0500') ...stage 2

I have to calulcate the time difference between every stage
I am using this (which I know is incorrect :-()

    import datetime as dt
    date_format = "yyyy-mm-ddThh-mm-ss"
    x1= d1.split('T')[0]+' '+(d1.split('T'))[1][:8]
    x2= d2.split('T')[0]+' '+(d2.split('T'))[1][:8]

    d1=('2017-01-06T02:23:44.000-0500')
    d2=('2017-01-19T17:30:21.000-0500')

#some string slicing to get rid of T and the timezone indicator
    start_dt = dt.datetime.strptime(x1, 'yyyy-mm-ddhh:mm:ss')
    end_dt = dt.datetime.strptime(x2, 'yyyy-mm-ddhh:mm:ss')

    x = start_dt - end_dt

It returns me a format mismatch error

can someone help me find the time spent between stage 1 and stage 2 I have to calculate this recursively

Body:
Mainly, as Patrick wrote, the format string was wrong. You can check how a format string is written here. Also, the variables d1 and d2 were used before they were declared, and subtraction of dates usually works in the way of difference = older_date - newer_date. In short:

import datetime as dt

date_format = "%Y-%m-%d %H:%M:%S"

d1=('2017-01-06T02:23:44.000-0500')
d2=('2017-01-19T17:30:21.000-0500')

x1 = d1.replace('T', ' ').split('.')[0]
x2 = d2.replace('T', ' ').split('.')[0]

start_dt = dt.datetime.strptime(x1, date_format)
end_dt = dt.datetime.strptime(x2, date_format)

x = end_dt - start_dt
print(x)

Prints:

13 days, 15:06:37

The splitting for x1 and x2 is personal taste, slicing off at indices just asks for the code to be broken during format change or with a different locale.


问:
Should signed or unsigned integers be used for sizes?
The standard library vector::size() gives a size_t, an unsigned number. In one of the CppCon talks I have heard somebody (was it Chandler Carruth?) say that this is unfortunate and that it should rather use signed integers.

The background is that the overflow is not defined for signed integers, therefore the compiler has much more leeway. In a talk Carruth showed how a uint8_t as a for loop index in bzip2 creates many more machine instructions on x86 than int8_t because it has to explicitly simulate the overflow with masks and shifts.

In the code that I now work on, there are certain sizes which are strictly positive. These are represented as size_t. This seems decent because this shows that they cannot be negative. On the other hand, there is no need for the defined modular arithmetic, so as long as the signed integer is large enough (we go to like 200), the unsigned integer would have the wrong interface for the arithmetics that we want.

At some point in the code there are loops from 0 to this size. And then the loop indices are subtracted and the absolute value is taken.

When I compiled it with my more modern GCC 7, it could not resolve the proper overload of std::abs because size_t - size_t gives ambigious values, apparently. I have changed the code to use int in the loop indices:

```<code>for (int t1 = 0; t1 < Lt; t1++) {
  for (int t2 = 0; t2 < Lt; t2++) {
</code>```

Now the abs(t1 - t2) works just fine. But the comparison t1 < Lt gives a warning because it is a comparison between signed and unsigned numbers.

What is the right approach?

Use unsigned integers for everthing that is non-negative and then use static_cast<int>() whenever I need to do a substraction.

Use signed integers for loop indices but unsigned integers for the sizes of the containers. Then use static_cast<int> in the comparisons.

Just use signed integers everywhere. When other libraries return unsigned integers, just use static_cast<int> there in order to satisfy the warnings.

答:
"In a talk Carruth showed how a uint8_t as a for loop index in bzip2 creates many more machine instructions on x86 than int8_t because it has to explicitly simulate the overflow with masks and shifts."

Well, if you can use either type, the for-range must be limited to [0, 127]. Just use int as the index type, then. It is by definition the natural type for basic math operations, and typically maps well to CPU registers.

Using types optimized for minimal storage will not generate the fastest math, no. That is not a surprise. You can't draw conclusions about signed versus unsigned based on such flawed setups.

"size_t - size_t gives ambiguous values"

Well, it doesn't, but it does use modular arithmetic. size_t(1)-size_t(2)==size_t(-1), but size_t(-1) is the largest possible value. This follows directly from the definition of modular math: x-1 < x, except when x-1 wraps around because x==0. (Or equivalently x+1>x except when x+1==0)

Calling abs(size_t(x)) is therefore also pointless since every size_t value is positive. And comparing signed integers against size_t is equally fraught with unintended consequences. Explicit casts are good, as they make the consequences clear.

But there is no universal solution to automatically figure out which cast should be applied. If a mechanical rule could be invented, we could have left that rule to the compiler. We haven't, because we can't. You, as a programmer will have to consider each case numerically.

Body:
The standard library vector::size() gives a size_t, an unsigned number. In one of the CppCon talks I have heard somebody (was it Chandler Carruth?) say that this is unfortunate and that it should rather use signed integers.

The background is that the overflow is not defined for signed integers, therefore the compiler has much more leeway. In a talk Carruth showed how a uint8_t as a for loop index in bzip2 creates many more machine instructions on x86 than int8_t because it has to explicitly simulate the overflow with masks and shifts.

In the code that I now work on, there are certain sizes which are strictly positive. These are represented as size_t. This seems decent because this shows that they cannot be negative. On the other hand, there is no need for the defined modular arithmetic, so as long as the signed integer is large enough (we go to like 200), the unsigned integer would have the wrong interface for the arithmetics that we want.

At some point in the code there are loops from 0 to this size. And then the loop indices are subtracted and the absolute value is taken.

When I compiled it with my more modern GCC 7, it could not resolve the proper overload of std::abs because size_t - size_t gives ambigious values, apparently. I have changed the code to use int in the loop indices:

for (int t1 = 0; t1 < Lt; t1++) {
  for (int t2 = 0; t2 < Lt; t2++) {

Now the abs(t1 - t2) works just fine. But the comparison t1 < Lt gives a warning because it is a comparison between signed and unsigned numbers.

What is the right approach?

Use unsigned integers for everthing that is non-negative and then use static_cast<int>() whenever I need to do a substraction.

Use signed integers for loop indices but unsigned integers for the sizes of the containers. Then use static_cast<int> in the comparisons.

Just use signed integers everywhere. When other libraries return unsigned integers, just use static_cast<int> there in order to satisfy the warnings.


问:
Update w/Select Subquery - Correct?
I am nervous to pull the trigger on this query, as I have not tooled around with subqueries all that much.  I wanted to make sure this beastie does what I want it to do in terms of my program.

```<code>DoCmd.RunSQL ("UPDATE Gage_Master SET Gage_Master.Est_Calibration_Cost = SELECT dbo_Gage_Master.Est_Calibration_Cost FROM dbo_Gage_Master WHERE dbo_Gage_Master.Est_Calibration_Cost <> Gage_Master.Est_Calibration_Cost WHERE Gage_Master.Gage_ID = dbo_Gage_Master.Gage_ID;")
</code>```

Basically - will this puppy update the Estimated Calibration Cost in the Gage_Master table (linked to another program's MDB datastore with a table by the same name) with the value in the SQL-Server stored copy of the Gage_Master table (dbo_Gage_Master) as long as they are not equal?

Sorry if this is an already asked question - like I said, this is a pretty complex thing, and the last thing I want to do is blank out my prices in my production database because I wrote something wrong.  Thanks in advance for your help!

答:
I'm assuming you're trying to run this in Access. This would explaing the "Missing Operator" error you've referred to in comments--Access doesn't understand UPDATE...FROM.... Try this instead:

```<code>UPDATE dbo_Gage_Master AS dgm INNER JOIN
  Gage_Master AS gm ON dgm.Gage_ID = gm.Gage_ID
SET gm.Est_Calibration_Cost = dgm.Est_Calibration_Cost
WHERE gm.Est_Calibration_Cost <> dgm.Est_Calibration_Cost;
</code>```

Yeah, it looks like you might be updating the wrong way, because dgm comes first in the join (it just worked out that way...). That's not the case, as it's the SET clause that determines what updates actually get done.

Title: Update w/Select Subquery - Correct?

Body:
I am nervous to pull the trigger on this query, as I have not tooled around with subqueries all that much.  I wanted to make sure this beastie does what I want it to do in terms of my program.

DoCmd.RunSQL ("UPDATE Gage_Master SET Gage_Master.Est_Calibration_Cost = SELECT dbo_Gage_Master.Est_Calibration_Cost FROM dbo_Gage_Master WHERE dbo_Gage_Master.Est_Calibration_Cost <> Gage_Master.Est_Calibration_Cost WHERE Gage_Master.Gage_ID = dbo_Gage_Master.Gage_ID;")

Basically - will this puppy update the Estimated Calibration Cost in the Gage_Master table (linked to another program's MDB datastore with a table by the same name) with the value in the SQL-Server stored copy of the Gage_Master table (dbo_Gage_Master) as long as they are not equal?

Sorry if this is an already asked question - like I said, this is a pretty complex thing, and the last thing I want to do is blank out my prices in my production database because I wrote something wrong.  Thanks in advance for your help!

Body:
I'm assuming you're trying to run this in Access. This would explaing the "Missing Operator" error you've referred to in comments--Access doesn't understand UPDATE...FROM.... Try this instead:

UPDATE dbo_Gage_Master AS dgm INNER JOIN
  Gage_Master AS gm ON dgm.Gage_ID = gm.Gage_ID
SET gm.Est_Calibration_Cost = dgm.Est_Calibration_Cost
WHERE gm.Est_Calibration_Cost <> dgm.Est_Calibration_Cost;

Yeah, it looks like you might be updating the wrong way, because dgm comes first in the join (it just worked out that way...). That's not the case, as it's the SET clause that determines what updates actually get done.


问:
Google BigQuery: creating a view via Python google-cloud-bigquery version 0.27.0 vs. 0.28.0
All,

I'm having trouble creating a Google BigQuery view in python with the version 0.28 of the bq library that has come out about two weeks ago.  I'm quite certain the problem is on my side, something I'm missing, but I cannot find the issue.

Please be gentle, I don't ask lots of questions online but I'm quite stumped.
 I'm also not completely incompetent, here are some details:

I have my GOOGLE_APPLICATION_CREDENTIALS set correctly

All the other commands I've run against bq via python are fine

I've reviewed the
https://cloud.google.com/bigquery/docs/python-client-migration

I think the issue is around the "fix"
https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4038
BigQuery: replaces table.create() with client.create_table() #4038

I've tried legacy vs. standard sql

I'm on python 2.7.12 (can't upgrade anytime soon, corporate version thing)

The issue?  The code in the second block below creates a TABLE, with no schema and no records.  It clearly should create a VIEW instead, right?

sudo pip install -Iv google-cloud-bigquery==0.27.0

```<code>from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data20'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(view_name)
table.view_query = sqlQuery

table.create()
</code>```

the above works fine, view created, great!

the below, only a table is created, no rows, no schema, yuck!

sudo pip uninstall google-cloud-bigquery

sudo pip install -Iv google-cloud-bigquery==0.28.0

```<code>from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data21'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True

table = bigquery.Table(table_ref)
bigquery_client.create_table(table)
</code>```

Other links:

How can I create a new view in bigquery using the python API?

https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html

Any useful thoughts would be very much appreciated.

Thanks and best regards...Rich

答:
Tim's answer was perfect, thank you very much.

Here is the final code:

```<code>from google.cloud import bigquery
bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table = bigquery.Table(table_ref)
table.view_query = sqlQuery
table.view_use_legacy_sql = True

bigquery_client.create_table(table)
</code>```

Body:
All,

I'm having trouble creating a Google BigQuery view in python with the version 0.28 of the bq library that has come out about two weeks ago.  I'm quite certain the problem is on my side, something I'm missing, but I cannot find the issue.

Please be gentle, I don't ask lots of questions online but I'm quite stumped.
 I'm also not completely incompetent, here are some details:

I have my GOOGLE_APPLICATION_CREDENTIALS set correctly

All the other commands I've run against bq via python are fine

I've reviewed the
https://cloud.google.com/bigquery/docs/python-client-migration

I think the issue is around the "fix"
https://github.com/GoogleCloudPlatform/google-cloud-python/pull/4038
BigQuery: replaces table.create() with client.create_table() #4038

I've tried legacy vs. standard sql

I'm on python 2.7.12 (can't upgrade anytime soon, corporate version thing)

The issue?  The code in the second block below creates a TABLE, with no schema and no records.  It clearly should create a VIEW instead, right?

sudo pip install -Iv google-cloud-bigquery==0.27.0

from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data20'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset = bigquery_client.dataset(dataset_name)
table = dataset.table(view_name)
table.view_query = sqlQuery

table.create()

the above works fine, view created, great!

the below, only a table is created, no rows, no schema, yuck!

sudo pip uninstall google-cloud-bigquery

sudo pip install -Iv google-cloud-bigquery==0.28.0

from google.cloud import bigquery

project=None
dataset_name = 'my_dataset_id'
view_name = 'vw_dummy_data21'
sqlQuery = 'select record_id as id, UPPER(first_name) as first_name, UPPER(last_name) as last_name from [my_project_code:my_dataset_id.dummy_data13]'

bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True

table = bigquery.Table(table_ref)
bigquery_client.create_table(table)

Other links:

How can I create a new view in bigquery using the python API?

https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html

Any useful thoughts would be very much appreciated.

Thanks and best regards...Rich

Body:
Tim's answer was perfect, thank you very much.

Here is the final code:

from google.cloud import bigquery
bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_name)
table_ref = dataset_ref.table(view_name)
table = bigquery.Table(table_ref)
table.view_query = sqlQuery
table.view_use_legacy_sql = True

bigquery_client.create_table(table)


问:
Calculate radius distance using cos/sin including if/then and inner join
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

```<code>SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100
</code>```

How i can get this working? How to write technically correct query?

Thanks for any answers.

答:
I imagine that calculation with several conversions, cos and sin is rather heavy.

I'd suggest first selecting on a rectangle

```<code>where abs(latitude1-latitude2)<latdif
and abs(longitude1-longitude2)<longdif
</code>```

Then use that in either a temporary table, a view, or a subquery.

This is of cause not a complete answer to the question.

Body:
What i need:

I need to write some kind of IF statement inside query to pick different coordinates, if table1.business_id is equal to 1.

For example:

Pick lng and lat fields from table1 if table1.business_id = 1, else, pick lng and lat fields from table2.

Query:

SELECT *,
(3959 * acos(
   cos(radians('.$cords['result']['latitude'].')) *
   cos(radians(lat)) * cos( radians(lng) -
   radians('.$cords['result']['longitude'].')) +
   sin(radians('.$cords['result']['latitude'].')) *
   sin(radians(lat))
)) AS distance
   FROM table1 INNER JOIN table2 ON table2.id = table1.business_id
   WHERE type <> "industry" AND '.$query.'
   HAVING distance < '.$radius.'
   ORDER BY distance LIMIT 100

How i can get this working? How to write technically correct query?

Thanks for any answers.

Body:
I imagine that calculation with several conversions, cos and sin is rather heavy.

I'd suggest first selecting on a rectangle

where abs(latitude1-latitude2)<latdif
and abs(longitude1-longitude2)<longdif

Then use that in either a temporary table, a view, or a subquery.

This is of cause not a complete answer to the question.


问:
Python code performance on big data os.path.getsize
Below is my code to get file size in ascending order.

```<code>def Create_Files_Structure(directoryname):
   for path, subdirs, files in os.walk(directoryname,followlinks=False):
        subdirs[:] = [d for d in subdirs if not d[0] == '.']
        try:
           files_list.extend([(os.path.join(path, file),os.path.getsize(os.path.join(path, file))) for file in files ])
        except Exception as e:
            print()
   files_list.sort(key=lambda s: s[1], reverse=True)
   for pair in files_list:
     print(pair)
   print(len(files_list))

start=time.time()
Create_Files_Structure("/home/<username>")
end=time.time()
print(end-start)
</code>```

This code is working however performance is slow if size of a directory is in TB or PB. Any suggestion to improve the code to get faster result please.

答:
Nice Question Try This :

```<code>import time, os

def create_files_structuredire_2(ctoryname):

    files_list = []
    counter = 0

    for dirpath, _, filenames in os.walk(ctoryname):

        for items in filenames:

            file_full_path = os.path.abspath(os.path.join(dirpath, items))
            get_size = os.path.getsize(file_full_path)
            files_list.append((file_full_path, get_size))
            counter += 1

    files_list.sort(key=lambda s: s[1], reverse=True)
    [print(f) for f in files_list]
    print(counter)

start = time.time()
create_files_structuredire_2("your_target_folder")
end = time.time()
print(end-start)
</code>```

NOTE : your time is 0.044736385345458984, my time is 0.001501321792602539 !!!!!!

Good Luck ...

Body:
Below is my code to get file size in ascending order.

def Create_Files_Structure(directoryname):
   for path, subdirs, files in os.walk(directoryname,followlinks=False):
        subdirs[:] = [d for d in subdirs if not d[0] == '.']
        try:
           files_list.extend([(os.path.join(path, file),os.path.getsize(os.path.join(path, file))) for file in files ])
        except Exception as e:
            print()
   files_list.sort(key=lambda s: s[1], reverse=True)
   for pair in files_list:
     print(pair)
   print(len(files_list))

start=time.time()
Create_Files_Structure("/home/<username>")
end=time.time()
print(end-start)

This code is working however performance is slow if size of a directory is in TB or PB. Any suggestion to improve the code to get faster result please.

Body:
Nice Question Try This :

import time, os

def create_files_structuredire_2(ctoryname):

    files_list = []
    counter = 0

    for dirpath, _, filenames in os.walk(ctoryname):

        for items in filenames:

            file_full_path = os.path.abspath(os.path.join(dirpath, items))
            get_size = os.path.getsize(file_full_path)
            files_list.append((file_full_path, get_size))
            counter += 1

    files_list.sort(key=lambda s: s[1], reverse=True)
    [print(f) for f in files_list]
    print(counter)

start = time.time()
create_files_structuredire_2("your_target_folder")
end = time.time()
print(end-start)

NOTE : your time is 0.044736385345458984, my time is 0.001501321792602539 !!!!!!

Good Luck ...


问:
Adjusting the Xcode iPhone simulator scale and size
Is there anyway to make the iOS simulator for iPhone 5 in Xcode, be the actual size of the iPhone 5. I'm getting a huge display and things seemed to be scaled.</p>

答:
Specific to Xcode 9.1:

You can refere to @Krunal's answer above or follow below steps

its bit tricky to adjust Simulator size.

If you want to zoom your simulator screen follow below steps :

Goto Window->Uncheck Show Device Bezels

Goto Window->select zoom

after doing this you can resize your simulator by dragging edges of simulator.

Pixel Accurate : Its to display your simulator in same size as Physical device pixels, if your screen size doesn't have enough resolution to cover dimension it would not enable Pixel Accurate option.

Alternate is change simulator to landscape mode by clicking ⌘ + → ,then you could click ⌘ + 2 to select Pixel Accurate option (make sure you have disable Show Device Bezels to reduce size.


问:
NSLocalizedString - Thread 1: EXEC_BAD_ACCESS with String.localizedStringWithFormat
I tried to make a notification with some localized variables. In the simulator, everything works without an error - even the notification shows up as it should, but if I test it on an iPhone, the app crashes.

```<code>    func getContent(fromName: String, andDue: String, andAmount: Double) -> UNMutableNotificationContent {
        let currency = self.appDelegate.settings.getShortCurrency() // standard währung aus dem System holen
        let content = UNMutableNotificationContent()

        content.subtitle = NSLocalizedString("REMINDERTITLE", comment: "Reminder: some payments are overdue...")

    // Error in this line:
    content.body = String.localizedStringWithFormat(NSLocalizedString("REMINDERTEXT", comment: "Hey, %@'s payment from %@ %@ is overdue since %@! Do you want to send him a reminder message?"), fromName, andAmount, currency, andDue)

        content.badge = 1
        content.sound = UNNotificationSound(named: "droppingCoin.wav")

        return content
    }
</code>```

The error is:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x4084900000000000)

in this line:

```<code>content.body = String.localizedStringWithFormat(NSLocalizedString("REMINDERTEXT", comment: "Hey, %@'s payment from %@ %@ is overdue since %@! Do you want to send him a reminder message?"), fromName, andAmount, currency, andDue)
</code>```

The comment text is the actual localized text value defined in the .strings file.

Thanks in advance!

答: You're using the wrong format specifier for andAmount. andAmount is a double and not an object, so use %f instead of %@.</p>

Body:
I tried to make a notification with some localized variables. In the simulator, everything works without an error - even the notification shows up as it should, but if I test it on an iPhone, the app crashes.

    func getContent(fromName: String, andDue: String, andAmount: Double) -> UNMutableNotificationContent {
        let currency = self.appDelegate.settings.getShortCurrency() // standard währung aus dem System holen
        let content = UNMutableNotificationContent()

        content.subtitle = NSLocalizedString("REMINDERTITLE", comment: "Reminder: some payments are overdue...")

    // Error in this line:
    content.body = String.localizedStringWithFormat(NSLocalizedString("REMINDERTEXT", comment: "Hey, %@'s payment from %@ %@ is overdue since %@! Do you want to send him a reminder message?"), fromName, andAmount, currency, andDue)

        content.badge = 1
        content.sound = UNNotificationSound(named: "droppingCoin.wav")

        return content
    }

The error is:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x4084900000000000)

in this line:

content.body = String.localizedStringWithFormat(NSLocalizedString("REMINDERTEXT", comment: "Hey, %@'s payment from %@ %@ is overdue since %@! Do you want to send him a reminder message?"), fromName, andAmount, currency, andDue)

The comment text is the actual localized text value defined in the .strings file.

Thanks in advance!


问:
Static data memory limit in C++ application
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

```<code>char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}
</code>```

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?

答:
Wanted to know what is the static data memory limit?

Platform-specific. You haven't specified a platform (OS, compiler, version), so no-one can possibly tell you. It's probably fine though.

What can be the quick fix for this code?

The quick fix is indeed to make the buffer static.

The good fix is to rewrite the function as

```<code>char *modify(char *out, size_t outsz) {
    // ...
    return out;
}
</code>```

(returning the input is just to simplify reusing the new function in existing code).

Is it a good practice to make the variable targetString static?

No.  Sometimes it's the best you can do, but it has a number of problems:

The buffer is always the same size, and always using ~68Kb of memory and/or address space for no good reason. You can't use a bigger one in some contexts, and a smaller one in others. If you really have to memset the whole thing, this incurs a speed penalty in situations where the buffer could be much smaller.

Using static (or global) variables breaks re-entrancy. Simple example: code like

```<code>printf("%s,%s\n", str_Modify(1), str_Modify(2));
</code>```

cannot work sanely, because the second invocation overwrites the first (compare strtok, which can't be used to interleave the tokenizing of two different strings, because it has persistent state).

Since it isn't re-entrant, it also isn't thread-safe, in case you use multiple threads. It's a mess.

Body:
Someone has written function in our C++ application and is already in the production and I don't know why it's not crashing the application yet. Below is the code.

char *str_Modify()
{
    char buffer[70000] = { 0 };
    char targetString[70000] = { 0 };

    memset(targetString, '\0', sizeof(targetString));

    ...
    ...
    ...
    return targetString;
}

As you can see, the function is returning the address of a local variable and the allocated memory will be released once the function returns.
My question

Wanted to know what is the static data memory limit?

What can be the quick fix for this code? Is it a good practice to make the variable targetString static?

Body:
Wanted to know what is the static data memory limit?

Platform-specific. You haven't specified a platform (OS, compiler, version), so no-one can possibly tell you. It's probably fine though.

What can be the quick fix for this code?

The quick fix is indeed to make the buffer static.

The good fix is to rewrite the function as

char *modify(char *out, size_t outsz) {
    // ...
    return out;
}

(returning the input is just to simplify reusing the new function in existing code).

Is it a good practice to make the variable targetString static?

No.  Sometimes it's the best you can do, but it has a number of problems:

The buffer is always the same size, and always using ~68Kb of memory and/or address space for no good reason. You can't use a bigger one in some contexts, and a smaller one in others. If you really have to memset the whole thing, this incurs a speed penalty in situations where the buffer could be much smaller.

Using static (or global) variables breaks re-entrancy. Simple example: code like

printf("%s,%s\n", str_Modify(1), str_Modify(2));

cannot work sanely, because the second invocation overwrites the first (compare strtok, which can't be used to interleave the tokenizing of two different strings, because it has persistent state).

Since it isn't re-entrant, it also isn't thread-safe, in case you use multiple threads. It's a mess.


问:
data duplicating when use custom controller in laravel's voyager admin panel
I use laravel 5.4 and voyager admin panel. There's module I created called recipes. I created database table, model and CUSTOM controller and views for this module. I also created BREAD, and indicated there my custom controller. the problem is the when I fill form and submit it, data been duplicated in table, I have 2 identical rows in my table every time I create the item. I think the problem is that it sends 2 requests, one of requests is from my custom route and controller, and another one is from voyager itself. but don't know how to fix it.

print screen from my BREAD

my routes

```<code>Route::group(['prefix' => 'admin', 'middleware' => ['admin']], function () {

   \Voyager::routes(); //voyager routes

   // routes for my custom module
   // I can comment this routes, but result is the same
   Route::resource('/recipes', 'Admin\RecipesController');

});
</code>```

my controller

```<code>public function store(Request $request)
{
    $recipe = Recipe::create($request->except(['modules']));
    return redirect()
        ->route("recipes.index")
        ->with([
            'message'    => __('voyager.generic.successfully_added_new')." recipe",
            'alert-type' => 'success'
        ]);
}
</code>```

any idea?

答: the issue was because of form element class form-edit-add, as it seems there was event bound to this class. I removed it and now it works fine

Body:
I use laravel 5.4 and voyager admin panel. There's module I created called recipes. I created database table, model and CUSTOM controller and views for this module. I also created BREAD, and indicated there my custom controller. the problem is the when I fill form and submit it, data been duplicated in table, I have 2 identical rows in my table every time I create the item. I think the problem is that it sends 2 requests, one of requests is from my custom route and controller, and another one is from voyager itself. but don't know how to fix it.

print screen from my BREAD

my routes

Route::group(['prefix' => 'admin', 'middleware' => ['admin']], function () {

   \Voyager::routes(); //voyager routes

   // routes for my custom module
   // I can comment this routes, but result is the same
   Route::resource('/recipes', 'Admin\RecipesController');

});

my controller

public function store(Request $request)
{
    $recipe = Recipe::create($request->except(['modules']));
    return redirect()
        ->route("recipes.index")
        ->with([
            'message'    => __('voyager.generic.successfully_added_new')." recipe",
            'alert-type' => 'success'
        ]);
}

any idea?


问:
Visual Studio class/file templates: Is there a way to change their content automatically per project/solution?
I've updated my default templates in Visual Studio for classes, interfaces, code files, etc.  I removed the default namespaces and added a copyright header blurb.

Is there a way to use a variable or something in the template so I don't have to zip/unzip and re-run the vs installer to change the copyright header? (I'm a consultant, the code-owner isn't always me or my company).

答: You can get the complete example implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample</p>

OwnerDisplayName: Zachary Yates