text:
Q: How do I connect to a Lotus Notes DB through VBA? I'm trying to connect to a Lotus Notes database via VBA in Microsoft Access 2003.  The code I have is as follows:
Set nSession = CreateObject("Notes.NotesSession")
Set nDatabase = nSession.GetDatabase("CN=MT_N01/O=Org Name", "LossPrevention\BrchPrVI.nsf", False)
I've tried variations for the server name, but nothing seems to work.  In Lotus Notes it appears as "Server: MT_N01/Org Name".  I've tried just "MT_N01" and "MT_N01/Org Name", but the NotesDatabase variable keeps ending up empty.
Any tips?

A: I might be wrong here, but I think you should call the Initialize() method of the session prior to using it.
Take a look at the samples here: http://www.ibm.com/developerworks/lotus/library/domino-msnet/index.html

A: I think that behaviour is normal; VBA knows nDatabase is a variant/object, but does not know anything about its contents. At least that is what I get when I try your code in Excel 2003.
Try to return something from the database object, for example nDatabase.ReplicaID should return the database identity string. If the databas is not properly loaded, you will get an error.
Many good links are posted in response to the ".NET and Lotus Notes Interop." question.

A: Unless you also need to us the NotesUIWorkspace class and its child classes to manipulate the Notes client user interface, you should be using the "Lotus.NotesSession" class instead of the "Notes.NotesSession" class.  And as per the answer from @Sagultay, you should be calling nSession.Intialize().


text:
Q: How to get the size of a struct within a union in C? How do you get the size of a struct within a union in C?
Given the following definition:
typedef union
{
    struct req_
    {
        uint8_t cmd1;
        uint8_t cmd2;
    } req;

    struct rsp_
    {
        uint8_t cmd_result;
        uint8_t status_1;
        uint8_t status_2;
        uint8_t status_3;
        uint8_t status_4;
    } rsp;
} msg_t;

sizeof(msg_t) would provide the maximum size of the union, which in this case, would be 5 as rsp_ is greater than req_.
How do you get sizeof(req_)?

A: Like this:
sizeof(struct req_);

For example:
int main()
{
    printf("sizeof msg_t=%zd\n",sizeof(msg_t));
    printf("sizeof struct req_=%zd\n",sizeof(struct req_));
}

Output:
sizeof msg_t=5
sizeof struct req_=2

A: req_ is a structure tag. You need to either put struct with it
size_t size = sizeof(struct req_);

or use the struct variable declared
size_t size = sizeof(msg_t.req_.req);

redpajama_set_name: RedPajamaStackExchange


text:
Q: :hover works in Chrome but not Firefox For some reason Firefox just doesn't like :hover.  The codes work fine in Chrome however.
html:

  <%= image_tag("worldmap.png", :usemap => "#worldmap", :class => "mapper") %>
  <map name="worldmap">
    <area shape="rect" coords="505,244,546,278" class="target" data-textboxleft="Text 1">
    <area shape="rect" coords="481,189,503,207" class="target" data-textboxleft="Text 2">
  </map>

CSS:
.target[data-textboxleft]:hover:after {
  content: attr(data-textboxleft);
  background: rgba(0,0,0,0.5);
  color: white;
  font-family: Papyrus;
  font-size: 16px;
  font-style: oblique;
  height: 50px;
  width: 180px;
  position: absolute;
  text-align: center;
  padding-top: 12px;
  left: 0;
  top: 0;
}

A: I eventually figured it out using jQuery.

  <%= image_tag("worldmap.png", :usemap => "#worldmap", :class => "mapper") %>
  <map name="worldmap">
    <area shape="rect" coords="505,244,546,278" class="target" data-name="Text 1">
    <area shape="rect" coords="481,189,503,207" class="target" data-name="Text 2">

  </map>

css:
#boxleft {
  display: none;
  background: rgba(0,0,0,0.5);
  color: white;
  font-family: Papyrus;
  font-size: 14px;
  font-style: oblique;
  opacity: 1;
  height: 50px;
  width: 180px;
  position: absolute;
  text-align: center;
  padding-top: 12px;
  left: 0;
  top: 0;
  border: 2px solid $gray-lighter;
}

A: The area element doesn't accept the :hover selector, so you achieve the effect you want with your current code. There are a couple of ways around it using jQuery Plugin, MapHilight or using canvas.
Have a look at these answers [Visible Area tag?  and  How to apply Hovering on html area tag?


text:
Q: Check the validity of a call to os.system using Python 3 Is there any way out to observe that the system call is valid or not if we go for a system call with an argument taken from user in Python 3 ? For example
os.system('pwd') will return true but
os.system('abc') will return false.
Can we check the same using sub-process ?


text:
Q: Alternative for float on moving banner I'm in the process of making all my containers stay "fullsized" and positioned correctly, when the viewport is smaller than the resolution of the website.
So far everything has gone easy, except for the navbar.
On resize of window, the navbars text moves.
It's currently held in place with float: right;
is there an alternative to float that will work in this instance?
I tried defining left and right margins, but the text doesn't stay in a straight line.
Website in question is: njdartistics.com

@charset "utf-8";
/* CSS Document */

@font-face {
    font-family: 'Bebas';
    src: url(Website%20Specific%20Resources/BEBAS.TTF)
}

body {
 background-image:url(Website%20Specific%20Resources/Background.png);

 width:1920px;
 margin: auto;
}

.outercontainer{
      height:100%;
      width:100%
}

.container {
 width:960px;
 margin: 0 auto;
  border-left:solid #000;
  border-right:solid #000;
background-color:#AAADAD;

}

.header {
 background-image:url(Website%20Specific%20Resources/New_Banner_.png);
 height: 300px;
 width: 100%;
 top: 0;
 position: fixed;
}

A {
 text-decoration:none;
 font-family: "bebas";
 color: #fff;

}

li {
 list-style:none;
 float:left;
 padding-right:50px;
 margin-left:25px;
 padding-top:15px;
 font-size:24px;

}

.nav {
 float: inherit;
 position: absolute;
}
.content {
font-family: "bebas";
width: 900px;
background-color:#AAADAD;

}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Index</title>
<link rel="stylesheet" type="text/css" href="styles.css">

Home

About  Us

Products

Gallery

Contact  Us

asdasdasdasdaf

asdasdasdasdafasdasdasdasdafasdasdasdasdafasdasdasdasdafasdasda

sdasdafasdasdasdasdafasdasdasdasdafasdasdasdasdafasdasdasdasdafasdasdasdasdaf

Thanks in advance.

A: As I'm understanding this, you want the navbar text responsive and to stay all on one line, correct?
To start, try changing the following css to something like this:
body {
background-image:url(Website%20Specific%20Resources/Background.png);
font: 100%/1.5 serif; /* 16px */
width:1920px;
margin: auto;
}

li {
list-style:none;
float:left;
font-size:1.5em;
font-size:3vw;
padding:0 1%;
width:15%;
}

.nav {
float: inherit;
position: absolute;
width:100%;
}

Using a combination of em and vw handles the font-size (but it should be noted that vw, or viewport width, doesn't work in every browser (see here). For the browsers that don't like it, em can attempt to handle it by basing its size on whatever font size you set  for the body.
Alternatively (or, really, in addition--wrangle it as you please), you can use a media query to handle smaller viewport/screen sizes when it comes to the font-size. For example:
 @media (max-width: 600px) {
    body { font: 80%; }
}

You can size up or down based on your needs. If you set it on the body, you don't have to rewrite the li or nav css, as the em units will respond accordingly. I would avoid setting font-size in anything BUT em, as px doesn't have much flexibility.
That said, after alllll this, you really should set different breakpoints for mobile devices to, for example, stack the menu or semi-hide it with the hamburger menu icon, as the text will get very, very, very small otherwise.

A: header {
    background-image:url(Website%20Specific%20Resources/New_Banner_.png);
    height: 300px;
    width: 1920px;
    top: 0;
    position: fixed;
}
This was the issue. Width was 100% instead of a fixed resolution.


text:
Q: Fatal Error after upgrading Magento 1.9.3.1 to PHP7 After upgrading PHP to 7.0 Magento show the following error message:
Fatal error: Uncaught TypeError: Argument 2 passed to Mage::dispatchEvent() must be of the type array, object given, called in /var/www/izdelam.si/public_html/app/code/local/Gitscripts/Title/Model/Observer.php on line 9 and defined in /var/www/izdelam.si/public_html/app/Mage.php:448
Stack trace:
#0 /var/www/izdelam.si/public_html/app/code/local/Gitscripts/Title/Model/Observer.php(9): Mage::dispatchEvent('title_assignmen...', Object(Varien_Event_Observer))
#1 /var/www/izdelam.si/public_html/app/code/core/Mage/Core/Model/App.php(1358): Gitscripts_Title_Model_Observer->applyTitle(Object(Varien_Event_Observer))
#2 /var/www/izdelam.si/public_html/app/code/core/Mage/Core/Model/App.php(1337): Mage_Core_Model_App->_callObserverMethod(Object(Gitscripts_Title_Model_Observer), 'applyTitle', Object(Varien_Event_Observer))
#3 /var/www/izdelam.si/public_html/app/Mage.php(451): Mage_Core_Model_App->dispatchEvent('controller_acti...', Array)
#4 /var/www/izdelam.si/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(350): Mag in /var/www/izdelam.si/public_html/app/Mage.php on line 448

The code that seems to have the issue, is the function applyTitle() that is located into the file Observer.php, and it looks like this:
[...]
public function applyTitle($observer){
    $head = $observer->getLayout()->getBlock('head');
    if($head){
        $this->setData('title',Mage::getSingleton('title/title'));
    }
    Mage::dispatchEvent('title_assignment_before',$observer);

    Mage::Register('current_title',Mage::getSingleton('title/title'));

    $title = $this->getData('title');
    if($title){
        $head->setTitle($title->getTitle());
    }

    return $this;
}
[...]

Could you help me to understand what is wrong with this code?


text:
Q: Diy development board troubleshoot i have designed arduino compatible diy board with Atmega328p-Pu.
,i have burned the bootloader for first time and the upload blink example to board and it didn't get any error. After that when i upload another code i got "avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03"

i'm use ftdi programmer to upload code(i have already add 0.1uf cap DTR and 10K pullup resistor in my design)

When i press and hold reset button while compile and release when uploading its successfully uploading code.
i tried original uno ic with my board its work without any uploading error. also tried my new ic with arduino original board and didn't get error
how to solve this error


text:
Q: Horizontal Dendrogram with Labels in R I am running into an issue where I can plot a vertical dendrogram with labels but I can't add labels when it is horizontal.
My Data looks like this:
Company Industry1 Industry2 Industry3
Google     3%        5%        6%
Apple      2%        6%        1%

When i import the data, the first column contains my Labels but the rows are just 1, 2, 3 etc.
So my code reads: Data Source Is called Cluster_D
labs = Cluster_D[, 1]
Industry <- Cluster_D
rownames(Industry) <- labs$`Company`

D.Industry <- dist(scale(round(Industry[, -1], 3)), method = "euclidean")
H.Industry <- hclust(D.Industry, method = "ward.D")
plot(H.Industry, labels = Cluster_D$`Company`)

So i assign my labels to the variable 'Labs". I then place my data into another variable "Industry".
Once i plot the data and pass in Labels i get the chart with the clusters I need. The chart works vertically with labels.....but
I have no idea how to get this chart flipped to horizontal and to keep the label names. I tried to use as.dendrogram function which allows me to use horiz=true but i cant keep my labels, as it reverts back to 1, 2, 3 etc.
Can anyone explain to me how I can get correct myself? I am used to use Statistica and i didn't have any issues doing hierarchical clustering, I am trying to pick up R. I feel like it should be super easy to assign labels but I just don't know how.
i tried using the below, but the charts is mislabeled (ABC order).
F.Industries <- as.dendrogram(H.Industry)
labels(F.Industries) <- paste(as.character(Cluster_D[,1]))
plot(F.Industries, horiz = TRUE)

A: As requested by PAR:
data - I added one more column IBM:
z <- read.table(text = "Company Industry1 Industry2 Industry3
Google     3%        5%        6%
Apple      2%        6%        1%
IBM        7%        4%        2%", header = T)

When I try:
scale(round(z[, -1], 3))
#output
Error in Math.data.frame(list(Industry1 = c(2L, 1L, 3L), Industry2 = c(2L,  :
  non-numeric variable in data frame: Industry1Industry2Industry3

Meaning the sample data you provided is not representative of your own.
Convert to numeric:
z = data.frame("Company" = z[,1], apply(z[,-1], 2, function(x) as.numeric(gsub("%", "", x))))

Row names are labels for the leaves
rownames(z) <- z[,1]

D.Industry <- dist(scale(z[, -1]), method = "euclidean")
H.Industry <- hclust(D.Industry, method = "ward.D")

plot(as.dendrogram(H.Industry), horiz = T)

one can adjust the margins with mar
par(mar=c(2, 0, 0, 8))
plot(as.dendrogram(H.Industry), horiz = T)

other approaches include using ape and ggdendro


text:
Q: Kotlin Image Compression Implementation My old implementation to upload image to Firebase Storage in JPEG format without any compression
private fun sendToFirebase() {

        if (imgUri != null) {

            val fileRef = storageRef!!.child(username+ ".jpg")

            ....

            // code to upload and read image url
        }
    }

Decided to write a image compression technique to compress image and then upload to Firebase Storage
Result : Achieved image compression technique, see below
Newly added code to compress image

*

*URI to Bitmap
val bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imgUri)

*Method to compress Bitmap
 private fun compressBitmap(bitmap: Bitmap, quality:Int):Bitmap{
    val stream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.WEBP, quality, stream)
    val byteArray = stream.toByteArray()
    return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size)
 }

*Bitmap compression Implementation
 compressBitmap(bitmap, 80)

Query: How to upload same compressed image to Firebase storage
 private fun sendToFirebase() {

    if (imgUri != null) {

        // code to convert uri to bitmap <start>
        val bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imgUri)

        compressBitmap(bitmap, 80)
        // code to convert uri to bitmap <end>

        // old implementation
        .....

    }
}

A: You don't seem to be passing anything into your function for sendtoFirebase. i am posting code i have done to successfully upload.
you looking at compressing first so you would need this;
private fun compressBitmap(bitmap: Bitmap, quality: Int): Bitmap {

    val stream = ByteArrayOutputStream()

    bitmap.compress(Bitmap.CompressFormat.WEBP,quality,stream)

    val byteArray = stream.toByteArray()

    arrayByte = byteArray

                uploadFile(arrayByte)

    return BitmapFactory.decodeByteArray(byteArray,0,byteArray.size)

}

in the above, uploadFile is the call for the firebase upload. i am passing the compressed bitmap into the function. the functional for upload looks as follows:
in below mImageURI is a companion object which is part of the URI passed for compression. you can remove the if statement below if you dont want to do the check
 private fun uploadFile(data:ByteArray) {

    if (mImageUri != null){

        val storageref = imageref.child("put your image id here")

        storageref.putBytes(data).addOnSuccessListener {

                            Handler().postDelayed({

                                progressbar.setProgress(0)
                                Toast.makeText(activity, "Upload Successful", Toast.LENGTH_LONG).show()

                            }

                                , 1000)

        }.addOnFailureListener{e->

            Toast.makeText(activity,e.message,Toast.LENGTH_LONG).show()
        }.addOnProgressListener {taskSnapshot ->

            val progress = (100.0 * taskSnapshot.bytesTransferred/taskSnapshot.totalByteCount)

            progressbar.setProgress(progress.toInt())

        }

    }
    else if(mImageUri == null) {
        Toast.makeText(activity,"No File Selected",Toast.LENGTH_LONG).show()

    }
}

You do not need to have the progress bar above. its just a nice visual for the user to have to see the progress of the upload if the file is large.
your really only need to ensure that you passing data into .putbytes

Edit: For your onActivity result if your code is similar to mine then use;
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
        && data != null && data.getData() != null) {

            mImageUri = data.getData()!!

        image1.setImageURI(data.getData())

   }
}

in the above image1 is a imageView on the current page to show the image selected.
Hope this helps


text:
Q: Correcting askers who do not follow up When I ask a question I always follow up with the answers that are arriving. I upvote good answers and I give feedback to answers which did not help me. I downvote answers missing the point. I always accept an answer if there is a correct one.
It seems that many askers do not follow this discipline. I consider this to be a problem. Good answers are being neglected and deprived of their "vote reward". Bad answers do not receive feedback which might have helped the answerer to improve his approach to answering.
When I answer, and I receive zero votes and zero comments, I am disappointed. I want to know what came out of the time that I invested. I'll be happy to take positive and negative feedback.
Is the Stack Overflow system doing enough to encourage askers to follow up with every answer rigorously? What more could be done?

A: No one owes you feedback. Least of all, quasi-real-time feedback.
No one forces you to answer all questions. Least of all, questions asked by people who don't provide the feedback you crave.
Not everyone shares your concerns. You're not the only person who craves feedback on answers, but plenty of others follow a more r-selective approach.
So, if you care about feedback, check out a user's prior behavior before investing energy in answering that user's questions, and decide accordingly.

A: I agree with Shafique that most users do NOT know how sites like stack overflow work.  And that is partly the reason they don't give feedback.  I see nothing wrong with encouraging users to provide feedback, i.e. post the answer and then write in parenthesis (e.g. if the answer works for you please acknowledge that it did). Most people do recognize that time and energy, especially when there is no $ exchanged, is a SPECIAL thing! They just need to know how to 'say thanks-ask more questions-communicate' on a busy looking webpage with too many things to click.

A: I suspect that many users do not know what is expected of them. This is completely normal - when I was new I asked crap questions, too. I had to clean some of them up later when I "grew up".
This might be a cultural issue. Not very different from weak/eroding corporate culture. We have a steady instream of "culturally untrained" members which is eroding culture. Btw, culture for me means "the set of behaviors and attitudes in common use".
There is a fairly straight-forward way to establish culture/behaviors: tell people what is expected. What is good behavior that we will reward, and what is bad behavior that we will hold you accountable for? Often, people are good-willed and want to comply.
My proposal: the system should generate a message to the inbox/mailbox of the asker after a few days when it detects that a low level of feedback was given. The message should say something like:

"Hope you've been happy with the answers! The answerers are awaiting your feedback now. Please make sure to follow up with them to show your respect and to help them improve."

I'll leave the precise specification of this feature to the Stack Exchange team. Maybe we can even send the message (almost) always for one month and observe the difference in behavior. This could even be statistically determined by the level of activity per question.


text:
Q: Test if SSH private key has password protection I'm trying to test if ~/.ssh/id_rsa is actually password protected.
When you run ssh-keygen you can choose an empty password, and I'm trying to detect this.
Is that possible with a one-liner?

A: If you open the private key file in text editor you will be able to see ENCRYPTED in the second line of the RSA/DSA key file.
For example:
 -----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,373B504621779D53C72BADE597C531A0

A: If you execute:
ssh-keygen -y -f ~/.ssh/name_of_key

you will get key printed if there is no password like this:
ssh-keygen -y -f ~/.ssh/id_dsa
ssh-dss AAAAB3NzaC1kc3M....

If there is password of the key you will be asked for it

A: I don't have enough reputation to comment, so I add here.
Thanks to  @Ulrich-Schwarz , I extended his answer to check all my keys (the one i generated, so I have the puublic/private pair) in my $HOME/.ssh/ :
for l in $(ls $HOME/.ssh/*.pub)
do         key=${l%.*}
   if SSH_ASKPASS=/bin/false ssh-keygen -y -f $key < /dev/null > /dev/null 2>&1
   then
       echo -n "NO  password: "
   else
       echo -n "YES password: "
   fi
   echo ${key}
done


text:
Q: MQTT messages not received by ESP32 after deep sleep I have a battery operated ESP32 board (=client) and use deep sleep mode to save power. I want to receive mqtt messages that have been sent by Nodered to a broker while the board (client) was asleep. I use  async-mqtt-client/AsyncMQttClient.h (see github).
After a fresh reboot of the ESP32, messages are received by the ESP32 board properly. But when the board has awoken from it first sleep, the messages don't arrive. I added mqttClient.setCleanSession(false) to my initialisation code to allow "broken sessions". This does not help.
I started to subscribe to the topic(s) everytime (after a first boot or after waking up). When I only subscribe to the topic when no session is present (after if (sessionPresent == 0) ) the problem remains.
Does anyone have suggestions how to move on???
[EDIT]  I added my code here. It is in development, so full of snippets taken from different sources:
Arduino IDE

/* Code by FV for WIFI Lora 32(V2) board, derived from File / Examples / Heltec ESP32 Dev-Boards / ESP32 / ADC_Read_Voltage / Battery_power
 * The original example gives a correct battery voltage readout on the display and a raw value in the Serial output .
 * The aim is to modify the code to send MQTT readouts to a web-service
 * This requires establishing a Wifi connection (station mode) and introduction of an MQTT client
 *
*/

/*
* V1.0
* WiFi and MQTT operational
* Battery voltage readout sometimes gives high values
*   - are the used pins in the combined sketches compatible?
*   - does introduction of WiFi interfere with the battery measurement?
*   - is the combination of the two loop delay methods sloppy?
*   - is it lack of conversion time for the ADC?
*
* V1.1 added some extra code with settings to do ADC conversion properly
*
* V1.2 adding deep sleep to save battery power in idle time
*   - https://randomnerdtutorials.com/esp32-timer-wake-up-deep-sleep/
*   - https://raw.githubusercontent.com/RuiSantosdotme/ESP32-Course/master/code/DeepSleep/TimerWakeUp/TimerWakeUp.ino
*   - need to move the includes to the top of the code, to prevent an error when compiling RTC_DATA_ATTR int wakeupCount = 0;
*   - BUG: after waking up, connecting to the WiFi network does not work.
*          connection is OK after pressing the RST button.
* V1.3 created more reliable WiFi reconnect using WiFi events
*   - BUG: delivery of data stops, reason unknown. Battery voltage at the moment of "crash" was high enough.
*   - introduce tools for debugging:
*         * introduce logging, while not connected to serial port
*         * introduce ESP side logging (Use different levels. Set level in Preferences)
*         * introduce logging on cloud server (a.o. battery voltage, timestamp, deviceId)
*   - SOLVED: not all info printed to Serial, solved by moving display initialization
*   - added timers for optimization / rationalization of delays
*   - BUG: awakeDuration should be the longest duration of all, It isn't.
*   - introduce reporting of timers in wireless / battery mode (MQTT)
* V1.4 solve V1.3 issues
*   - must be able to use MQTT client in any scope
*   - Optimization of delays and uptime:
*     - successDuration takes most of the awake time. Room for improvement in speed of making connection with WiFi
* V1.5 SWITCH TO  Async MQTT Client Library,  https://randomnerdtutorials.com/esp32-mqtt-publish-bme280-arduino/
*   - see demo sketch: ESP-mqtt-publish
*   - added deviceId, a string representing the board's MAC adress in reverse order
*   - added MQTT topics containing the unique deviceId
*     * prevent using String variables. See
*   - a logging flag is present, which persists over reboots by storing it into flash memory
*     * further logging methods to be implemented
*   -
*
*

*/

/*
 * HelTec Automation(TM) Electricity detection example.
 *
 * Function summary:
 *
 * - Vext connected to 3.3V via a MOS-FET, the gate pin connected to GPIO21;  //BUT WHERE IS THE CODE THAT DOES THAT?
 *
 * - Battery power detection is achieved by detecting the voltage of GPIO13;  //SHOULD BE GPIO37    what is the meaning of GPIO36 in this sketch?
 *
 * - OLED display and PE4259(RF switch) use Vext as power supply;
 *
 * - WIFI Kit series V1 don't have Vext control function;
 *
 * HelTec AutoMation, Chengdu, China.
 * 成都惠利特自动化科技有限公司
 * https://heltec.org
 * support@heltec.cn
 *
 * this project also release in GitHub:
 * https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series
 *
*/

/*
Simple Deep Sleep with Timer Wake Up
=====================================
ESP32 offers a deep sleep mode for effective power
saving as power is an important factor for IoT
applications. In this mode CPUs, most of the RAM,
and all the digital peripherals which are clocked
from APB_CLK are powered off. The only parts of
the chip which can still be powered on are:
RTC controller, RTC peripherals ,and RTC memories

This code displays the most basic deep sleep with
a timer to wake it up and how to store data in
RTC memory to use it over reboots

This code is under Public Domain License.

Author:
Pranav Cherukupalli <cherukupallip@gmail.com>
*/
/*
   This sketch shows the WiFi event usage - Example from WiFi > WiFiClientEvents
   Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/
*/

#include "Arduino.h"
#include <Preferences.h>  //not required in Arduino IDE ( NOT TRUE !)
//https://randomnerdtutorials.com/esp32-save-data-permanently-preferences/
//also see info on how to remove a namespace

Preferences preferences;     //create an instance (preferences) of Preferences

#define PREFERENCES_READ_ONLY = false //use preferences in R/W mode

#include <Wire.h>
#include "heltec.h"         //study conditional includes/ compilation
//#include "esp_wifi.h"
#include <WiFi.h>
extern "C" {
  #include "freertos/FreeRTOS.h"
  #include "freertos/timers.h"
}
// https://github.com/marvinroger/async-mqtt-client
// https://github.com/marvinroger/async-mqtt-client/blob/master/docs/2.-API-reference.md
// Very important: As a rule of thumb, never use blocking functions in the callbacks (don't use delay() or yield()).
// Otherwise, you may very probably experience unexpected behaviors.
#include <AsyncMqttClient.h>

#define WIFI_SSID "XXXXXXXXXXXXXX"
#define WIFI_PASSWORD "XXXXXXXXXXXXXXX"
#define MQTT_USER "XXXXXXXXX"
#define MQTT_PASSWORD "XXXXXXXXXXXXXXX"

// Mosquitto MQTT Broker
#define MQTT_HOST IPAddress(192, XXXXXXXXXXX)
// For a cloud MQTT broker, type the domain name
//#define MQTT_HOST "example.com"
#define MQTT_PORT XXXXXXXX

bool enabled_sleepmode = true;
char deviceId[23] = "";
char deviceType[10] = "";
char deviceTopic[50] = "";

AsyncMqttClient mqttClient;
TimerHandle_t mqttReconnectTimer;
TimerHandle_t wifiReconnectTimer;

unsigned long previousMillis = 0;   // Stores last time temperature was published
const long interval = 10000;        // Interval at which to publish sensor readings

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  //mqttClient.setClientId("myESP");
  //mqttClient.setCredentials(MQTT_USER,MQTT_PASSWORD);
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      connectToMqtt();
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
      xTimerStart(wifiReconnectTimer, 0);
      break;
  }
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
  //test sub

  if (sessionPresent == 0){

  uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub);
  }

  mqttClient.publish("test/lol", 0, true, "test 1");
  Serial.println("Publishing at QoS 0");
  uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2");
  Serial.print("Publishing at QoS 1, packetId: ");
  Serial.println(packetIdPub1);

  uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3");
  Serial.print("Publishing at QoS 2, packetId: ");
  Serial.println(packetIdPub2);
     if (sessionPresent == 0){   //if no active previous session, subscribe. This assumes that subscription is not necessary when sessionPresent != 0

  uint16_t packetIdSub2a = mqttClient.subscribe("test/lol2", 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub2a);

  uint16_t packetIdSub1a = mqttClient.subscribe("test/lol1", 1);
  Serial.print("Subscribing at QoS 1, packetId: ");
  Serial.println(packetIdSub1a);
  uint16_t packetIdSub0a = mqttClient.subscribe("test/lol0", 0);
  Serial.print("Subscribing at QoS 0, packetId: ");
  Serial.println(packetIdSub0a);
   }

}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");
  if (WiFi.isConnected()) {
    xTimerStart(mqttReconnectTimer, 0);
  }
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}
void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("Publish received.");
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  qos: ");
  Serial.println(properties.qos);
  Serial.print("  dup: ");
  Serial.println(properties.dup);
  Serial.print("  retain: ");
  Serial.println(properties.retain);
  Serial.print("  len: ");
  Serial.println(len);
  Serial.print("  index: ");
  Serial.println(index);
  Serial.print("  total: ");
  Serial.println(total);

 //need to convert payload to properly readably info
  String messageTemp;
for (int i = 0; i < len; i++) {
//Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}

  Serial.print("  payload: ");
  Serial.println(messageTemp);

}

void onMqttPublish(uint16_t packetId) {
  Serial.print("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

//#include <ESP8266WiFi.h>
//#include <PubSubClient.h>   //Knoleary MQTT module

//WiFiClient espClient;
//PubSubClient mqtt_client(espClient);
//unsigned long lastMsg = 0;
//#define MSG_BUFFER_SIZE  (50)
//char msg[MSG_BUFFER_SIZE];
//int value = 0;

#define uS_TO_S_FACTOR 1000000  /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP  60        /* Time ESP32 will go to sleep (in seconds) */

RTC_DATA_ATTR int wakeupCount = 0;  //store in ULP, keep value while sleeping

bool loggingMode = false;
unsigned long wakeupTime; //milliseconds
unsigned long sleepTime; //milliseconds
unsigned long connectStart; //milliseconds
unsigned long connectSuccess; //milliseconds

//get unique deviceId, it contains the MAC address in reverse order
//later also get the device type and Rev

void get_deviceId() {
  uint64_t chipid = ESP.getEfuseMac(); // The chip ID is essentially its MAC address(length: 6 bytes).
  snprintf(deviceId, 23, "%04X%08X", (uint16_t)(chipid >> 32), (uint32_t)chipid);
}

void get_deviceType() {
  snprintf(deviceType, 23, "ESP32", "", "");
}

/*
Method to print the reason by which ESP32 has been awaken from sleep
*/

void wake_up_from_deep_sleep(){
  wakeupTime = millis();
  Serial.begin(115200);
  delay(10); //Take some time to open up the Serial Monitor //was 1000
  //Print the wakeup reason for ESP32
  print_wakeup_reason();

  // Open Preferences with my-app namespace. Each application module, library, etc
  // has to use a namespace name to prevent key name collisions. We will open storage in
  // RW-mode (second parameter has to be false).
  // Note: Namespace name is limited to 15 chars.
  preferences.begin("my-app", false);

  // Remove all preferences under the opened namespace
  //preferences.clear();

  // Or remove the counter key only
  //preferences.remove("counter");

  // Get the counter value, if the key does not exist, return a default value of 0
  // Note: Key name is limited to 15 chars.
  unsigned int counter = preferences.getUInt("counter", 0);

  // Increase counter by 1
  counter++;

  // Print the counter to Serial Monitor
  Serial.printf("Total nr of wakeups: %u\n", counter);

  // Store the counter to the Preferences
  preferences.putUInt("counter", counter);

  loggingMode = preferences.getBool("loggingMode", false);
  //loggingMode = true;
  // Close the Preferences
  preferences.end();

  Serial.println("loggingMode: " + String(loggingMode));
/*
  for(int i=0; i<17; i=i+8) {
    chipId2 |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
  }

*/

//  Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());   //ESP.getChipModel()

//  Serial.printf("This chip has %d cores\n", ESP.getChipCores());
//  Serial.print("Chip ID: "); Serial.println(chipId2);

get_deviceId();
Serial.println(deviceId);
get_deviceType();
Serial.println(deviceType);
//get device Ver ????

  //Increment boot number and print it every reboot
  ++wakeupCount;
  Serial.println("----- wakeupCount since last reboot: " + String(wakeupCount)+" -----");

  }

void put_loggingMode(bool my_value){

   preferences.begin("my-app", false);
   preferences.putBool("loggingMode", my_value);
   // Close the Preferences
   preferences.end();
  }

void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

  void prepare_and_go_for_sleep(){

  /*
  First we configure the wake up source
  We set our ESP32 to wake up every 5 seconds
  */
  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
  Serial.println("Setup ESP32 to sleep for " + String(TIME_TO_SLEEP) +
  " Seconds");

  /*
  Next we decide what all peripherals to shut down/keep on
  By default, ESP32 will automatically power down the peripherals
  not needed by the wakeup source, but if you want to be a poweruser
  this is for you. Read in detail at the API docs
  http://esp-idf.readthedocs.io/en/latest/api-reference/system/deep_sleep.html
  Left the line commented as an example of how to configure peripherals.
  The line below turns off all RTC peripherals in deep sleep.
  */
  //esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF);
  //Serial.println("Configured all RTC Peripherals to be powered down in sleep");

  /*
  Now that we have setup a wake cause and if needed setup the
  peripherals state in deep sleep, we can now start going to
  deep sleep.
  In the case that no wake up sources were provided but deep
  sleep was started, it will sleep forever unless hardware
  reset occurs.
  */

  //esp_wifi_disconnect();
  unsigned long disconnectTime = millis();
  sleepTime = millis();

  unsigned long awakeDuration = sleepTime - wakeupTime;
  Serial.println("awakeDuration " + String(awakeDuration));

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/timers/awakeDuration");

  mqttClient.publish(deviceTopic, 1, true, String(awakeDuration).c_str());
  unsigned long connectDuration = disconnectTime - connectStart;

  Serial.println("connectDuration " + String(connectDuration));

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/timers/connectDuration");
   mqttClient.publish(deviceTopic, 1, true, String(connectDuration).c_str());

  unsigned long successDuration = connectSuccess - connectStart;

  Serial.println("successDuration " + String(successDuration));

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/timers/successDuration");
   mqttClient.publish(deviceTopic, 1, true, String(successDuration).c_str());
    Serial.println("----- Waiting for going to sleep -----");
     delay(5000);
  Serial.println("----- Going to sleep now -----");
  Serial.println();

  Serial.flush();
  esp_deep_sleep_start();
  Serial.println("This will never be printed"); //unreachable code
  }

//battery parameters
#define Fbattery    3700  //The default battery is 3700mv when the battery is fully charged.

float XS = 0.00225;      //The returned reading is multiplied by this XS to get the battery voltage.
uint16_t MUL = 1000;
uint16_t MMUL = 100;

void setup(){

  wake_up_from_deep_sleep();

  //set logging mode
  loggingMode = true;
  //persist the value in the preferences
  put_loggingMode(loggingMode);

  Heltec.begin(true /*DisplayEnable Enable*/, false /*LoRa Enable*/, false /*Serial Enable*/);
  Heltec.display->init();
  Heltec.display->flipScreenVertically();
  Heltec.display->setFont(ArialMT_Plain_10);
  Heltec.display->drawString(0, 0, "WAKE UP");
  Heltec.display->display();
  delay(1);
  Heltec.display->clear();

  //setup WiFi and MQTT connections
  if (wakeupCount == 1) {

  Serial.println("setting up WiFi");
/* XXXXX
  setup_wifi();
XXXXX */
  mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
  wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);

  //find a way to use a unique MQTT clientId, the broker uses the clientId and does not need action by the user
  //see e.g.: https://www.cloudmqtt.com/blog/mqtt-what-is-client-id.html
  //you can re-use the MQTT clientId as an Id for the cloud service. Look up, if it can be retrieved automatically from messa content
  //otherwise the device may have to send the clientId to the cloud service
  //investigate if chipID or boardId is unique

  mqttClient.setClientId(deviceId);

  // If your broker requires authentication (username and password), set them below
  mqttClient.setCredentials(MQTT_USER, MQTT_PASSWORD);
  connectToWifi(); //and MQTT broker
  }
  else {
    Serial.println("alternative WiFi connect");
    /* XXXXX
    setup_wifi();
    XXXXX */
    mqttReconnectTimer = xTimerCreate("mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToMqtt));
    wifiReconnectTimer = xTimerCreate("wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void*)0, reinterpret_cast<TimerCallbackFunction_t>(connectToWifi));

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  //mqttClient.onSubscribe(onMqttSubscribe);
  //mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  mqttClient.setClientId(deviceId);

  //messages to the board do not arrive after wake-up
  //have a look at "clean sessions" vs "persistent sessions"

  mqttClient.setCleanSession(false);  //for interrupted sessions

  // If your broker requires authentication (username and password), set them below
   mqttClient.setCredentials(MQTT_USER, MQTT_PASSWORD);
  connectToWifi(); //and MQTT broker
    }

  Serial.println("Wait for WiFi... ");
  while (WiFi.status() != WL_CONNECTED) { }
  connectSuccess = millis();
  Serial.println("WIFI CONNECTED");
  while (mqttClient.connected() == false) { }
  Serial.println("MQTT CONNECTED");

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/deviceId");

   //report deviceId to cloud service
   uint16_t packetIdPubx = mqttClient.publish(deviceTopic, 2, true, deviceId);
   Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", deviceTopic, packetIdPubx);

    // DO SOMETHING USEFUL in setup
  Serial.println("something useful in setup()");
   //prepare ADC for battery voltage measurement
   //analogSetClockDiv(255); // 1338mS
   analogSetCycles(8);                   // Set number of cycles per sample, default is 8 and provides an optimal result, range is 1 - 255
   analogSetSamples(1);                  // Set number of samples in the range, default is 1, it has an effect on sensitivity has been multiplied
   analogSetClockDiv(1);                 // Set the divider for the ADC clock, default is 1, range is 1 - 255
   analogSetAttenuation(ADC_11db);       // Sets the input attenuation for ALL ADC inputs, default is ADC_11db, range is ADC_0db, ADC_2_5db, ADC_6db, ADC_11db
   analogSetPinAttenuation(36,ADC_11db); // Sets the input attenuation, default is ADC_11db, range is ADC_0db, ADC_2_5db, ADC_6db, ADC_11db
   analogSetPinAttenuation(37,ADC_11db);
                                        // ADC_0db provides no attenuation so IN/OUT = 1 / 1 an input of 3 volts remains at 3 volts before ADC measurement
                                        // ADC_2_5db provides an attenuation so that IN/OUT = 1 / 1.34 an input of 3 volts is reduced to 2.238 volts before ADC measurement
                                        // ADC_6db provides an attenuation so that IN/OUT = 1 / 2 an input of 3 volts is reduced to 1.500 volts before ADC measurement
                                        // ADC_11db provides an attenuation so that IN/OUT = 1 / 3.6 an input of 3 volts is reduced to 0.833 volts before ADC measurement
//   adcAttachPin(VP);                     // Attach a pin to ADC (also clears any other analog mode that could be on), returns TRUE/FALSE result
//   adcStart(VP);                         // Starts an ADC conversion on attached pin's bus
//   adcBusy(VP);                          // Check if conversion on the pin's ADC bus is currently running, returns TRUE/FALSE result
//   adcEnd(VP);

   adcAttachPin(36);
   adcAttachPin(37);

   //WiFi LoRa 32        -- hardare versrion ≥ 2.3
   //WiFi Kit 32         -- hardare versrion ≥ 2
   //Wireless Stick      -- hardare versrion ≥ 2.3
   //Wireless Stick Lite -- hardare versrion ≥ 2.3
   //Battery voltage read pin changed from GPIO13 to GPI37

   delay(100);

   //measure ????? voltage on pin 36
   adcStart(36);
   while(adcBusy(36));

   //publish ????? voltage

   uint16_t c2  =  analogRead(36)*0.769 + 150;
   adcEnd(36);
   Serial.printf("voltage input on GPIO 36: ");
   Serial.println(analogRead(36));

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/Vin");
   uint16_t packetIdPub0 = mqttClient.publish(deviceTopic, 1, true, String(c2).c_str());

   //uint16_t packetIdPub0 = mqttClient.publish(deviceTopic, 2, true, "HELLO");
   Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", deviceTopic, packetIdPub0);
   Serial.printf("Message: %.2f \n", c2);

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/topic1");

   uint16_t packetIdPubt = mqttClient.publish(deviceTopic, 1, true, "device specific info");
   Serial.printf("Pablishing on topic %s at QoS 1, packetId: %i", deviceTopic, packetIdPubt);
   Serial.printf("Message: %s \n", "device specific info");

      Serial.println("-------------");
   //measure battery voltage on pin 37
   adcStart(37);
   while(adcBusy(37));
   uint16_t c  =  analogRead(37)*XS*MUL;
   adcEnd(37);

   //publish battery voltage
   Serial.println(analogRead(37));

   strcpy(deviceTopic,"");
   strcat(deviceTopic,"fleet/");
   strcat(deviceTopic,deviceType);
   strcat(deviceTopic,"/");
   strcat(deviceTopic,deviceId);
   strcat(deviceTopic,"/Vbat");

   uint16_t packetIdPuba = mqttClient.publish(deviceTopic, 2, true, String(c).c_str());
   //uint16_t packetIdPuba = mqttClient.publish(deviceTopic, 1, true, "HELLO");
   Serial.printf("Publishing on topic %s at QoS 1, packetId: %i", deviceTopic, packetIdPuba);
   Serial.printf("Message: %.2f \n", c);

   Heltec.display->drawString(0, 0, "Remaining battery still has:");
   Heltec.display->drawString(0, 10, "Vbat =");
   Heltec.display->drawString(35, 10, (String)c);
   Heltec.display->drawString(60, 10, "(mV)");

   Heltec.display->drawString(0, 20, "Vin   = ");
   Heltec.display->drawString(33, 20, (String)c2);
   Heltec.display->drawString(60, 20, "(mV)");

   Heltec.display->display();

  delay(100);
  //delay(10000); // long delay for visibility in network device list
  if (enabled_sleepmode) {prepare_and_go_for_sleep();}
}

void loop(){
  //This is not going to be called when going to sleep in setup()
  // DO SOMETHING USEFUL in loop
    Serial.println("something useful in loop()");
    delay(1000);
  //prepare_and_go_for_sleep();
}

A: While in deep sleep the broker is going to mark the client as offline.
Setting the Clean Session flag to false is a good start, but you will also need to make sure you have subscribed at QOS 1 or 2 not 0 so the broker knows to queue the messages while the client is offline.

A: When you enter deep-sleep your connections are dropped and the server may decide to mark your node as offline.
You subscribe to topics with different QoS'. Some subscriptions use QoS 0, which tells the broker to try to send messages into those topics just once, without retries.
If you specify QoS 1 or QoS 2, the broker will try to resend those messages when it detects your node is alive again.
There is a standards compliant project that you could find handy for debugging your device, MQTTnet, you can implement a very simple broker with it, enable its logging support, and play with its parameters. It can provide nice and clear clues, yet you'll need VisualStudio, the community editions works well, and some C# knowledge.

A: It might be possible that the behaviour that I observe is due to the limitations of the client. See: this link. Any comments on that?
If this limitation is really the cause, I don't have to pursue this path further.
Thanks


text:
Q: Not storing the EditText vlaue in a string I am having a problem in storing a Edit able Text value in a string. I just want to store a value that user enter store it in some variable. i used toast just after storing a value to check whether the value is store in it or not and toast doesn't show any value. i try the following code but didnt find it helpful.
    package com.example.electropollsys;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class CreateAcc extends Activity {
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
             WindowManager.LayoutParams.FLAG_FULLSCREEN);

     setContentView(R.layout.create_acc);

     final Button b = (Button) findViewById(R.id.button3);
     b.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {

             Intent i = new Intent(CreateAcc.this, SignIn.class);
            i.addFlags(
                Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
         }

     });

     final Button a = (Button) findViewById(R.id.button1);
     a.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("ShowToast")
            public void onClick(View v){

                EditText input1= (EditText)findViewById(R.id.fname1);
                String fname = input1.getEditableText().toString();

                EditText input2= (EditText) findViewById(R.id.lname1);
                String lname = input2.getEditableText().toString();

                Toast.makeText(CreateAcc.this,"...."+fname+"...." , Toast.LENGTH_LONG);
                Toast.makeText(CreateAcc.this,"...."+lname+"...." , Toast.LENGTH_LONG);

              }
         });
    }
    }

A: Try:
Toast.makeText(CreateAcc.this,"...."+fname+"...." , Toast.LENGTH_LONG).show();
Toast.makeText(CreateAcc.this,"...."+lname+"...." , Toast.LENGTH_LONG).show();

Toasts do not show unless the show() method is called. the makeText() method returns a Toast object which you must use to display the toast.
You normally get a lint warning about this, but you seem to have suppressed it with @SuppressLint("ShowToast").

A: You did like way.
Toast.makeText(CreateAcc.this,"...."+fname+"...." , Toast.LENGTH_LONG);

Using this its initiate the toast object and return the object but to show the toast notification you need to call show method on that object.
Instead of this write this.
Toast.makeText(CreateAcc.this,"...."+fname+"...." , Toast.LENGTH_LONG).show();

OR
Toast toast = Toast.makeText(CreateAcc.this,"...."+fname+"...." , Toast.LENGTH_LONG);
toast.show();

A: You forgot to add .show() at the end.
Refer http://developer.android.com/guide/topics/ui/notifiers/toasts.html
http://thedevelopersinfo.wordpress.com/2009/10/23/showing-toast-in-android/


text:
Q: Is there a Python function to calculate the diff based on the first element? I have a pandas dataframe, like this example:
df = pd.DataFrame({
    'steps': ['step1','step2', 'step3', 'step4','step5'],
    'qty': [100, 95, 92, 87, 78]},
    index=[0,1,2,3,4])

I would like to calculate the percentage of abandonments in each step, based on the first value.
Output:
Steps   qty Tx %
Step1   100 0,00%
Step2   95  5,00%
Step3   92  3,00%
Step4   87  5,00%
Step5   78  9,00%

I thought about using pd.pct_change(), but it doesn't work as expected.
The manual calculation would be something like:

values = [(1 - df['qty'][0]/df['qty'][0]) - (1-df['qty'][0]/df['qty'][0]),
          (1 - df['qty'][1]/df['qty'][0]) - (1-df['qty'][0]/df['qty'][0]),
          (1 - df['qty'][2]/df['qty'][0]) - (1-df['qty'][1]/df['qty'][0]),
          (1 - df['qty'][3]/df['qty'][0]) - (1-df['qty'][2]/df['qty'][0]),
          (1 - df['qty'][4]/df['qty'][0]) - (1-df['qty'][3]/df['qty'][0])]

However, I believe that this is not scalable, especially considering increasing the number of steps or time periods.
Could someone help me think of some function or show a rationale that can make this calculation simpler?

A: You can use pd.Series.shift to shift the qty column one element down. Then simply calculate the difference between the shifted column and itself:
import pandas as pd

df = pd.DataFrame({
    'steps': ['step1','step2', 'step3', 'step4','step5'],
    'qty': [100, 95, 92, 87, 78],
})

df['Tx %'] = df.qty.shift() - df.qty
print(df)

# output:
#    steps  qty  Tx %
# 0  step1  100   NaN
# 1  step2   95   5.0
# 2  step3   92   3.0
# 3  step4   87   5.0
# 4  step5   78   9.0

A: This works:
# you have
values = [(1 - df['qty'][0]/df['qty'][0]) - (1-df['qty'][0]/df['qty'][0]),
          (1 - df['qty'][1]/df['qty'][0]) - (1-df['qty'][0]/df['qty'][0]),
          (1 - df['qty'][2]/df['qty'][0]) - (1-df['qty'][1]/df['qty'][0]),
          (1 - df['qty'][3]/df['qty'][0]) - (1-df['qty'][2]/df['qty'][0]),
          (1 - df['qty'][4]/df['qty'][0]) - (1-df['qty'][3]/df['qty'][0])]

# 1s cancel out, so the above is equivalent to
values = [( - df['qty'][0]/df['qty'][0]) + (df['qty'][0]/df['qty'][0]),
          ( - df['qty'][1]/df['qty'][0]) + (df['qty'][0]/df['qty'][0]),
          ( - df['qty'][2]/df['qty'][0]) + (df['qty'][1]/df['qty'][0]),
          ( - df['qty'][3]/df['qty'][0]) + (df['qty'][2]/df['qty'][0]),
          ( - df['qty'][4]/df['qty'][0]) + (df['qty'][3]/df['qty'][0])]

# since every element is divided by df['qty'][0], you can take it out, so the above is equivalent to
values = [( - df['qty'][0] + df['qty'][0]) / df['qty'][0],
          ( - df['qty'][1] + df['qty'][0]) / df['qty'][0],
          ( - df['qty'][2] + df['qty'][1]) / df['qty'][0],
          ( - df['qty'][3] + df['qty'][2]) / df['qty'][0],
          ( - df['qty'][4] + df['qty'][3]) / df['qty'][0]]

#the RHS is the LHS shifted one level down, so it's equivalent to:
values = (- df['qty'] + df['qty'].shift()).fillna(0) / df['qty'][0]

# in summary
df['Tx %'] = (df['qty'].shift() - df['qty']).fillna(0) / df['qty'][0] * 100
   steps  qty  Tx %
0  step1  100   0.0
1  step2   95   5.0
2  step3   92   3.0
3  step4   87   5.0
4  step5   78   9.0

A: This response my doubt:
df['Tx %'] = round(((1 - df.qty / df.qty[0]) - (1- df.qty.shift() / df.qty[0]))*100, 2)
Thanks to @jfaccioni


text:
Q: Eager Loading of Associations using MongoMapper I'm looking to Eager Load Associated Documents using MongoMapper. Say I have an author with a :has_one condition to a Post, I should be able to load the author using a single query
Post.find(:all, :include => :author)

Any suggestions?

A: UPDATE: The code below is just as models workflow.. I tried it after some coding and it didnt work!
Lets say you have Post model and User model.
User has_many posts, and you want All the users (authors) with their posts.
Here a tip to handle it. and my example is fetching one post.
post.rb
class Post
  include MongoMapper::Document

  key :title, String
  key :body, String
  key :user_id, ObjectId

  belongs_to :user

end

and user.rb
class User
  include MongoMapper::Document
  key :name
  many :posts, :embed => :title
end

Now,
u = User.first
p = u.posts.first

puts p.title # read it from embedded doc
puts p.body # lazy loading

The trick here is to embed the mostly common fields like the name of the user, _id, user slug, etc.
I didnt test what above, but you have to give a try!
Best
--Amr


text:
Q: Unable to detect droppable event on body using jquery UI I am creating to create drag and drop functionality using jquery UI. However , the drop event isn't getting triggered when I drop something on the body
Here is my demo code.Any help will be appreciated.
http://jsfiddle.net/ysptW/1/

A: Change
 $( "body" ).droppable({

to:
 $( "#droppable" ).droppable({

Here is the jsFiddle
UPDATE
You almost had it, the problem was that your body didn't have a height, which was identified by giving it a css border.  Once a height was set using body{height:200px;} then it worked.
new jsFiddle in response to comments:

A: Update your code from
$("body").droppable

to
$("#droppable").droppable...

You can check the same at
    http://jsfiddle.net/anubhavranjan/yEvsY/
For more info, visit http://jqueryui.com/droppable


text:
Q: Standard Day Chart in R My DataFrame looks like this
  UserId   Date  Time ObservationValue
1     10 Jan 01 10:00              200
2     10 Jan 01 11:30              120
3     10 Jan 02 08:00               50
4     10 Jan 03 05:30               45

I wanted to plot a standard day chart in R for each userid
X axis is Time
Y axis is ObservationValue
Am able to scatter plot all these points
But I am unable to differentiate the different dates in the scatter plot of points
Hence I wanted a line for each DATE in the graph
i.e. For UserId 10
Jan 01 must be plotted as a line
Jan 02 must be plotted as a line
both preferably in a different color.
How do I go about it?

A: ggplot(DataFrame, aes(Time, ObservationValue, color=Date)) + geom_line()

or if you want different UserIds in different plots:
ggplot(DataFrame, aes(Time, ObservationValue, color=Date)) + geom_line() + facet_wrap(~UserId)

A: If you want to make a plot for a specific UserId, you can also use:
ggplot(DataFrame[DataFrame&UserId==10,], aes(Time, ObservationValue, color=Date)) +
geom_line()


text:
Q: How to generate Swagger with format application/json only? In the Swagger file by default both response formats, JSON:API and application/json are included.
This causes problems when generating Java classes and prevents the client from compiling.
I tested this with two different compilers
Swagger Code Generator 3.0.35 https://mvnrepository.com/artifact/io.swagger.codegen.v3/swagger-codegen/3.0.35 as well as
OpenAPI Generator in different versions https://mvnrepository.com/artifact/org.openapitools/openapi-generator-cli/3.3.4.
As a workaround the Swagger file currently has to be manually adjusted and the JSON:API format has to be deleted, which causes a lot of effort during updates.
Is the generation of the Swagger file possible containing only the format application/json?

A: No that is not possible and IMHO should also not be possible, as that would undermine the whole point of having an OpenApiSchema.
The OpenApi schema file is a specification of the shopware API, and as shopware offers both response formats it does not make sense to generate OpenApi files that are incomplete. As a specification that is not complete is by definition no specification anymore.
IMHO the issues lies with the code generators you wanna use. As they should skip formats that they don't support, instead of erroring.


text:
Q: How do I view Transaction Assistant entries with the Kronos API? I want to use the Kronos Workforce Central API to view and edit queries in the Kronos Transaction Assistant.
I can login to Kronos by submitting an XML login request to /wfc/XmlService, but I haven't found any documentation for accessing the Transaction Assistant.
<Kronos_WFC version = '1.0'>
    <Request
        Object = 'System'
        Action = 'Logon'
        Username = 'SomeUsername'
        Password = 'SomePassword'
     />
</Kronos_WFC>

How do I retrieve Transaction Manager entries in Kronos WFC v6.3 with the Kronos API?

A: According to the Workforce Central v6.3 Timekeeping Developer's Guide (login required), you can retrieved failed XML transactions from the Transaction Assistant with <FailedXMLTransaction>.

FailedXMLTransaction Tag
The FailedXMLTransaction tag provides information about an XML transaction
  that has failed an attempt to process an XML request. It is used to retrieve or modify failed XML transaction information.
Note: This tag provides information for the Transaction Assistant.

You can use the Load action to view entries from the Transaction manager.

Load
Returns all failed transactions for the specified SourceName and
  TransactionType. You must specify at least one of these properties
  with the Load action; if you do not, an error is returned.
Return Value Type: Zero or more FailedXMLTransaction tags
Optional Properties: SourceName, TransactionType

The XML request below retrieves failed Pay Code Edits that were submitted by the Workforce Integration Manager.
<Kronos_WFC version='1.0'>
    <Request Action='Load'>
        <FailedXMLTransaction SourceName='WIM' TransactionType='Pay Code Edits'/>
    <Request>
</Kronos_WFC>

As for editing transactions, I unfortunately couldn't find any way to do this with the XML API in v6.3.


text:
Q: Can I run mongoimport as a part of Jenkins build step I am running a job which produces a json output file and I want to dump the file contents into mongo as a part of build step but when I run mongoimport the job fails saying mongoimport command not found
Below is the command am using as a part of build step shell script:
'''mongoimport --uri "dbString" --drop --collection col-name --file file-path-in-workspace -- jsonArray'''


text:
Q: Problems with rsGetElementAt_uchar4 I'm trying to implement a median filter in RenderScript. But the work of the code is not stable. Reading elements not from the current line rsGetElementAt_uchar4 (inputAlloc, x , y + a ) causes errors. What is the problem ? Is there an example of such a filter using RenderScript?
    #pragma version(1)
#pragma rs java_package_name(a.myapplication)
#pragma rs_fp_relaxed

rs_allocation inputAlloc;
int bWidht, bHeight;

static uchar4 arrpix[9];
static uchar4 buff;

uchar4 __attribute__((kernel)) median(uchar4 in, uint32_t x, uint32_t y)
{

uchar4 arrpix[9];
uchar4 buff;

                      if((x<bWidht) && (y<bHeight)){
        arrpix[0] = rsGetElementAt_uchar4(inputAlloc, x -1 , y - 1);
        arrpix[1] = rsGetElementAt_uchar4(inputAlloc, x    , y - 1);
        arrpix[2] = rsGetElementAt_uchar4(inputAlloc, x +1 , y - 1);

        arrpix[3] = rsGetElementAt_uchar4(inputAlloc, x -1 , y    );
        arrpix[4] = in;
        arrpix[5] = rsGetElementAt_uchar4(inputAlloc, x +1 , y    );

        arrpix[6] = rsGetElementAt_uchar4(inputAlloc, x -1 , y + 1);
        arrpix[7] = rsGetElementAt_uchar4(inputAlloc, x    , y + 1);
        arrpix[8] = rsGetElementAt_uchar4(inputAlloc, x +1 , y + 1);

for(int i=0; i<4; i++)

for(int i=0; i<=8; i++){

if(arrpix[i].r>arrpix[i+1].r){
buff.r = arrpix[i].r; arrpix[i].r = arrpix[i+1].r;
arrpix[i+1].r = buff.r;}

if(arrpix[i].g>arrpix[i+1].g){
buff.g = arrpix[i].g; arrpix[i].g = arrpix[i+1].g;
arrpix[i+1].g = buff.g;}

if(arrpix[i].b>arrpix[i+1].b){
buff.b = arrpix[i].b; arrpix[i].b = arrpix[i+1].b;
arrpix[i+1].b = buff.b;}

}
}
    return arrpix[4];
}

A: You need to check x>0 and y>0 because 0-1 =-1
Bottom loops don't look completely correct either. Can you fix the spacing and did you mean to use i in both loops?


text:
Q: I'm having trouble with my do while loop So I am a beginner using java, and I am trying to have the user enter a temperature in Fahrenheit and convert it into Celsius, all while making sure the use enters a valid number for the double variable instead of letters. and than displaying in back to the user. I am particularly having trouble with the loop. Here is my code.
import java.util.Scanner;

public class TempConverter
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        double temp;
        do
        {
            System.out.print("Please enter temperature in Fahrenheit: ");
            while(!in.hasNextDouble())
            {
                System.out.println("ERROR. Please enter a valid temperature: ");
                in.nextDouble();
            }
            temp = in.nextDouble();
        }
        double finalTemp = ((temp - 32)*5)/9;
        System.out.print("Celsius value of Fahrenheit value " + temp + " is " + finalTemp + ".");
    }
}

A: The while must come after. It will keep iterating until the condition in the while has been met.
    do
    {
        System.out.print("Please enter temperature in Fahrenheit: ");
            System.out.println("ERROR. Please enter a valid temperature: ");
            in.nextDouble();
        temp = in.nextDouble();
    }
    while(!in.hasNextDouble())


text:
Q: get-buffer-window-list throws error in Emacs 24 if name not found I have code which looks for an open window with one of three commonly used names, "*shell*", "*stata*", "stata".
I am running the following elisp code to check for each name:
(setq stata-win (get-buffer-window-list "*shell*"))
(if (eq (length stata-win) 0) (setq stata-win (get-buffer-window-list "*stata*")))
(if (eq (length stata-win) 0) (setq stata-win (get-buffer-window-list "stata")))

(car stata-win)

This previously worked, but the first line now triggers an error if a window with the name shell is not found. How can I test for the existence of an open window matching a name without triggering an error if the name is not found?

A: get-buffer-window-list errors out only if the buffer does not exist.
If the buffer exists but is not displayed in any window, the function returns nil.
You can check for buffer existence using get-buffer.
Thus, what you want is:
(defun get-buffers-window (buffer-names)
  (let (found buf)
    (while (and (null found)
                (setq buf (pop buffer-names)))
      (setq found
            (and (get-buffer buf)
                 (car (get-buffer-window-list buf)))))
    found))
(get-buffers-window '("*shell*" "stata" "*stata*"))

Note that for lists foo the forms
(if foo ...)

and
(if (< 0 (length foo)) ...)

are equivalent, but the former does not traverse the list (and thus faster) and also more idiomatic.


text:
Q: Creating Columns for Hour of Day and date based on datetime column How can I create a new column that has the day only, and hour of day only based of a column that has a datetime timestamp?
DF has column such as:
   Timestamp
2019-05-31 21:11:43
2018-11-21 18:01:00
2017-11-21 22:01:04
2020-04-15 11:01:00
2017-04-20 04:00:33

I want two new columns that look like below:
   Day      | Hour of Day
2019-05-31     21:00
2018-11-21     18:00
2017-11-21     22:00
2020-04-15     11:00
2017-04-20     04:00

I tried something like below but it only gives me a # for hour of day,
df['hour'] = pd.to_datetime(df['Timestamp'], format='%H:%M:%S').dt.hour

where output would be 9 for 9:32:00 which isnt what I want to calculate
Thanks!

A: Please try dt.strftime(format+string)
df['hour'] = pd.to_datetime(df['Timestamp']).dt.strftime("%H"+":00")

Following your comments below. Lets Try use df.assign and extract hour and date separately
df=df.assign(hour=pd.to_datetime(df['Timestamp']).dt.strftime("%H"+":00"), Day=pd.to_datetime(df['Timestamp']).dt.date)

A: You could convert time to string and then just select substrings by index.
df = pd.DataFrame({'Timestamp': ['2019-05-31 21:11:43', '2018-11-21 18:01:00',
                             '2017-11-21 22:01:04', '2020-04-15 11:01:00',
                             '2017-04-20 04:00:33']})
df['Day'], df['Hour of Day'] = zip(*df.Timestamp.apply(lambda x: [str(x)[:10], str(x)[11:13]+':00']))


text:
Q: Dropdown-List - Multi-Selection should add text to Textbox in several Lines Hello everybody! :)
I've made an easy random Drop-Down-list on our "Price-Request-Site" with all the Items in the List that we sell to our Customers.http://i.imgur.com/qg5jj0p.jpg
And because they need to request Prices for those items, they can select one or more items from the Dropdown-List and the Output goes to a "simple Textbox"
You have to Select one or more Items from that DropDown-list and the JavaScript should "paste" the selected List-items to the Textbox.
The Textbox is already a part of a "Formular" to send the Textbox-input as an E-mail.

My JavaScript does the following at the moment:
If click an Item from the List, the Item-name appears in the Text-box in the first Line.
If I click a Second OR/AND another item, the JavaScript will overwrite the now existing "Item/Textline" from the first Line in the Textbox.
http://i.imgur.com/9DoY7cS.jpg"
I need the following solution to my JavaScript and it should be easy as possible:
When I click to another Item from the List, it should be added to the Second Line, When I click another Item, it should be added in the next (3rd) Line...
Background-information:
This Script should make it easier for the Customer to write a Price-Request-EMail to us.
(Without searching through the Shop and looking for or Article-Numbers, instead he can choose Products from the Dropdown-list with an Output to this Email-form/textbox)
function favsports()
{
var mylist=document.getElementById("mylist");
document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text;
}

I would be very Happy if someone could help me with my issue, i'am really new to JS :D


text:
Q: Creating NSDictionary with Initial Name to Sort I'm trying to merge the code from this link into my own application while using my own dictionary. I have had several problems, however.
My code produces this kind of dictionary (because I'm using a web service to get this data from a MySQL database):
{audiences = ({
            name = ABDUL;
            id = 1;
        },{
            name = ELSA;
            id = 2;
        },...etc)}

However, I want a dictionary like this:
audiences = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
              @"C" : @[@"Camel", @"Cockatoo"],
              @"D" : @[@"Dog", @"Donkey"]};

Which, in my case, would appear like this:
audience = @{@"A":@[@"Abdul"],
             @"E":@[@"Elsa"]};

To summarize my problems:
1) How can I create an NSDictionary using only the names (no id)?
2) The dictionary including initial in it
Thanks for your help, I'm a newbie in Xcode and Objective-C, so please forgive me if I'm asking a noob question. Also, please bear with my bad English. Thanks in advance.

A: So, your initial data structure received from the web service is (re-expressed in Cocoa):
NSDictionary* data = @{ @"audiences" : @[
                                          @{ @"name" : @"ABDUL",
                                             @"id" : @1 },
                                          @{ @"name" : @"ELSA",
                                             @"id" : @2 },
                                        ] };

You can build the data structure you describe like this:
NSMutableDictionary* audience = [NSMutableDictionary dictionary];
for (NSDictionary* person in data[@"audiences"])
{
    NSString* name = person[@"name"];
    if (![name length])
        continue;

    NSRange range = [name rangeOfComposedCharacterSequenceAtIndex:0];
    NSString* key = [[name substringWithRange:range] uppercaseString];
    NSMutableArray* list = audience[key];
    if (!list)
    {
        list = [NSMutableArray array];
        [audience setObject:list forKey:key];
    }
    [list addObject:name];
}

A: I'm going to assume that you don't want the initials to be case sensitive.
NSArray *audiences = @[
                        @{ @"name" : @"ABDUL", @"id" : @1 },
                        @{ @"name" : @"ELSA", @"id" : @2 },
                        @{ @"name" : @"erik erikson", @"id" : @3 },
                        @{ @"name" : @"Leeroy Jenkins", @"id" : @-1 },
                        @{ @"name" : @"", @"id" : @4 },
                      ];

NSMutableDictionary *audienceMembersByInitial = [NSMutableDictionary dictionary];
for (NSDictionary *audienceMember in audiences) {
    NSString *name = audienceMember[@"name"];
    if (name.length > 0) {
        NSString *initial = [[name substringToIndex:1] uppercaseString];
        NSArray *audienceMembersWithInitial = audienceMembersByInitial[initial] ?: @[];
        audienceMembersByInitial[initial] = [audienceMembersWithInitial arrayByAddingObject:name];
    }
}
return [audienceMembersByInitial copy];

Output is...
@{
  @"A" : @[ @"ABDUL" ],
  @"E" : @[ @"ELSA", @"erik erikson" ],
  @"L" : @[ @"Leeroy Jenkins" ],
};


text:
Q: Adding minutes by literals ho could I manipulate some Int adding them as minutes and sum them? the result should be in hours and minutes just like 1:15 or 6:30.
My playground gives 1.25 but I expected 1.15
struct standardDayOfWork {

var dailyHours : Double = 0

}

var dayToUse = standardDayOfWork()

enum hourFractions : Double {

    case quarter = 15
    case half = 30
    case threeQuarter = 45
    case hour = 60
}

dayToUse.dailyHours += hourFractions.half.rawValue
dayToUse.dailyHours += hourFractions.half.rawValue

dayToUse.dailyHours += hourFractions.quarter.rawValue

var total = dayToUse.dailyHours / 60   //1.25

A: Because in the decimal system a quarter is 0.25.
To get numeric 1.15 you could use this weird expression:
var total = Double(Int(dayToUse.dailyHours) / 60) + (dayToUse.dailyHours.truncatingRemainder(dividingBy: 60) / 100.0)

Or if you can live with a formatted "hh:mm" string I'd recommend
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.string(from: dayToUse.dailyHours * 60)


text:
Q: Encoding a GET using OAuth in Ruby Twitter API I'm trying to write simple Ruby on Rails web app that logs in to Twitter via oAuth and gets the user's list of followers, without using an existing oAuth library. Using their guide at https://dev.twitter.com/docs/auth/oauth, I've managed to get logging in working correctly and thus have a subsequent outh_token and oauth_token_secret. However, when trying to encode the GET request for the logged in user's followers, I keep getting a 401 "This method requires authentication."
Using my code and their sample data, I can see that I'm generating the oauth_signature correctly. I may be generating the signature_base_string incorrectly, but seeing as it works ok when logging in, I don't see how it could be wrong the second time. The methods are part of a class, so the consumer key and secret are obviously class variables.
Relevant code is below. It's the output of the HTTP GET in 'followees' that's giving the 401. I'm hoping this is something ridiculously obvious that I'm just missing from looking at this too long! I know I have the right values passed to the function as parameters. Thanks.
  def followees(auth_token, auth_token_secret, user_id)
    method = 'GET'
    base_uri = 'https://api.twitter.com/1/friends/ids.json'
    params = {
      'cursor' => '-1',
      'oauth_consumer_key' => @@consumer_key,
      'oauth_nonce' => generate_nonce, #not shown, no need!
      'oauth_signature_method' => 'HMAC-SHA1',
      'oauth_token' => auth_token,
      'oauth_timestamp' => Time.now.to_i.to_s,
      'oauth_version' => '1.0',
      'user_id' => user_id
    }
    signature_base_string = signature_base_string(method, base_uri, params)
    params['oauth_signature'] = url_encode(sign(@@consumer_secret + '&' + auth_token_secret, signature_base_string))
    header = header(params)
    base_uri += '?cursor=-1&user_id=' + user_id
    url = URI.parse(base_uri)
    http = Net::HTTP.new(url.host, 443)
    http.use_ssl = true
    resp, data = http.get(url.path, { 'Authorization' => header })
  end

  def signature_base_string(method, uri, params)
    encoded_params = params.sort.collect{ |k, v| url_encode("#{k}=#{v}") }.join("%26")
    method + '&' + url_encode(uri) + '&' + encoded_params
  end

  def url_encode(string)
    CGI::escape(string)
  end

  def sign(key, base_string)
    digest = OpenSSL::Digest::Digest.new('sha1')
    hmac = OpenSSL::HMAC.digest(digest, key, base_string)
    Base64.encode64(hmac).chomp.gsub(/\n/, '')
  end

  def header(params)
    header = "OAuth "
    params.each do |k, v|
      header += "#{k}=\"#{v}\", "
    end
    header.slice(0..-3)
  end

A: Figured it out. Needed a break to step back from it! Basically, the last line in followees wasn't including the GET data, so
resp, data = http.get(url.path, { 'Authorization' => header })

should've been
resp, data = http.get(url.to_s, { 'Authorization' => header })

I had copied the code for POSTing, hence just url.path was being used there.


text:
Q: Change the content of text file in onclick() method of dialogue box Problem is the string which writes to outputstreamswriter has correct value but in try/catch block within onclick() method of dialogue box outputstreamwriter is not working. My file name is default.txt i'm sure file name has nothing to do with the problem. outputstreamwriter does not change the content of file whatsoever i've tried bufferwriter or fileoutputstream but nothing seems to work. Kindly help i'm losing my mind from days now!
here's the code.
package zafus.personalitymeter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

public class ChoseAnswers extends Activity {
private final String TAG="";
public String vale;

public List<String> obj;
public int numOfAnswers=0;
//public RelativeLayout mylayout =(RelativeLayout)findViewById(R.id.calayout);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chose_answers);
    obj=null;
    obj=readFromFile("answer.txt", this);
    numOfAnswers=Integer.valueOf(obj.get(0).toString());
    int i=1;
    LinearLayout mylayout =(LinearLayout)findViewById(R.id.linearLayout1);

    while(i<=numOfAnswers){
        Button tt = new Button(this);
        tt.setText(obj.get(i));
        tt.setId(i+1);
        tt.setPadding(5, 10, 5, 10);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        tt.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                vale=((Button)v).getText().toString();
                AlertDialog.Builder dlgAlert1  = new AlertDialog.Builder(ChoseAnswers.this);
                dlgAlert1.setMessage("Show this answer as a result of next test?");

                dlgAlert1.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        obj=null;
                        obj=readFromFile("default.txt", ChoseAnswers.this);
                        obj.set(1,vale);
                        String receiveString = "";
                        int num=Integer.valueOf(obj.get(0))+2;
                        StringBuilder ab = new StringBuilder();
                        int i=0;
                        for(;i<num;i++){
                            ab.append(obj.get(i)+"\n");
                        }

                        receiveString=ab.toString();

                        try {
                            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("default.txt", Context.MODE_PRIVATE));
                             //outputStreamWriter.write("");
                            outputStreamWriter.write(receiveString);
                            outputStreamWriter.close();
                            }

                        catch (IOException e) {
                            Log.e(TAG, "File write failed: " + e.toString());
                        }

                        ChoseAnswers.this.finish();
                    }});

                dlgAlert1.setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                    }});
            dlgAlert1.show();

            }
        });
        if (i == 1){

            params.setMargins(0, 150, 0, 20);

        }
        else{
            params.setMargins(0, 20, 0, 20);
        }
        tt.setLayoutParams(params);
        tt.setBackgroundResource(R.drawable.bxml);
        tt.setTextColor(Color.parseColor("#330011"));
        mylayout.addView(tt);

       i++;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.choseanswers, menu);
    return true;
}

public static List<String> readFromFile(String fileName, Context context) {

List<String> words = new ArrayList<String>();

InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
    fIn = context.getResources().getAssets().open(fileName, context.MODE_WORLD_READABLE);
    isr = new InputStreamReader(fIn);
    input = new BufferedReader(isr);
    String line = "";
    while ((line = input.readLine()) != null) {
        words.add(line);
    }
} catch (Exception e) {
    e.getMessage();
} finally {
    try {
        if (isr != null)
            isr.close();
        if (fIn != null)
            fIn.close();
        if (input != null)
            input.close();
    } catch (Exception e2) {
        e2.getMessage();
    }
}

return words;

}
}

A: In your onClick you read a file from assets and save it to internal memory.
On the next click the same happens.
You should read the file from internal memory too if you want to check if the write succeeded.


text:
Q: Shortening code with a for loop is possible? I have a strategy including 20 poses pyramiding, and i follow the all pose seperately like this.
strategy.entry("BUY1", strategy.long, when= PoseCount==1 and PoseCount[1] !=1 and barstate.isconfirmed, alert_message = message_long_entry)
.....
strategy.entry("BUY20", strategy.long, when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_long_entry)

strategy.entry("SELL1", strategy.short, when= PoseCount==-1 and PoseCount[1] !=-1  and barstate.isconfirmed, alert_message = message_short_entry)
....
strategy.entry("SELL20", strategy.short, when= PoseCount==-20 and PoseCount[1] !=-20  and barstate.isconfirmed, alert_message = message_short_entry)

strategy.close("BUY1", when= PoseCount==-1 and PoseCount[1] !=-1   and barstate.isconfirmed, alert_message = message_long_exit)
.....
strategy.close("BUY20", when= PoseCount==-20 and PoseCount[1] !=-20   and barstate.isconfirmed, alert_message = message_long_exit)

strategy.close("SELL1", when= PoseCount==1 and PoseCount[1] !=1  and barstate.isconfirmed, alert_message = message_short_exit)
....
strategy.close("SELL20", when= PoseCount==20 and PoseCount[1] !=20  and barstate.isconfirmed, alert_message = message_short_exit)

strategy.exit("BUY1 TP/SL",  "BUY1",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
....
strategy.exit("BUY20 TP/SL",  "BUY20",    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

strategy.exit("SELL1 TP/SL",  "SELL1",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)
....
strategy.exit("SELL20 TP/SL",  "SELL20",   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

I want to shorten this structure using for loop. I tried the following but failed. Thanks in advance for your help.
for x = 1 to 20
   strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
   strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
   strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
   strategy.close("SELL"+ tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
   strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)
   strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

edit
still same error (Mismatched input 'to' expecting 'end of line without line continuation') with the following
for x = 1 to 20
     strategy.entry("BUY" + tostring(x), strategy.long, when= PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.entry("SELL" + tostring(x), strategy.short, when= PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)

for x = 1 to 20
     strategy.close("BUY"+ tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("BUY TP/SL"+ tostring(x),  "BUY"+ tostring(x),    limit=long_profit_level,  stop=long_stop_level ,     alert_message = message_long_exit)

for x = 1 to 20
     strategy.exit("SELL TP/SL"+ tostring(x),  "SELL"+ tostring(x),   limit=short_profit_level,  stop=short_stop_level ,   alert_message = message_short_exit)

A: this is the way. I solved :)
for x = 1 to 20
    strategy.entry("BUY"+str.tostring(x), strategy.long, when=   PoseCount==x and PoseCount[1] !=x and barstate.isconfirmed, alert_message = message_long_entry)
    strategy.entry("SELL"+str.tostring(x) , strategy.short, when=   PoseCount==-x and PoseCount[1] !=-x  and barstate.isconfirmed, alert_message = message_short_entry)
    strategy.close("BUY"+str.tostring(x), when= PoseCount==-x and PoseCount[1] !=-x   and barstate.isconfirmed, alert_message = message_long_exit)
    strategy.close("SELL"+str.tostring(x), when= PoseCount==x and PoseCount[1] !=x  and barstate.isconfirmed, alert_message = message_short_exit)
    strategy.exit("BUY TP/SL"+str.tostring(x),  "BUY"+str.tostring(x),     profit = per(tp), loss = per(stoploss) , trail_points=per(trpo) , trail_offset=per(trof), alert_message = message_long_exit)
    strategy.exit("SELL TP/SL"+str.tostring(x),  "SELL"+str.tostring(x),    profit = per(tp), loss = per(stoploss) ,trail_points=per(trpo),trail_offset=per(trof), alert_message = message_short_exit)


text:
Q: #define ABS(x) ((x >= 0) ? x : -x) C# Unity3D Giving error: "Cannot define or undefine preprocessor symbols after first token in file" I don't know if this is a C# question, or specifically Unity3d's implementation:
Where should this normally be placed:
#define ABS(x) ((x >= 0) ? x : -x)

I'm getting "Cannot define or undefine preprocessor symbols after first token in file" wherever I try. e.g
using UnityEngine;
using System.Collections;
#define ABS(x) ((x >= 0) ? x : -x)

public class FillTriangle {
…
}

Should this work in standard MSDN C#?


text:
Q: Best pattern to use with inheritance model I have a model whereby I have an abstract class (lets call it Vehicle) and several inherited classes, such as Bike, Motorbike, Car, Van etc. This is essentially a simplified version of a real world problem.
abstract class Vehicle
    int ID;
    int WheelCount;
    string OwnerName;

class Bike
    DateTime lastSafetyCheck;

class Motorbike
    int EngineCC

class Car
    double EngineSize

class Van
    double StorageCapacity

I have within my system an IEnumerable<Vehicle> which contains each of these. This is contained in a thread safe singleton class, essentially acting as an in-memory database.
I wish to have a method in my application (in either the singleton or a seperate class) which allows me to query for only a certain type of Vehicle.
Initially I considered a method like:
internal IEnumerable<T> GetVehicles<T>() where T : Vehicle

in order that I would be able to supply a type T which would specify the type I wish to retrieve. I know that I can then use typeof() in order to perform logic. But what I cannot figure out is how to return my values? I'm basically struggling with the contents of the method, and I am beginning to think there must be a design pattern out there which would make a lot more sense.
AK

A: LINQ already has this method - OfType:
var vans = Vehicales.OfType<Van>();

As an aside, to determine whether an instance is an instance of a type you do not need to use typeof(), you can use the is and as operators (and they can be used with generic types also):
if (vehicle is Van) ...
if (vehicle is T) ...

Or
var van = vehicle as Van;
if (van != null) ...

var instance = vehicle as T; // Will need T : class generic type constraint
if (instance != null) ...

var instance = vehicle as T?; // Will need T : struct generic type constraint
if (instance != null) ...

A: Why not just use OfType()?
From MSDN:

Filters the elements of an IEnumerable based on a specified type.

Your code could look like this:
internal IEnumerable<T> GetVehicles<T>() where T : Vehicle
{
    return AllVehicles.OfType<T>();
}

A: If you have a collection of Vehicles, and your method returns an IEnumerable instead, you should just be able to run the following
var cars = GetVehicles().OfType<Car>();

That way your method GetVehicles does not need to do any logic, and you can filter by type in the Linq call instead.


text:
Q: Setup mercurial to only work with users already authenticated with my server? I have a Mercurial server setup and would like to use it for source control over Apache. The setup i followed, however, requires that I have a .htpasswd which it uses to authenticate Mercurial users.
Is it possible to have this authenticated list be the people who are already users on the server so they don't have to create new id's and passwords?

A: Certainly.  This is one of mercurial's strengths.  When run as a CGI (or wsgi) it entirely trusts the REMOTE_USER environment variable.  So just have apache set REMOTE_USER before running the ScriptAlias (or wsgi) and mercurial will use that authentication.  Apache has many different authentication modules to interface with any user/pass system you already have.


text:
Q: Does a PropertyChangedEventHandler keep my custom control from being garbage collected? I am fairly new to WPF, and I wondered listening for property changes will keep my custom control from being garbage collected...
Essentially, I listen to events like this:
obj.PropertyChanged += this.The_PropertyChanged;

I am afraid that the control in which I execute the code not be able to be garbage collected while obj still exists, as obj.PropertyChanged holds a reference to this. Is this correct? If so, what is the correct way to avoid this? If I am informed correctly, there is no Dispose() method that could be overridden to be called when the Control is removed from the screen, so there is no obvious location to remove this.The_PropertyChanged from obj.PropertyChanged...

A: Yes, you are correct. obj will have a reference to "this" and therefore "this" will not get garbage collected.   The solution is:
obj.PropertyChanged -= this.The_PropertyChanged;

and you would place that code where "this" is Closed, Disposed, or else wise no longer going to be around.
So for the control, if the Window that hosts the control is closed that could be where you place the code.


text:
Q: How I can to test my private field in my class (TypeScript) with using Jest? I have class which has private filed:
export class RecordingFeesService {
    private readonly url: string;
    private readonly aud: string;

    constructor() {
        this.url = process.env.RECORDING_FEES_URL || "";
        this.aud = process.env.RECORDING_FEES_AUD || "";
    }
}

How I can to test my private fields (url, aud) with using Jest?


text:
Q: regex match anything ends with but not contains a sequence I'm using regex to extract json data in html and and i cannot find how to get text ends with '});' but not include it.
Here is a sample data:
start({"main":{"ss_service":"...();"}});

Thank you for your help.


text:
Q: SSIS - Check if URL is valid In SSIS [VS 2012], is there a way to check to see if a URL is valid before continuing with the loading process? If possible I would like to separate a list of URLs between valid and invalid, and only load the valid URLs. I already have a package created loading a list of URLs, but I'm receiving errors in the history from the invalid URLs and I would like to clean up those errors by filtering out the invalid URLs. Examples would be greatly appreciated! Thanks!

A: I was able to achieve the above by using the script task component along with the following C# piece of code. I passed my URL through a variable and was able to see if it was valid or invalid. I then set up my precedence constraints based on that. Thanks!
    public void Main()

    Dts.Variables["Found"].Value = UrlFound(Dts.Variables["URL1"].Value.ToString());
    Dts.TaskResult = (int)ScriptResults.Success;

    private bool UrlFound(string url)
    {
        try
        {
            //Creating the HttpWebRequest
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //Setting the Request method HEAD, you can also use GET too.
            request.Method = "HEAD";
            //Getting the Web Response.
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //Returns TRUE if the Status code == 200
            response.Close();
            return (response.StatusCode == HttpStatusCode.OK);
        }
        catch
        {
            return false;
        }

    }