text:
Q: Msp430 I²C single write-read example I've been trying to use an I²C bus between a MSP430G2553 launchpad and ITG-3200 gyroscope breakout. Here is the Launchpad datasheet and user guide and the ITG-3200 datasheet. The ITG-3200 uses a repeated start to read from a specific register. But not necessarily.  After checking the example code on the Arduino (I checked the data flow on buses with an oscilloscope) I realised that even with a Stop-Start condition it should work. What I'm trying to do is to accomplish this on the MSP Launchpad.
I'm using two I²C examples provided from TI msp430g2xx3_uscib0_i2c_04 (single read) and msp430g2xx3_uscib0_i2c_06 (single write). I combined these two sets of code and came up with code for my ITG-3200 which uses a write operation followed by a read for reading it's registers. Here is the code:
#include <msp430.h>

int TXByteCtr = 1;
unsigned char PRxData;                     // Pointer to RX data
int Rx = 0;
unsigned char WHO_AM_I = 0x00;

void init_I2C(void);
void Transmit(void);
void Receive(void);
int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
  P1SEL |= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  P1SEL2|= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  init_I2C();
  while(1){
  //Transmit process
  Rx = 0;
  Transmit();
  while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent

  //Receive process
  Rx = 1;
  Receive();
  while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
  }
}

//-------------------------------------------------------------------------------
// The USCI_B0 data ISR is used to move received data from the I2C slave
// to the MSP430 memory. It is structured such that it can be used to receive
//-------------------------------------------------------------------------------
#pragma vector = USCIAB0TX_VECTOR
__interrupt void USCIAB0TX_ISR(void)
{
  if(Rx == 1){                              // Master Recieve?
  PRxData = UCB0RXBUF;                       // Get RX data
  __bic_SR_register_on_exit(CPUOFF);        // Exit LPM0
  }

  else{                                     // Master Transmit
  if (TXByteCtr)                            // Check TX byte counter
  {
      UCB0TXBUF = WHO_AM_I;                     // Load TX buffer
      TXByteCtr--;                            // Decrement TX byte counter
  }
  else
  {
      UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
      IFG2 &= ~UCB0TXIFG;                     // Clear USCI_B0 TX int flag
      __bic_SR_register_on_exit(CPUOFF);      // Exit LPM0
  }
 }

}

void init_I2C(void) {
  _DINT();
  IE2 |= UCB0RXI             //Enable RX interrupt
  IE2 |= UCB0TXIE;                          // Enable TX interrupt
  while (UCB0CTL1 & UCTXSTP);               // Ensure stop condition got sent
  UCB0CTL1 |= UCSWRST;                      // Enable SW reset
  UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC;     // I2C Master, synchronous mode
  UCB0CTL1 = UCSSEL_2 + UCSWRST;            // Use SMCLK, keep SW reset
  UCB0BR0 = 12;                             // fSCL = SMCLK/12 = ~100kHz
  UCB0BR1 = 0;
  UCB0I2CSA = 0x69;                         // Slave Address is 069h
  UCB0CTL1 &= ~UCSWRST;                     // Clear SW reset, resume operation
}

void Transmit(void){
    while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
    UCB0CTL1 |= UCTR + UCTXSTT;             // I2C TX, start condition
    __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts
}
void Receive(void){
   UCB0CTL1 &= ~UCTR ;                  // Clear UCTR
   while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
    UCB0CTL1 |= UCTXSTT;                    // I2C start condition
    while (UCB0CTL1 & UCTXSTT);             // Start condition sent?
    UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
    __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts
}

I don't really know why is this happening but SDA and SCL clocks keeps locking to 0V. I'm sure about the circuit (full with pull-up resistors) because that is working on an Arduino. Can you point out what seems to be the problem here?
Edit: It is better if i put the two examples from TI resource here aswell.
It is better if i give the two example of TI here. Here is the master RX single byte from the slave: ( msp430g2xx3_uscib0_i2c_04.c )
 /* --COPYRIGHT--,BSD_EX
     * Copyright (c) 2012, Texas Instruments Incorporated
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * *  Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * *  Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     *
     * *  Neither the name of Texas Instruments Incorporated nor the names of
     *    its contributors may be used to endorse or promote products derived
     *    from this software without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
     * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
     * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     *******************************************************************************
     *
     *                       MSP430 CODE EXAMPLE DISCLAIMER
     *
     * MSP430 code examples are self-contained low-level programs that typically
     * demonstrate a single peripheral function or device feature in a highly
     * concise manner. For this the code may rely on the device's power-on default
     * register values and settings such as the clock configuration and care must
     * be taken when combining code from several examples to avoid potential side
     * effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
     * for an API functional library-approach to peripheral configuration.
     *
     * --/COPYRIGHT--*/
    //******************************************************************************
    //  MSP430G2xx3 Demo - USCI_B0 I2C Master RX single bytes from MSP430 Slave
    //
    //  Description: This demo connects two MSP430's via the I2C bus. The master
    //  reads from the slave. This is the master code. The data from the slave
    //  transmitter begins at 0 and increments with each transfer. The received
    //  data is in R5 and is checked for validity. If the received data is
    //  incorrect, the CPU is trapped and the P1.0 LED will stay on. The USCI_B0
    //  RX interrupt is used to know when new data has been received.
    //  ACLK = n/a, MCLK = SMCLK = BRCLK = default DCO = ~1.2MHz
    //
    //                                /|\  /|\
    //               MSP430G2xx3      10k  10k     MSP430G2xx3
    //                   slave         |    |        master
    //             -----------------   |    |  -----------------
    //           -|XIN  P1.7/UCB0SDA|<-|---+->|P1.7/UCB0SDA  XIN|-
    //            |                 |  |      |                 | 32kHz
    //           -|XOUT             |  |      |             XOUT|-
    //            |     P1.6/UCB0SCL|<-+----->|P1.6/UCB0SCL     |
    //            |                 |         |             P1.0|--> LED
    //
    //  D. Dang
    //  Texas Instruments Inc.
    //  February 2011
    //   Built with CCS Version 4.2.0 and IAR Embedded Workbench Version: 5.10
    //******************************************************************************
    #include <msp430.h>

    unsigned char RXData;
    unsigned char RXCompare;

    int main(void)
    {
      WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
      P1SEL |= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
      P1SEL2|= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
      UCB0CTL1 |= UCSWRST;                      // Enable SW reset
      UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC;     // I2C Master, synchronous mode
      UCB0CTL1 = UCSSEL_2 + UCSWRST;            // Use SMCLK, keep SW reset
      UCB0BR0 = 12;                             // fSCL = SMCLK/12 = ~100kHz
      UCB0BR1 = 0;
      UCB0I2CSA = 0x069;                        // Slave Address is 048h
      UCB0CTL1 &= ~UCSWRST;                     // Clear SW reset, resume operation
      IE2 |= UCB0RXIE;                          // Enable RX interrupt
      RXCompare = 0;                            // Used to check incoming data

      while (1)
      {
        while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
        UCB0CTL1 |= UCTXSTT;                    // I2C start condition
        while (UCB0CTL1 & UCTXSTT);             // Start condition sent?
        UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
        __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts

      }
    }

    // USCI_B0 Data ISR
    #pragma vector = USCIAB0TX_VECTOR
    __interrupt void USCIAB0TX_ISR(void)
    {
      RXData = UCB0RXBUF;                       // Get RX data
      __bic_SR_register_on_exit(CPUOFF);        // Exit LPM0
    }

And here is the Master TX single byte to the slave ( msp430g2xx3_uscib0_i2c_04.c )
/* --COPYRIGHT--,BSD_EX
 * Copyright (c) 2012, Texas Instruments Incorporated
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * *  Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * *  Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *******************************************************************************
 *
 *                       MSP430 CODE EXAMPLE DISCLAIMER
 *
 * MSP430 code examples are self-contained low-level programs that typically
 * demonstrate a single peripheral function or device feature in a highly
 * concise manner. For this the code may rely on the device's power-on default
 * register values and settings such as the clock configuration and care must
 * be taken when combining code from several examples to avoid potential side
 * effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
 * for an API functional library-approach to peripheral configuration.
 *
 * --/COPYRIGHT--*/
//******************************************************************************
//  MSP430G2xx3 Demo - USCI_B0 I2C Master TX single bytes to MSP430 Slave
//
//  Description: This demo connects two MSP430's via the I2C bus. The master
//  transmits to the slave. This is the master code. It continuously
//  transmits 00h, 01h, ..., 0ffh and demonstrates how to implement an I2C
//  master transmitter sending a single byte using the USCI_B0 TX interrupt.
//  ACLK = n/a, MCLK = SMCLK = BRCLK = default DCO = ~1.2MHz
//
//                                /|\  /|\
//               MSP430G2xx3      10k  10k     MSP430G2xx3
//                   slave         |    |        master
//             -----------------   |    |  -----------------
//           -|XIN  P1.7/UCB0SDA|<-|---+->|P1.7/UCB0SDA  XIN|-
//            |                 |  |      |                 |
//           -|XOUT             |  |      |             XOUT|-
//            |     P1.6/UCB0SCL|<-+----->|P1.6/UCB0SCL     |
//            |                 |         |                 |
//
//  D. Dang
//  Texas Instruments Inc.
//  February 2011
//   Built with CCS Version 4.2.0 and IAR Embedded Workbench Version: 5.10
//******************************************************************************
#include <msp430.h>

unsigned char TXData;
unsigned char TXByteCtr;

int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
  P1SEL |= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  P1SEL2|= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  UCB0CTL1 |= UCSWRST;                      // Enable SW reset
  UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC;     // I2C Master, synchronous mode
  UCB0CTL1 = UCSSEL_2 + UCSWRST;            // Use SMCLK, keep SW reset
  UCB0BR0 = 12;                             // fSCL = SMCLK/12 = ~100kHz
  UCB0BR1 = 0;
  UCB0I2CSA = 0x69;                         // Slave Address is 048h
  UCB0CTL1 &= ~UCSWRST;                     // Clear SW reset, resume operation
  IE2 |= UCB0TXIE;                          // Enable TX interrupt

  TXData = 0x00;                            // Holds TX data

  while (1)
  {
    TXByteCtr = 1;                          // Load TX byte counter
    while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
    UCB0CTL1 |= UCTR + UCTXSTT;             // I2C TX, start condition
    __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts
                                            // Remain in LPM0 until all data
                                            // is TX'd
    TXData++;                               // Increment data byte
  }
}

//------------------------------------------------------------------------------
// The USCIAB0TX_ISR is structured such that it can be used to transmit any
// number of bytes by pre-loading TXByteCtr with the byte count.
//------------------------------------------------------------------------------
#pragma vector = USCIAB0TX_VECTOR
__interrupt void USCIAB0TX_ISR(void)
{
  if (TXByteCtr)                            // Check TX byte counter
  {
    UCB0TXBUF = TXData;                     // Load TX buffer
    TXByteCtr--;                            // Decrement TX byte counter
  }
  else
  {
    UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
    IFG2 &= ~UCB0TXIFG;                     // Clear USCI_B0 TX int flag
    __bic_SR_register_on_exit(CPUOFF);      // Exit LPM0
  }
}

A: Here is the code that reading a single byte via I²C. Do not forget to connect 2 pull-up resistors on P1.6 and P1.7. These are the SDA and SCL lines on I2C bus.
#include <msp430g2553.h>

int TXByteCtr;
unsigned char PRxData;
int Rx = 0;
char WHO_AM_I = 0x00;

char itgAddress = 0x69;

void init_I2C(void);
void Transmit(void);
void Receive(void);

int main(void)
{
  WDTCTL = WDTPW + WDTHOLD;                 // Stop WDT
  P1SEL |= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  P1SEL2|= BIT6 + BIT7;                     // Assign I2C pins to USCI_B0
  init_I2C();

  while(1){
      //Transmit process
      Rx = 0;
      TXByteCtr = 1;
      Transmit();
      //Receive process
      Rx = 1;
      Receive();
  }
}

//-------------------------------------------------------------------------------
// The USCI_B0 data ISR is used to move received data from the I2C slave
// to the MSP430 memory. It is structured such that it can be used to receive
//-------------------------------------------------------------------------------
#pragma vector = USCIAB0TX_VECTOR
__interrupt void USCIAB0TX_ISR(void)
{
  if(Rx == 1){                              // Master Recieve?
      PRxData = UCB0RXBUF;                       // Get RX data
      __bic_SR_register_on_exit(CPUOFF);        // Exit LPM0
  }

  else{                                     // Master Transmit
      if (TXByteCtr)                            // Check TX byte counter
        {
          UCB0TXBUF = WHO_AM_I;                     // Load TX buffer
          TXByteCtr--;                            // Decrement TX byte counter
        }
        else
        {
          UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
          IFG2 &= ~UCB0TXIFG;                     // Clear USCI_B0 TX int flag
          __bic_SR_register_on_exit(CPUOFF);      // Exit LPM0
        }
 }

}
void init_I2C(void) {
      UCB0CTL1 |= UCSWRST;                      // Enable SW reset
      UCB0CTL0 = UCMST + UCMODE_3 + UCSYNC;     // I2C Master, synchronous mode
      UCB0CTL1 = UCSSEL_2 + UCSWRST;            // Use SMCLK, keep SW reset
      UCB0BR0 = 12;                             // fSCL = SMCLK/12 = ~100kHz
      UCB0BR1 = 0;
      UCB0I2CSA = itgAddress;                         // Slave Address is 069h
      UCB0CTL1 &= ~UCSWRST;                     // Clear SW reset, resume operation
      IE2 |= UCB0RXIE + UCB0TXIE;               //Enable RX and TX interrupt
}

void Transmit(void){
    while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
    UCB0CTL1 |= UCTR + UCTXSTT;             // I2C TX, start condition
    __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts
}
void Receive(void){
        while (UCB0CTL1 & UCTXSTP);             // Ensure stop condition got sent
        UCB0CTL1 &= ~UCTR ;                     // Clear UCTR
        UCB0CTL1 |= UCTXSTT;                    // I2C start condition
        while (UCB0CTL1 & UCTXSTT);             // Start condition sent?
        UCB0CTL1 |= UCTXSTP;                    // I2C stop condition
        __bis_SR_register(CPUOFF + GIE);        // Enter LPM0 w/ interrupts
}


text:
Q: Flutter Convert from QuerySnapshot to a Future >> How do I return a QuerySnapshot as a Future >>  ?
Code snippet:
Future <List<Map<dynamic, dynamic>>>() {
List<Map<dynamic,dynamic>> list;
.....

.....
QuerySnapshot collectionSnapshot = await collectionRef.getDocuments();

list = collectionSnapshot.documents;  <--- ERROR
return list;

}

I think I need to use a Map of but couldn't get around it to work.

A: collectionSnapshot.documents return List and not List types, you will need to convert List of documentsnapshots to List<Map<dynamic, dynamic>>.
My be something like this:
Future <List<Map<dynamic, dynamic>>> getCollection() async{
List<DocumentSnapshot> templist;
List<Map<dynamic, dynamic>> list = new List();
CollectionReference collectionRef = Firestore.instance.collection("path");
QuerySnapshot collectionSnapshot = await collectionRef.getDocuments();

templist = collectionSnapshot.documents; // <--- ERROR

list = templist.map((DocumentSnapshot docSnapshot){
  return docSnapshot.data;
}).toList();

return list;
}

A: Ganapat's answer worked out for me with a few minor changes.
Future <List<Map<dynamic, dynamic>>> getCollection() async{
List<DocumentSnapshot> templist;
List<Map<dynamic, dynamic>> list = new List();
CollectionReference collectionRef = Firestore.instance.collection("path");
QuerySnapshot collectionSnapshot = await collectionRef.get(); // <--- This method is now get().

templist = collectionSnapshot.documents; // <--- ERROR

list = templist.map((DocumentSnapshot docSnapshot){
  return docSnapshot.data() as Map<Dynamic,Dynamic>; // <--- Typecast this.
}).toList();

return list;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Link winmm.lib to CLion using CMake I am trying to play music in my C++ project, but I'm getting undefined reference error. I know it was already answered here, but that doesn't help me at all:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I know how to fix it in VisualStudio, by adding a reference to winmm.lib to my linker. Is there a way how to do it in CLion? I tried adding it to my CMake list, but it still doesn't work, because I don't really know how to do that.
# Path to WinMM.Lib
link_directories(C:\\Program Files \(x86\)\\Windows Kits\\10\\Lib\\10.0.18362.0\\um\\x64)

# Link to GLFW, GLEW and OpenGL
target_link_libraries(template PUBLIC
        ${GLFW_LIBRARIES}
        ${GLEW_LIBRARIES}
        ${OPENGL_LIBRARIES}
        ${winMM.Lib})

A: As @arrowd said, winMM isn't a variable,so CMake file should look like this.
# Link to GLFW, GLEW and OpenGL
target_link_libraries(template PUBLIC
        ${GLFW_LIBRARIES}
        ${GLEW_LIBRARIES}
        ${OPENGL_LIBRARIES}
        winMM.Lib)


text:
Q: readline() in pySerial sometimes captures incomplete values being streamed from Arduino serial port Every one second, Arduino prints (in serial) 'current time in milliseconds and Hello world'. On serial monitor, the output looks fine.
But in pySerial, sometimes there is line break at the middle of string.
313113   Hel
lo world
314114   Hello world
315114   Hello world

My python code is as:
import serial
import time
ser = serial.Serial(port='COM4',
                    baudrate=115200,
                    timeout=0)

while True:
   str = ser.readline()         # read complete line
   str = str.decode()           # decode byte str into Unicode
   str = str.rstrip()

   if str != "":
      print(str)
   time.sleep(0.01)

What am I doing wrong?
My configuration:

Python       3.7
  pySerial     3.4
  Board        Arduino Mega

A: The problem definitely seems to be caused by very fast reads where the data is read when the serial output from the Arduino hasn't finished sending full data.
Now with this fix, the pySerial will be able to receive the complete data and no data is missed. The main benefit is that it can be used for any type of data length and the sleep time is quite low.
I have fixed this issue with code below.
# This code receives data from serial device and makes sure
# that full data is received.

# In this case, the serial data always terminates with \n.
# If data received during a single read is incomplete, it re-reads
# and appends the data till the complete data is achieved.

import serial
import time
ser = serial.Serial(port='COM4',
                    baudrate=115200,
                    timeout=0)

print("connected to: " + ser.portstr)

while True:                             # runs this loop forever
    time.sleep(.001)                    # delay of 1ms
    val = ser.readline()                # read complete line from serial output
    while not '\\n'in str(val):         # check if full data is received.
        # This loop is entered only if serial read value doesn't contain \n
        # which indicates end of a sentence.
        # str(val) - val is byte where string operation to check `\\n`
        # can't be performed
        time.sleep(.001)                # delay of 1ms
        temp = ser.readline()           # check for serial output.
        if not not temp.decode():       # if temp is not empty.
            val = (val.decode()+temp.decode()).encode()
            # requrired to decode, sum, then encode because
            # long values might require multiple passes
    val = val.decode()                  # decoding from bytes
    val = val.strip()                   # stripping leading and trailing spaces.
    print(val)


text:
Q: How To Make Something Run Every Time User Opens To Specific Page Swift I'm currently creating a game in Swift and Xcode. So, basically there is a tab bar leading to 3 different pages: Home, game page, and settings/themes. I am currently trying to create some themes for the app. I'm asking this question because I want to create a piece of code that runs every time a user opens to another page that checks wether or not the theme has changed(and changes the theme if the theme needs to change).
Example: User opens app. Taps into settings from home page, and selects a 'rainbow' theme. Now when the user taps back into home, or game page, the theme should have changed, because the code that runs every time the user opens to specific page checked and found out the theme changed(and changed the theme). Any help would be appreciated

A: Write your function in a Base class and make your controllers inherit from that Base class. You'll be able to call that function from any controller that inherits from that class. And if you want to call the function automatically then call that function in viewDidLoad of Base class.
Call function on specific controllers

A: I could use the 'view did appear' function, like this:
   override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //code
   }


text:
Q: Most concise way to initialize a large 2D array You're probably chuckling away. I'm creating a large map for a Socket.IO based RPG I'm making. Is this stupid? I know I can create 2 dimensional arrays using 5 lines with code but I need the array to have different numbers in. For example, 0 = allowed to walk to, 1 = not allowed to walk to. Imagine the numbers to be very varied, 0s, 1s etc.
If there is a better way please let me know. Maybe a way to read from a text file or something?
var map = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
];

A: You can initialize the m x n empty matrix, then just store the coordinates of the 1s:
var ones = [[2,3], [5, 12], ...];

for(i=0;i<ones.length;i++)
    matrix[ones[i][0]][ones[i][1]] = 1;

Or just use a bitmap, as other suggested - canvas may help you.

A: One way to make your data more readable is to encode it as a string and "parse" it on the fly:
var map = ("\
----------------------------------1--------------- \
-------------------------------------------------- \
---1---------------------------------------------- \
-------------------------------------------------- \
-------------------------------------------------- \
-------------------------------------------------- \
-------------------------------------------------- \
⋮
-------------------------------------------------- \
--------------------------------------------------"
    .split(' ')
    .map(function(row) {
        return row.split('')
                  .map(function(cell) {
                      return {'-':0, '1':1}[cell];
                  });
    }));

A: As @sje387 mentioned, this couldn't be closer to the definition of "bit map". So you might want to store it as an image and retrieve pixels, but...
Take into account that the browser parses javascript arrays and turns them into an in-memory, fast representation. If you're coding a browser game, maybe reading bitmaps might be slower than having them as actual arrays, nicely minified into the meat of the game.
To this extent, what you might want to do is:

*

*Make a 1-bit bitmap (I think even MSPaint can make it). Save as bitmap.

*Code something that reads all the pixels of this bitmap (the bitmap format is very simple).

*Output a valid javascript array with the values of the pixels in the bitmap, into a file somewhere in your repository.

*Pipe this together in your build process, so that the final minified code has the bitmap in it as an array.

A: Well, if it contains only zeroes, then yes, it could be created in a much more concise way. But if gotta store data - you gotta store data. Arrays work fine for this purpose. As maps grow larger, you can employ more clever tricks for storing maps (for example, encode map data into a png image, or whatever).

A: Bitmaps may be somewhat messy.  Instead, make just a text file of zeros and ones and retrieve it via AJAX:
0000000010111111101010110110011
1111010011100101100101010101000
0001010101010101101001010101010
etc...

js:
var map;
var xhr = new XMLHttpRequest("GET", "map.txt", true);
xhr.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
        map = this.responseText.split("\n").map(function(line) {
            return this.split("");
        });
    }
}
xhr.send(null);

You can split on newlines to get an array of strings, then split each string to get an array of "characters".
You'll end up with an array of single-character strings, so you may want to iterate over the arrays and convert them all to numbers, but depending on the rest of your code, it may not be necessary.

A: You should also consider the possibility of using run-length encoding to store these kind of sparse data.


text:
Q: Calculating pow(double,2) gives a huge number (C) I'm trying to code a simulation of Pi calculating using multiple processes.
I have a function that generates random double x, y numbers from 1 to -1,
and when im trying to calculate whether x^2 + y^2 <= 1,
but the result is a huge number, and its always bigger than 1.
icpi.cpp (main file):
#include <mpi.h>
#include <iostream>
#include "main_header.h"
#include "dynamic.h"
using namespace std;

int main(int argc,char *argv[])
{

int numprocs, myid, i, root = 0, pointsInCircle = 0, pointsOutOfCircle = 0;
boolean pointInside = TRUE;
double point[DIMENSION], scatterTable[NUMBER_OF_SLAVES][DIMENSION], pi, t1, t2;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
MPI_Status status;
srand(time(NULL));
t1 = MPI_Wtime();
printf("Trying to scatter..\n");
fflush(stdout);
MPI_Scatter(&scatterTable[0][0], DIMENSION, MPI_DOUBLE,     // Master process sends the first tasks to the slaves.
    &point[0], DIMENSION, MPI_DOUBLE, root, MPI_COMM_WORLD);
printf("Scatter successful\n");
fflush(stdout);
if (myid == 0) {
    for (i = 0; i < TOTAL_NUM_OF_POINTS; i++) {
        MPI_Recv(&pointInside, 1, MPI_INT, MPI_ANY_SOURCE, 0, MPI_COMM_WORLD, &status);
        if (pointInside) {
            pointsInCircle++;
            printf("point inside\n");
            fflush(stdout);
        }
        else {
            pointsOutOfCircle++;
            printf("point outside\n");
            fflush(stdout);
        }
        point[0] = randomPoint();       //  X component
        point[1] = randomPoint();       //  Y component
        printf("x = %f, y = %f\n", point[0], point[1]);
        fflush(stdout);
        MPI_Send(&point[DIMENSION], 2, MPI_DOUBLE, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
    }
    point[0] = point[1] = END_OF_PI_CALC;
    for (i = 0; i < NUMBER_OF_SLAVES; i++)
        MPI_Send(&point[DIMENSION], 2, MPI_DOUBLE, status.MPI_SOURCE, 0, MPI_COMM_WORLD);
    t2 = MPI_Wtime();
    pi = calculatePi(pointsInCircle, pointsOutOfCircle);
    printf("Pi = %f.\n Time to calculate: %f", pi, (t2-t1));
}
else {
    while (point[0] != END_OF_PI_CALC || point[1] != END_OF_PI_CALC) {
        pointInside = withinCircle(point[0], point[1]);
        MPI_Send(&pointInside, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
        MPI_Recv(&point[DIMENSION], 2, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,     &status);
    }
}

if (myid == 0)
    MPI_Finalize();
return 0;
}

dynamic.cpp:
#include "dynamic.h"
#include <stdio.h>;
#include <math.h>
boolean withinCircle(double x, double y) {
    double result = (pow(x,(double)2) + pow(y, (double)2));
    printf("result = %f", result);
    fflush(stdout);
    if (result <= 1)
        return TRUE;
    return FALSE;
}

double randomPoint() {
    double range = (RANDOM_MAX - RANDOM_MIN);
    double div = RAND_MAX / range;
    return RANDOM_MIN + (rand() / div);
}

double calculatePi(int pointsWithin, int pointsOutside) {
    double pi = (pointsWithin / pointsOutside) * 4;
    return pi;
}

dynamic.h:
#ifndef DYNAMIC_H
#define DYNAMIC_H

#include "main_header.h"
#define TOTAL_NUM_OF_POINTS 20000
#define NUM_OF_POINTS_TO_SEND 1
#define RANDOM_MAX 1
#define RANDOM_MIN -1
#define NUMBER_OF_SLAVES 3
#define DIMENSION 2
#define END_OF_PI_CALC 2

boolean withinCircle(double x, double y);

double randomPoint();

double calculatePi(int pointsWithin, int pointsOutside);

#endif DYNAMIC_H

main_header.h:
#ifndef MAIN_H
#define MAIN_H

#include <time.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

typedef int boolean;        //  Defines a boolean datatype.

#endif MAIN_H

example result from the wmpiexec:
x = -0.944151, y = 0.389386
result = 17134570711043240115048918967982918960341742262641887592820622432866394633762913354831186160392586118427086670840176838705152.000000
point outside

(I know the result of the actual calculation might not be right, its just an example)

A: double calculatePi(int pointsWithin, int pointsOutside) {
    double pi = (pointsWithin / pointsOutside) * 4;
    return pi;
}

This is wrong. What's happening is that you're doing an integer division and then multiplying by 4, and then casting it to a double. So you're getting floor behavior.
You need to cast either pointsWithin or pointsOutside to a double before you do the division.
(It's also the wrong formula, but that is another matter.)

A: I have misused MPI_Send and MPI_Recv, and now its calculating the power right.


text:
Q: Logging emails in SharePoint list We have a requirement on a project that the client would like to see all correspondence between them and their customers in a central location.
We though of using a sharepoint list. What is then the best way to get the emails into the sharepoint list?

A: There are a couple of ways to make it easy for users to store email in SharePoint. One way is to enable incoming email. The article Configure incoming e-mail (SharePoint Server 2010) on TechNet covers this in detail. This involves some environmental changes to setup email addresses that will be routed to your SharePoint server (e.g. Active Directory and/or Exchange) as well as configuring settings for the individual lists - the list settings are covered in the article Enable and configure e-mail support for a list or library. This works with both SharePoint 2007 and SharePoint 2010.
As you tagged the question with SharePoint 2010 an alternative would be to use SharePoint Workspace to allow users to drag and drop email from Outlook directly into the appropriate list or library but this does require licenses for Office 2010 or SharePoint Workspace 2010. Alternatively products such as Colligo provide this type of functionality for SharePoint 2007.

A: You can enable email on the list directly. The following comes directly from Ken Zheng's post on this subject.

SharePoint users can add content to
  discussion boards, announcements,
  calendars, libraries (document,
  picture and form) and blogs via email.
  By setting your list or library up to
  receive email, you can efficiently
  update the content of your site
  without having to navigate the
  SharePoint frontend.

*

*Login to your SharePoint site.

*Navigate to the list or document library you want to email to.

*Click Settings.

*Choose List Settings or Document Library Settings respectively.

*In the far right column, select Incoming Email Settings.

*Click Yes to allow items to be added through email and create an
  email address to which you will send
  the items.

*OPTIONAL: You can modify other Incoming Email Settings regarding
  attachments, messages, meeting
  invitations and security on this page,
  as well.

*When finished, click OK to complete the setup. Incoming email has now been
  enabled for your SharePoint list or
  library.

More posts on this subject.

A: Custom list cannot receive incoming emails unless you use some tool like http://anurasoftware.com/default.aspx


text:
Q: How to add a global state store in a Spring Cloud Stream application I'm trying to configure a global state store in a Spring Cloud Stream application but it fails with :
Exception in thread "svc-toa-app-datainteg-io-dev-fd2e1a47-0758-4b95-9b2e-022ca4df95ca-
StreamThread-1" org.apache.kafka.streams.errors.TopologyException: Invalid topology:
Topic is unknown to the topology. This may happen if different KafkaStreams instances of
the same application execute different Topologies. Note that Topologies are only identical if all operators are added in the same order.
Following the official documentation I added the following to configure the state store :
 @Bean
    public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
        return factoryBean -> {
            if (factoryBean.getStreamsConfiguration().getProperty(StreamsConfig.APPLICATION_ID_CONFIG)
                           .equals(applicationId)) {
                try {

                    final var keyValueStore = new KeyValueStoreBuilder<>(
                        Stores.inMemoryKeyValueStore(PRODUCT_INFO_STORE),
                        productInfoKeySerde(),
                        productInfoValueSerde(),
                        Time.SYSTEM
                    );

                    final StreamsBuilder streamsBuilder = factoryBean.getObject();

                    streamsBuilder.addGlobalStore(
                        keyValueStore.withLoggingDisabled(),
                        productInfoTopic,
                        Consumed.with(productInfoKeySerde(), productInfoValueSerde()),
                        ProductGlobalStateStoreProcessor::new
                    );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }

And I have a processor where I want to use the state store :
public class ProductGlobalStateStoreProcessor implements Processor<ProductInfoKey, ProductInfo, Void, Void> {
    KeyValueStore<ProductInfoKey, ProductInfo> stateStore;

    @Override
    public void init(ProcessorContext<Void, Void> context) {
        stateStore = context.getStateStore(ProductGlobalStateStoreConfiguration.PRODUCT_INFO_STORE);
    }

    @Override
    public void process(Record<ProductInfoKey, ProductInfo> record) {
        stateStore.put(record.key(), record.value());
    }
}

I'm a little lost on what I'm missing, I've tried to add a gktable binding in the properties but it does not change anything.

A: I've found my issue : another instance was running with the same application id.
Since I added a new source node for the global state store, topologies were different and that's why it would not start.


text:
Q: azure logic app not able to retrieve who is the approver after approving the mail(UserEmailAddress- showing Null) I have created a flow using logic apps where once the owner approves the mail I need to know who approved that mail. While using normal my account I am able to retrieve the user who approved the mail but while using the service account am not able to retrieve the values. All the values its showing as null while using the service account.
How do I get the --> email address <-- of the user that selects 'Approve' or 'Reject' buttons in the email? If an email is forwarded to another person I would like to know who (email address) clicked approve or reject.

A: After reproducing from my end, I observed that when the mail is viewed in HTML format this doesn't work and also while forwarding the mail, but this works when the response is sent through the adaptive cards and not the HTML message that are received during the Send email with options action. One way that this can work is when you use only the adaptive cards that are send as the request.

RESULTS:

and when you use HTML responses then below is something how you'll be receiving the response.

You can also try Creating your own actionable messages for Flow Approvals by StefanS365 where in you add provider in Actionable Email Developer Dashboard and request the approvals.


text:
Q: How do you use sstableloader to populate a Cassandra Cluster? I have set up a 3 node Cassandra Cluster on EC2 using Whirr. I also have a 4th EC2 instance which I am using to write sstables following the example from DataStax.
Once the sstables are written I am attempting to load the Cassandra Cluster however I keep getting :
Starting client (and waiting 30 seconds for gossip) ...
java.lang.IllegalStateException: Cannot load any sstable, no live member found in the cluster

I have configured the seed in the sstableloader cassandra.yaml to be a node in the cluster, and opened up the ports between the seed node in the cluster, and the sstableloader instance. I am able to reach the seed node using cassandra-cli from the sstableloader instance, so I think that is all configured properly.
Is there anything else I am missing? Does sstableloader have to be run on one of the cluster nodes itself for gossip to work?

A: Which ports did you open between the nodes? Port 7000 (by default) specifically is required for gossip.


text:
Q: Is $|x+y|/\sqrt{x^2+y^2}$ continuous? Let $g: \mathbb{R}^2 $ -> $\mathbb{R}$

Can I just do the following?
$x^2+y^2\geq 2|x+y|$, so $\sqrt{x^2+y^2}\geq \sqrt{2|x+y|}$, therefore $$\left|\frac{x+y}{\sqrt{x^2+y^2}}\right|\leq\frac{|x+y|}{\sqrt{2|x+y|}}=\frac{\sqrt{|x+y|}}{\sqrt{2}},$$ which converges to $0$ as $x,y\to 0$, that means that it is continuous.
Or is that wrong?

A: HINT
Note that
$$x^2+y^2\geq 2|x+y|$$
is not true for $x=y=\frac12$.
Check the path with $x=-y=t\to 0$.

A: You wrote that
$$x^2+y^2>2|x+y|$$
which is false.
Take $x=y=\frac12$. it gives
$\frac 12>2$.

A: Hint:
Set $y=mx$. For all $x,y\ne0$, the function is
$$\frac{|1+m|}{\sqrt{1+m^2}},$$ which is not constant.

A: Do not overthink this.  When $x=0, y\ne 0$ the function equals $1$, but if instead $y=-x$ with both of these arguments nonzero then the function equals $0$.  There is no single value for $f(0,0)$ that renders the function continuous because the algebraic expression for other values of $x$ and $y$ does not have a (single, invariant) limit as $(x,y)$ approaches $(0,0)$.


text:
Q: .bashrc edit messes up terminal command arrow-up history print I wanted to give my terminal prompt in Ubuntu a more personal look, and wanted to change the text prior to the '$' when writing a command.
From what I've found this is done by editing the .bashrc file in the home directory, so I went in there and changed
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi

to
if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='\e[1;32m[\W]\$ \e[m'
fi

This works and the terminal looks the way I want it to.
But after some time when entering a couple of commands when I use the arrow-up key to get to the command history, things get weird.
From a clean line and pressing the arrow-up key is works. When pressing it again the text that was on the line gets capped at about ~15 characters and the new command in the history (that is supposed to be displayed) gets capped by a few characters in the beginning, and they are sort of merged together on the command line.
E.g. my two most recent commands are
Java Test4 words-250.txt words-250-in.txt
Javac Test4.java

When pressing the arrow-up key once, the first line is displayed, as it should. When pressing it a second time, this is displayed:
Java Test4 worc Test4.java

Despite this weird output, the terminal works fine. If for instance I press enter after doing the above, Javac Test4.java will run. If I instead try to delete the entire line using backspace, I am only able to delete up until the line says
Java Test4

and if pressing enter after that I get a new empty line, just as if the line was empty when pressing enter.
All of this goes away if I reset the .bashrc file.
Why does this happen and how can I fix it?

A: You need to enclose the escape sequences in \[...\], to tell bash not to count them while determining the prompt width. Otherwise, bash thinks the prompt is longer than the actual displayed length (because the escape sequences don't consume any visible space).
So, adapting the other prompt:
PS1='\[\033[1;32m\][\W]\$ \[\033[00m\]'

Both the above PS1 and the following would work equally well:
PS1='\[\e[1;32m\][\W]\$ \[\e[m\]'


text:
Q: global variable lost value from one action to another I have created a global variable de type string (erreurUtilisateurExist) and changing its value from one action to another with the objective of passing its content through a ViewBag to the View. However, it is passed as null. Can someone tell me where is my error please, must be something simple I can not see. Sorry somethings are in French.
public class AuthController : Controller
{

    string erreurUtilisateurExist = "";

    public ActionResult Create()
    {
        ViewBag.ErreurUtilisateurExist = erreurUtilisateurExist;
        return View();
    }

    [HttpPost]
    public ActionResult Create(Utilisateur utilisateur)
    {
        bool NotinDB = Utilisateur.creer(utilisateur);

        if (NotInDB)
        {
            FormsAuthentication.SetAuthCookie(utilisateur.Email, false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            erreurUtilisateurExist = "There is a user already using this address";
            return View("Create");
        }

    }

A: The web is stateless, and each time a request is made, a new instance of you controller, and therefore a new instance of erreurUtilisateurExist variable is created (its value is not persisted).
In you case, the correct approach is to add a ModelState error and return the view so that it is displayed to the user. Change you controller code to
[HttpPost]
public ActionResult Create(Utilisateur utilisateur)
{
    if (!ModelStateIsValid)
    {
        return View(utilisateur);
    }
    bool NotinDB = Utilisateur.creer(utilisateur);
    if (NotInDB)
    {
        FormsAuthentication.SetAuthCookie(utilisateur.Email, false);
        return RedirectToAction("Index", "Home");
    }
    else
    {
        ModelState.AddModelError("", "There is a user already using this address");
        return View(utilisateur);
    }
}

and the error message will be displayed in the element generated by your @Html.ValidationSummary() in the view.
If you want to display the error associated with a specific property, then use (say)
ModelState.AddModelError("Email", "There is a user already using this address");

which will be displayed in the placeholder defined by
@Html.ValidationMessageFor(m => m.Email)

You can also use the [Remote] attribute to give you client side validation - refer How to: Implement Remote Validation in ASP.NET MVC


text:
Q: Pulling Cuisine Type from TripAdvisor Restaurants using Python I am currently trying to pull data from TripAdvisor Restaurant from different countries. The fields I am trying to pull is name, address, and cuisine type (chinese, steakhouse, etc.). I have successfully been able to pull name and address using my script; however, pulling cuisine type is proving pretty difficult for myself. If you take a look below, you'll find screenshots of what I am trying to pull from TripAdvisor, and my code.
What I want to pull from TripAdvisor is circled in red.
When I print my code it keeps printing 'Asian' even thought the second one should be a 'Steakhouse'.
#import libraries
import requests
from bs4 import BeautifulSoup
import csv

#loop to move into the next pages. entries are in increments of 30 per page
for i in range(0, 120, 30):
    #need this here for when you want more than 30 entries pulled
    while i <= range:
        i = str(i)
        #url format offsets the restaurants in increments of 30 after the oa
        url1 = 'https://www.tripadvisor.com/Restaurants-g294217-oa' + i + '-Hong_Kong.html#EATERY_LIST_CONTENTS'
        r1 = requests.get(url1)
        data1 = r1.text
        soup1 = BeautifulSoup(data1, "html.parser")
        for link in soup1.findAll('a', {'property_title'}):
            #print 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href')
            restaurant_url = 'https://www.tripadvisor.com/Restaurant_Review-g294217-' + link.get('href')
            #print link.string
            account_name = link.string.strip()
            #cuisine type pull
            for link in soup1.findAll('a', {'cuisine'}):
                cuisinetype = link.string.strip()
            r_address = requests.get(restaurant_url)
            r_addresstext = r_address.text
            soup2 = BeautifulSoup(r_addresstext, "html.parser")
            for restaurant_url in soup2.findAll('span', {'street-address'})[0]:
                #print(restaurant_url.string)
                rest_address = restaurant_url.string
                rest_array = [account_name, rest_address, cuisinetype]
                print rest_array
                #with open('ListingsPull-HongKong.csv', 'a') as file:
                    #writer = csv.writer(file)
                    #writer.writerow([account_name, rest_address])
        break

A: This approach is not especially elegant but might be acceptable to you. I notice that the information you want seems to be repeated under the 'Details' tab for 'Cuisine'. I've found it easier to access there this way.
>>> import requests
>>> from bs4 import BeautifulSoup
>>> restaurant_url='https://www.tripadvisor.ca/Restaurant_Review-g294217-d2399904-Reviews-Tin_Lung_Heen-Hong_Kong.html'
>>> soup2 = BeautifulSoup(requests.get(restaurant_url).text, "html.parser")
>>> street_address=soup2.find('span',{'street-address'})
>>> street_address
International Commerce Centre, 1 Austin Road West, Kowloon
>>> street_address.contents[0]
'International Commerce Centre, 1 Austin Road West, Kowloon'
>>> for item in soup2.findAll('div', attrs={'class', 'title'}):
...     if 'Cuisine' in item.text:
...
...         item.text.strip()
...         break
...
'Cuisine'
>>> content=item.findNext('div', attrs={'class', 'content'})
>>> content

Chinese, Asian

>>> content.text
'\nChinese,\xa0Asian\n'
>>> content.text.strip().split('\xa0')
['Chinese,', 'Asian']


text:
Q: Can i make HTML forms in Django without using django forms API and Model Forms If yes, what the pros and corns
if no, what the pros and corns
Actually, I want to build HTML forms without the Django Form API and ModelForm

A: Yes of course you can, but then you need to maintain by hand the fields you would like, handle validation on the server side and probably a lot more. In short, it's a lot of work. If you want to write custom html around the fields it's possible so there is no reason to write a whole form from scratch. What are you trying to achieve?


text:
Q: Is there a way to simulate multiple locations over time like 'City Run' on a device? Currently in the iOS simulator you can simulate a City Run which changes your location over time.
You can also simulate your location on an iOS device but only individual coordinates. Is it possible to simulate something like a City Run but on a device?

A: I would look into using a GPX file(http://wiki.openstreetmap.org/wiki/GPX).  Similar as to how you would simulate location found https://developer.apple.com/library/ios/recipes/xcode_help-debugger/articles/simulating_locations.html you can upload a GPX file that hold information including multiple GPS points.
Another option depending on what you are trying to do is use a subclass of a CLLocationManager to read data from a file. There is an example of this here (https://github.com/Raizlabs/RZLocationSimulationManager/tree/develop) unfortunately there isn't any sample code with it, but you should be able to get an idea of how it is done from the code.


text:
Q: How i can ouput categiries in django on dpopdown in navbar? Views, functions from categories
def get_categories(request, cat_id):

    product = Product.objects.filter(cat_id=cat_id)
    cats = Category.objects.all()
    if len(product) == 0:
        raise Http404()

    context = {
        'product': product,
        'cats': cats,
        'menu': menu,
        'title': 'Отображение по категориям',
        'cat_selected': cat_id,

    }

    return render(request, 'task1/get_category.html', context=context)

Models with get_absolute_url
class Category(models.Model):
    name = models.CharField(max_length=255, verbose_name='Категории')
    slug = models.SlugField(max_length=255, unique=True, verbose_name='URL', db_index=True)

    class Meta:
        verbose_name = 'Категории'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('сategory', kwargs={'cat_id': self.pk})

Urls.py
path('category/', get_categories, name='category'),

This is piece of code from base.html. Dpodown from navbar.

              {% for c in cats %}

                    Категории

{{ c.name }}

                  {% else %}

{{ c.name }}

                  {% endif %}

              {% endfor %}

I'm really idk what to do, help me please
I've tried, but i get mistake
Navbar looks like, i have 4 categories and i get 4 columns in navbar


text:
Q: Sentence Equivalence Question This question is part of 5 lb. Book of GRE® Practice Problems Verbal Question Directory.
The following is a GRE-style sentence-equivalence question, where two of the six given options fit the meaning of the sentence as a whole.

James Joyce, the author of many novels, including Lady Chatterley's Lover, saw deeply into the hearts of his characters, but, in a life irony as subtle yet piercing as those endured by his characters, he himself could barely _________ text well enough to proof his own galleys.
a) see
b) feel
c) walk
d) move
e) distinguish
f) interpret

The correct options are A and E.
Can anyone explain me why option F is incorrect?
Moreover, I've never seen the structure "as .. yet ..". I've looked that up on the internet, but couldn't find any relevant explanations.
I would appreciate your help.
Thanks in advance.

A: The difference has to do with whether or not we are talking about construing something according to one's own understanding, tendencies, or preferences. In case of the verb "to interpret," we would be. In case of "seeing" and "distinguishing," on the other hand, we are simply talking about having access to what is there. In other words, ask yourself whether using judgement is emphasized.
That is why "interpret" is a wrong answer. Insofar as matters of bad eyesight go, there is no judgment or interpretation necessary—you simply need to be able to see what is there on the page.
As for the "as...yet..." construction, I don't think it's actually correct to think of it as an "as...yet... construction". In other words, read the phrase like this, and you will see that the as and yet are not really working together to create a specific construction:
"in a life irony as subtle-yet-piercing as those endured by his characters..."
What IS working together there are the two instances of "as." The construction is a comparison like "Johnny is not as tall as Sarah."
Note: In English we add hyphens between words in order to make the whole bit function as an adjective. That is what I mean by "subtle-yet-piercing." It becomes an adjective. Think of it serving the same function as "wet" in the following: "in a climate as wet as those endured by his characters..."


text:
Q: Prevent Windows 10 from resetting default applications? My Photos app broke, somehow, so I got the nomacs photo viewer, but Windows does NOT like it. I kept setting it to the default photo viewer in Default Apps, but at some point in time it would be reset to Photos and my taskbar/desktop icons would all flash so I knew it would be resetting it.
I ended up uninstalling Photos with a powershell prompt, and now the default stays nomacs. Windows still tries to reset it to no avail though, so my taskbar/desktop icons still flash from time to time.
Any help would be much appreciated.

A: Windows 10 is well known for resetting apps which the user has set by default.

*

*Press Win+R keys on your keyboard, the "Run" dialog will appear. Type regedit in it.

*The User Account Control dialog box opens up. Click on YES.

*The Registry Editor dialog box opens.

*Go to the following key
HKEY_CURRENT_USER\SOFTWARE\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\Repository\Packages\Microsoft.Windows.Photos_16.122.14020.0_x64__8wekyb3d8bbwe\App\Capabilities\FileAssociations
and Further refer to
https://winaero.com/blog/prevent-windows-10-from-resetting-your-default-apps/

A: That is the answer we've got from Microsoft when we opened the case:
Windows would reset the associations to the default ones if some incompatibility found between the apps installed keeping the association and the system.
E.g. the older version of Adobe Reader associated with PDF will cause it's reset to Edge.
Old version WinZip may cause associations reset for .zip files.
So, the solution is to keep all the external application versions installed compatible with the Windows build you have.

A: Found the solution it's microsofts "realtime broker". Changed it in regedit (admin), under 'start' = 4 (never), rebooted, and opened up apps defaults and they did not change. CNTRL ALT DELETE task menu, check for "realtime broker" and delete it. This broker is only used for microsofts store. This is the spawned program that is changing all the defaults to mircrosoft (edge, emails, etc). Running Windows 10, 1809 64 bit.
Update. No this did not work. So made a boot up program to do this for me.
first, edit your defaults as normally you would do. Then go into CMD as admin (critial as admin). Then save your defaults with (Dism.exe /Online /Export-DefaultAppAssociations:"C:\AppAssociations.xml"). Or something like this in a different location. Then create a text file named MS_Defaul.bat in this directory here the .xml file is located. Edit this file with the following.
@ECHO OFF
TIMEOUT /T 10
Dism.exe /Online /Import-DefaultAppAssociations:"C:\AppAssociations.xml"
save the file.
create a short cut of this file, and move it to Startup file location, which is:
C:\Users\\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Now every time the computer boots (10 seconds later - you can experiment this delay time) the DEFAULT settings will take place.
Caviot, the browser (firefox) never asks anymore if you want to change defaults, but on looking at defaults in windows its still IE, and Outlook. Hum... as long as it does not ask me anymore, I'm good with this mod.  DONE.


text:
Q: Fails Hibernate JSON mapping to PostgreSQL database in Spring Boot web application everybody!!! I'm developing a Spring Boot web application with PostgreSQL database connection. I need to make Hibernate mapping between the MyJson field in UserData Entity and jsonb-type field in the corresponding PG table column. But when I run my application, I see the following Errors

2016-06-26 14:16:39.504  INFO 4552 --- [on(2)-127.0.0.1] alex.pol.Application                     : Starting Application v0.0.1-SNAPSHOT on Dmitriy-Litvinenko with PID 4552 (/home/dima/Web/apache-tomcat-8.0.32/webapps/ROOT/WEB-INF/classes started by dima in /home/dima/Web/apache-tomcat-8.0.32/bin)
2016-06-26 14:16:39.549  INFO 4552 --- [on(2)-127.0.0.1] alex.pol.Application                     : No active profile set, falling back to default profiles: default
2016-06-26 14:16:40.829  INFO 4552 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a3995da: startup date [Sun Jun 26 14:16:40 EEST 2016]; root of context hierarchy
2016-06-26 14:16:43.153  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-06-26 14:16:44.144  INFO 4552 --- [on(2)-127.0.0.1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-06-26 14:16:44.342  INFO 4552 --- [on(2)-127.0.0.1] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$8ad0af19] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-06-26 14:16:44.517  INFO 4552 --- [on(2)-127.0.0.1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3689 ms
2016-06-26 14:16:45.940  INFO 4552 --- [on(2)-127.0.0.1] b.a.w.TomcatWebSocketContainerCustomizer : NonEmbeddedServletContainerFactory detected. Websockets support should be native so this normally is not a problem.
2016-06-26 14:16:46.818  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-06-26 14:16:46.837  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'errorPageFilter' to: [/*]
2016-06-26 14:16:46.838  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-06-26 14:16:46.838  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-06-26 14:16:46.838  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-06-26 14:16:46.838  INFO 4552 --- [on(2)-127.0.0.1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-06-26 14:16:49.350  INFO 4552 --- [on(2)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-06-26 14:16:49.382  WARN 4552 --- [on(2)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/tool/schema/spi/DelayedDropRegistry
2016-06-26 14:16:49.423 ERROR 4552 --- [on(2)-127.0.0.1] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/tool/schema/spi/DelayedDropRegistry
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578) ~[spring-beans-4.2.5.RELEASE.jar:4.2.5.RELEASE]

Here is my UserData class file

@Entity(name = "UserData")
@TypeDef(name = "MyJsonType",typeClass = MyJsonType.class)
public class UserData extends BaseModel {

    private String firstName;

    private String secondName;

    @Column
    @Type(type = "MyJsonType")
    private MyJson jsonProperty;/*//socialData;*/

    @OneToOne(cascade = CascadeType.MERGE)
    @JoinColumn(name = "user_id")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

Here is MyJson.java file

import java.io.Serializable;

public class MyJson implements Serializable {

    private String stringProp;

    private Long longProp;

    public String getStringProp() {
        return stringProp;
    }

    public void setStringProp(String stringProp) {
        this.stringProp = stringProp;
    }

    public Long getLongProp() {
        return longProp;
    }

    public void setLongProp(Long longProp) {
        this.longProp = longProp;
    }
}

MyJsonType.java file

import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;

import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

public class MyJsonType implements UserType {

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.JAVA_OBJECT};
    }

    @Override
    public Class<MyJson> returnedClass() {
        return MyJson.class;
    }

    @Override
    public Object nullSafeGet(final ResultSet rs, final String[] names, final SessionImplementor session,
                              final Object owner) throws HibernateException, SQLException {
        final String cellContent = rs.getString(names[0]);
        if (cellContent == null) {
            return null;
        }
        try {
            final ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(cellContent.getBytes("UTF-8"), returnedClass());
        } catch (final Exception ex) {
            throw new RuntimeException("Failed to convert String to Invoice: " + ex.getMessage(), ex);
        }
    }

    @Override
    public void nullSafeSet(final PreparedStatement ps, final Object value, final int idx,
                            final SessionImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            ps.setNull(idx, Types.OTHER);
            return;
        }
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final StringWriter w = new StringWriter();
            mapper.writeValue(w, value);
            w.flush();
            ps.setObject(idx, w.toString(), Types.OTHER);
        } catch (final Exception ex) {
            throw new RuntimeException("Failed to convert Invoice to String: " + ex.getMessage(), ex);
        }
    }

    @Override
    public Object deepCopy(final Object value) throws HibernateException {
        try {
            // use serialization to create a deep copy
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(value);
            oos.flush();
            oos.close();
            bos.close();

            ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray());
            return new ObjectInputStream(bais).readObject();
        } catch (ClassNotFoundException | IOException ex) {
            throw new HibernateException(ex);
        }
    }

    @Override
    public boolean isMutable() {
        return true;
    }

    @Override
    public Serializable disassemble(final Object value) throws HibernateException {
        return (Serializable) this.deepCopy(value);
    }

    @Override
    public Object assemble(final Serializable cached, final Object owner) throws HibernateException {
        return this.deepCopy(cached);
    }

    @Override
    public Object replace(final Object original, final Object target, final Object owner) throws HibernateException {
        return this.deepCopy(original);
    }

    @Override
    public boolean equals(final Object obj1, final Object obj2) throws HibernateException {
        if (obj1 == null) {
            return obj2 == null;
        }
        return obj1.equals(obj2);
    }

    @Override
    public int hashCode(final Object obj) throws HibernateException {
        return obj.hashCode();
    }

}

MyPostgreSQL94Dialect.java file

import org.hibernate.dialect.PostgreSQL94Dialect;

import java.sql.Types;

public class MyPostgreSQL94Dialect extends PostgreSQL94Dialect {

    public MyPostgreSQL94Dialect() {
        super();
        this.registerColumnType(Types.JAVA_OBJECT, "jsonb");
    }
}

And my pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.example</groupId>
 <artifactId>UBWApp</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <name>UBWApp</name>
 <description>UBWApp</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.3.3.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
  <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-github</artifactId>
   <version>1.0.0.BUILD-SNAPSHOT</version>
  </dependency>
  <dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.2</version>
  </dependency>
  <dependency>
  <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-core</artifactId>
   <version>1.1.0.RELEASE</version>
  </dependency>
  <dependency>
     <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-facebook</artifactId>
   <version>2.0.3.RELEASE</version>
  </dependency>
  <dependency>
  <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-linkedin</artifactId>
   <version>1.0.2.RELEASE</version>
  </dependency>
  <dependency>
  <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-google</artifactId>
   <version>1.0.0.RC1</version>
  </dependency>
  <dependency>
  <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-twitter</artifactId>
    <version>1.1.0.RELEASE</version>
   </dependency>
  <dependency>
   <groupId>com.github.weekens</groupId>
   <artifactId>spring-social-vkontakte</artifactId>
   <version>1.1.1.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-web</artifactId>
   <version>1.1.4.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.social</groupId>
   <artifactId>spring-social-config</artifactId>
   <version>1.1.4.RELEASE</version>
  </dependency>
  <dependency>
  <groupId>org.glassfish.jersey.security</groupId>
   <artifactId>oauth1-server</artifactId>
   <version>2.4.1</version>
  </dependency>
  <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.0</version>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>
  <dependency>
   <groupId>net.sf.json-lib</groupId>
   <artifactId>json-lib</artifactId>
   <version>2.4</version>
   <classifier>jdk15</classifier>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.0.9.Final</version>
  </dependency>
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-entitymanager</artifactId>
   <version>5.1.0.Final</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-tomcat</artifactId>
   <!--<scope>provided</scope>-->
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>jstl</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.postgresql</groupId>
   <artifactId>postgresql</artifactId>
   <version>9.4.1208.jre7</version>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>4.2.1.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>commons-validator</groupId>
   <artifactId>commons-validator</artifactId>
   <version>1.4.0</version>
  </dependency>
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>

  <!-- Logging-->
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.17</version>
  </dependency>

  </dependencies>
 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/libs-snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
 </repositories>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>


text:
Q: Paypal IPN: What happens if my listener doesn't send back acknowledgement upon receiving the IPN? It is probably not the best practice but in a simple project of mine I've been using the following link in the Emails being sent to my customers once they fill out my Google form.

https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&no_shipping=1&tax=0&amount=60&business=my@email.com&currency_code=USD&notify_url=https://example.com/myListener.php&item_name=dummy

In my listener I simply process the POST data from IPN and post it to a simple google sheet so I know whether my customers paid or not.
It's been working fine (Hundreds of transactions have been recorded without any error) until lately I read this on Paypal's IPN instruction page

Although it says my listener MUST respond to EVERY IPN message, I never did that, nor do I think I ever got any resending messages. Ironically, today while I am just writing this I noticed a recent transaction was reported twice in my Google Sheet, and this is the only abnormal record. I then sent a test payment but this time it didn't get reported twice.
I went into the Paypal account and checked IPN hisotry, the transaction in question does have "No. of retries" as "1", as the picture below shows:

So this explains why my Google Sheet shows two identical transactions. And it partly matches the behavior described in the IPN instruction page, although there is only 1 retry, in contrast to "keep retrying until my listener responds".
Anyone knows why the actual behavior is so different from what they say on their own page?
Also, since my listener is actually working perfectly, I don't want to touch it at this time. But will it cause potential problems if I leave it as is?

A: Your IPN listener must reply with an HTTP 2xx success status when PayPal posts to it, or PayPal will keep retrying (up to around 20 times) until it does so.
So if the listener replies with e.g. an HTTP 4xx, 5xx, or gives no reply at all or can't be connected to -- PayPal will keep retrying.
I'm not sure what the specific confusion is here; the behavior is as described. You screenshot shows a 200 for the last status.


text:
Q: Can't change the label on an excel ribbon I've got a problem trying to set a custom label on teh fly with a ribbon using Excel-DNA.
If I don't included the annotation "getLabel='GetLabel'" then the plugin loads fine. ie the ribbon tab is shown with 2 buttons andthe button callbacks work fine.
If I do inclue the property "getLabel='GetLabel'" then the plugin doesn't even load, ie onLoad isn't called and the ribbon tab doesn't show up in excel.
Can anyone see what I'm doing wrong here.  I don't see any errors when running in the debugger.
Here is my DNA file.  I've tried to base it off one of the samples so it's easier to follow.
<DnaLibrary Name="Emsx Addin" RuntimeVersion="v2.0">
<ExternalLibrary Path="EmsxExcelTech1.dll" />
<Reference AssemblyPath="System.Windows.Forms.dll" />

<!-- Some images that can be used in the Ribbon ui -->
<Image Name="M" Path="M.png" Pack="true" />

<CustomUI>
<customUI xmlns='http://schemas.microsoft.com/office/2009/07/customui' loadImage='LoadImage' onLoad='OnLoad'>
  <ribbon>
    <tabs>
      <tab id='CustomTab' label='K2 Emsx' insertAfterMso='View'>
        <group id='SampleGroup' label='Global Sheet Status'>
          <button id='LoginCmd' label='Logon' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />
          <button id='BetaCmd' label='Use Beta Route' image='M' size='normal' onAction='RunTagMacro' tag='OnUseBetaRoutes' />
        </group >
      </tab>
    </tabs>
  </ribbon>
</customUI>
</CustomUI>
</DnaLibrary>

Here is my Ribbon derived C# file.
[ComVisible(true)]
public class EmsxRibbon : ExcelRibbon
{
    private IRibbonUI ribbon = null;

    public void OnLogonPressed(IRibbonControl control)
    {
        EmsxIntegration.Instance.Login();
        MessageBox.Show("Hello from control " + control.Id);
        if (ribbon != null)
        {
            ribbon.InvalidateControl(control.Id);
        }

    }

    string GetLabel(IRibbonControl control)
    {
        if (control.Tag == "Logon")
        {
            return "Logon";
        }
        else
        {
            return "Logoff";
        }
    }

    public static void OnUseBetaRoutes()
    {
        MessageBox.Show("Hello from 'ShowHelloMessage'.");
    }

    public void OnLoad(IRibbonUI ribbon)
    {
        this.ribbon = ribbon;
    }

}

A: When you use the getLabel event, you should not use label property, so change
<button id='LoginCmd' label='Logon' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />

to
<button id='LoginCmd' image='M' onAction='OnLogonPressed' getLabel='GetLabel' />

Hope this helps.


text:
Q: Converting XML to Json using Json.NET contains a '@' prefix for all object's properties I am writing a small program that converts a generated XML (using the C# XmlSerializer) to a Json. The converting from XML to Json is done via Json.NET. I have not used Json at all and I am not sure that the generated code is correct. What I am concerned about is that all the properties of the exported objects have a '@' prefix. Is that normal for a Json code? For example converting this XML:
<Icon Name="name1" Path="public/images/name1.png" Size="50x50">
  <IconCategories>
    <string>misc</string>
  </IconCategories>
</Icon>

is converted to:
{
  "Icon":
  {
    "@Name": "name1",
    "@Path": "public/images/name1.png",
    "@Size": "50x50",
    "IconCategories":
    {
      "string": "misc"
    }
  }
}

Is the '@Name' normal or should it be 'Name'? Using this online xml to json convert also yields similar results but with instead of the '@' symbol the '-' is used.


text:
Q: Merge internal repository into external repository without showing all commits I've got internal and external repositories. external lags behind internal and is mostly a mirror (sometimes there needs to be minor differences between the two). main is the primary branch in each repository (historically called master)
What I'm trying to do is the following flow:
A - B - C - D - E  (internal branch: main)
        \       \
 -   -   C   -   E  (internal branch: tracking)

tracking pushes to external branch: to-merge, then to-merge gets merged with external main, resulting in:

 -   -   C   -   E  (external branch: main)

When setting this up initially, I git checkout -bed at C a branch from internal called tracking with external as a remote. I squashed (using git rebase -i HEAD~X flow) so that C was the only commit showing up (although if I understand correctly...this creates a new commit? So is it actually C' i.e. something totally new?), then pushed that branch to a remote branch to-merge in external (this is how I'm transferring files from one repo to the other)
After internal main goes to commit E, I cannot do a fast-forward merge from C on the branch tracking (maybe because C on tracking is C'??) so I have to resolve all the merge conflicts manually, which is what I'm trying to avoid.
Is there an easier way to do this? The easiest way I can think of is to copy all the files at each milestone commit on internal main that I want to transfer to external main, and just create new commits, but that doesn't seem very git-esque. Suggestions?
To preempt some questions: no, I cannot allow intermediate commits to show up in the external repository.


text:
Q: Combine two Select statements in one call I am trying to query a table to find first the exact match to a column,
in case the match fails; select the closest one in the range.
For e.g.
testTable
  id        width       cost

  1         10.2        100
  2         10.5        200
  3         10.1         50

 Select * from testTable where width = 10.3;

in case this returns without record I want to go for the nearest one in the range of 10.1 to 10.9.
EDIT1: it's Oracle; updated the tag

A: In most databases you can do something like this:
Select *
from testTable
order by abs(width - 10.3)
fetch first 1 row only;

Some databases might use limit, top, or even where rownum = 1, but the idea is the same.

A: You would write something like this:
 select * from (
    Select * from testTable where width = 10.3
    union
    Select * from testTable where width > 10.1 and width < 10.9
    order by abs (10.3 - width) asc
) T LIMIT 1

And yes, it can be reduced to what Gordon Linoff showed
    Select * from testTable where width > 10.1 and width < 10.9
    order by abs (10.3 - width) asc
    LIMIT 1


text:
Q: Microsoft Edge Forces Margins when Printing CSS Microsoft Edge is forcibly adding margins to pages when attempting to print. None of the other browsers do this because I specified on my print.css file that I don't want margins like so:
@page { margin: 0; }
Microsoft Edge is the only browser that adds margins despite my css rule. Even when adding margin: 0 to the developer tools, I can see that rule disappear as soon as I click on Print.
From my research, this seems to be the default behavior for Edge.
Does anybody know a work around to this at least? I need all the horizontal real estate available for my page that I'm trying to print. I prefer not to have to do a redesign of the page just to accommodate Edge.


text:
Q: Will dispatch_async inside autoreleasepool cause issues? I'm parsing midi messages inside an autoreleasepool. After determining the message that's being sent, I make calls to the main thread using dispatch_async(dispatch_get_main_queue(). This seems to work well most of the time but occasionally I'll get a crash where it stops on the line
while (semaphore_wait(midiReceivedSemaphore) == KERN_SUCCESS ) {

The method looks something like this:
@autoreleasepool {

    unsigned int maxPacketLength = 0x100;
    unsigned char* data = malloc(maxPacketLength);
    UInt16 length;

    while (semaphore_wait(midiReceivedSemaphore) == KERN_SUCCESS ) {

        midi_packet_buffer_next_packet_length(midiPacketBuffer, &length);
        if( length > 0) {

            length = midi_packet_buffer_read(midiPacketBuffer, data, length);

            for (unsigned int packetContentsIndex = 0; packetContentsIndex < length; packetContentsIndex++) {
                while (packetContentsIndex < length) {
                    Byte command = data[packetContentsIndex];

                    switch (command) {
                        case 0xA0: //aftertouch
                            commandLength += 2;
                            int meterChannel = data[packetContentsIndex +1];
                            int meterValue = data[packetContentsIndex +2];

                            if (meterValue < 0x10)
                            {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [delegate sendLevelMeterPT:meterChannel withValue:meterValue ];

                                });
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }
    free(data);
}

Is this a very bad way of handling the MIDI messages? The reason I used dispatch_async is so that it wouldn't slow down the midi processing thread, before using dispatch_async the method was missing some messages if they were coming in fast. Now it catches all the messages but I get the occasional crash. I'm thinking I might have to rewrite the whole midi processing method but want to know the proper way to go about it. Any advice would be great.


text:
Q: How to position div below another div with images? I'm fighting two days already with this problem. I want to put div with images at absolute positions, below other div with images. Somehow divs are ignoring images and stack on top of each other.
example code is here: https://jsfiddle.net/6H4RA/10/
So it should display one image in the first row, and two images in the second.
I must be missing something obvious.
Here is the code from JSFiddle:
#banner-left {
    position:absolute;
    width:100px;
    height:100px;
}

#header{
    position:relative;
    background: #ffa;
}

#footer {
            position:relative;
            margin-top:0px;
            width: 100%;
            background: #6cf;
}

        Header

    FOOTER

--edit--
I forgot to mention that images must be at absolute positions. That's the catch.

A: There may be no need to use absolute positioning in this layout design.
Here is how I might approach implementing this.
Note: id's should be unique on a web page, so I changed your #banner-left to a class .banner-left.

.banner-left {
    float: left;
    margin-right: 20px; /* if needed */
}
.banner-left img {
    display: block;
}
#header {
    overflow: auto;
    background: #ffa;
}
#footer {
    overflow: auto;
    background: #6cf;
}

Header

Footer

A: In you banner width id, add
  display: inline-block;

A: I forgot to mention that images must be at absolute positions. That's the catch.
Marc, your example works great but i have lots of images with absolute position that i want to move depending on website size with a simple container div.

A: You have a couple of problems with your code.
First, you can't have multiple elements with the same id. This may not cause problems in your small jsfiddle right now, but it can and will come back and bite you in the rear, later on. However, that is easily solved by turning the ids into classes.
The other problem is that there is no more content in the header and footer divs after the text. Yes, there are the absolutely positioned blocks, but they don't count. Absolutely positioned elements don't partake in the page flow. So the header and footer divs don't have a clue about them!
The easiest solution, as possible in your example, is to give those divs a bottom padding of 100px, so that the images appear to be inside them instead of sticking out. (They don't really sit inside them, but they just are displayed in the same place where the parents' padding is.)

.banner-left {
  position:absolute;
  width:100px;
  height:100px;
}
.banner-left img {
  width:100px;
  height:100px;
}
#header{
  position:relative;
  background: #ffa;
  padding-bottom:100px;
}

#footer {
  position:relative;
  margin-top:0px;
  width: 100%;
  background: #6cf;
  padding-bottom:100px;
}

  Header

  FOOTER

If, however, you don't know beforehand what the heights of the images are, you may have to run some Javascript on the images to figure out which one is the highest, or find out a way to avoid the display:absolute.


text:
Q: Split by '/' till '[' appears I want to split the following kind of string:

Parent/Child/Value [4za] AX/BY

and get create a String[] out of it via:
String[] ArrayVar = Regex.Split(stringVar, "?");

which split the string by every / before first appearance of [.
So as result I would get
Array[0] => "Parent"
Array[1] => "Child"
Array[2] => "Value [4za] AX/BY"

strings could also have other formats like

Parent/Value [4za] AX/BY
Value [4za] AX/BY

How can I do this?

A: You could use normal string operations to do this. Just split the string on the first [ then split that accordingly. Then just add the end part of the string onto the last element:
string inputstring = "Parent/Child/Value [4za] AX/BY";

int index = inputstring.IndexOf('[');

string[] parts = inputstring.Substring(0, index).Split('/');
parts[parts.Length - 1] += inputstring.Substring(index);

A: Use negative lookbehind ((?<!...)). The following regex means "/ not preceded by opening bracket":
(?<!\[.*)/

Demo
C# demo: https://dotnetfiddle.net/85S3cK