text:
Q: SlickR Shiny R dynamically convert dots to images when filtering the carousel obj by user input Have been working through this slickR problem for a while.  I would greatly appreciate any input or fresh perspectives on how to resolve this issue or different ways to approach a solution.
There are two issues I've been working through:
The first I think can be solved using CSS, which I am not super familiar with, slickR seems to be creating multiple divs when the 'obj' is updated through the use of input$series.  This is undesirable since it relocates the most recent div lower on the page.  I tried using javascript, which I am also not very familiar with, to destroy the old slick using an observe event. Bonus points for a simple solution for that issue.
The main issue I am working to resolve is that I would like to convert the dots to images and have them update dynamically as each series is selected.  The goal here is that I would like to have a larger image displayed above and a series of 'thumbnails' displayed below so that the user can have some idea of what each photo looks like without having to scroll through every image in the carousel.
My app is much more complicated than this example, but I am using slickR since it has a convenient way to access the current, active, and center slides, which I am using to filter an additional dataframe to render the display of information regarding each active/centered image in the carousel.
Here is an example which demonstrates both issues:
library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinydashboardPlus)
library(jsonlite)
library(htmltools)
library(htmlwidgets)
library(slickR)

fish <- c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
  "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg" )

butterfly <- c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
)

bird <- c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
)

df <- data.frame(fish=fish, butterfly=butterfly, bird=bird)
pics <- df[,"fish"]

ui <- dashboardPagePlus(
  useShinyjs(),

  header = dashboardHeaderPlus(disable = TRUE ),
  sidebar = dashboardSidebar(

    radioButtons('series', "Choose Series",
                 choices = c("fish"="fish", "butterfly"="butterfly", "bird"="bird")
                 )
    ),

  body = dashboardBody(

    tags$script( sprintf("var dotObj = %s", jsonlite::toJSON( 'dots')) ),

    slickROutput('slickRCarousel'),

    uiOutput('dots')

  )
)

server <- function(input, output, session) {

  # unslick to counteract slick generating multiple divs?
   observeEvent(input$series, ignoreInit = TRUE, {
     runjs("$('.slickRCarousel').slick('unslick');")
    print(df[,input$series])
  })

  # observe({
  #   print(input$slickROutput_current$.clicked)
  # })

  output$dots <- renderPrint({
    c(df[,input$series])
  })

  # carousel setup
    cP2 <- JS("function(slick,index) {
          return '';
          }")

  opts <-
    settings(
      initialSlide = 1,
      slidesToShow = 3,
      slidesToScroll = 1,
      centerMode = TRUE,
      focusOnSelect = TRUE,
      dots = TRUE,
      customPaging = cP2
    )

  output$slickRCarousel <- renderSlickR({

    slick_dots_logo <- slickR(
      obj = df[,input$series],
      height = 100,
      width = "95%"
    ) + opts

  })

}

shinyApp(ui, server)

Thank you in advance for taking the time to look at this!
EDIT 1: Clarification and Current Approach
Here is my current approach, attempting to pass a dynamic value through session$sendCustomMessage and update the variable responsible for rendering the slickR dots (or thumbnails).
The persistent issues are:

*

*the carousel jumps when the radio buttons are changed

*the thumbnails are not updating when the radio buttons are changed

code:
library(shiny)
library(shinyjs)
library(shinydashboard)
library(shinydashboardPlus)
library(jsonlite)
library(htmltools)
library(htmlwidgets)
library(slickR)

fish <- c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
 "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg" )

butterfly <- c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
)

bird <- c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
)

df <- data.frame(fish=fish, butterfly=butterfly, bird=bird)

ui <- dashboardPagePlus(
  useShinyjs(),

  header = dashboardHeaderPlus(disable = TRUE ),
  sidebar = dashboardSidebar(

    radioButtons('series', "Choose Series",
                 choices = c("fish"="fish", "butterfly"="butterfly", "bird"="bird")
    )
  ),

  body = dashboardBody(

    # this sets thumbnails to always be fish, replacing with
    # df[,input$series] seems to cause an issue.
    tags$script( HTML(sprintf("var dotObj = %s", jsonlite::toJSON( df[,'fish'])) ) ),

    #attempting to add a custom message handler to update the dots, but it doesn't
    # update
    tags$script("
                  Shiny.addCustomMessageHandler(setDots, function(newDots) {
                    var dotObj = newDots;
                  });
                "),

    slickROutput('slickRCarousel')

  )
)

server <- function(input, output, session) {

  #custom message handler to update the dots, but it doesn't update
  observe({
    session$sendCustomMessage('setDots', jsonlite::toJSON( df[,input$series]))
    #print(jsonlite::toJSON( df[,input$series]))
  })

  # unslick to counteract slick generating multiple divs
  # and pushing the carousel down? It's not working
   observeEvent(input$series, ignoreInit = TRUE, {
     runjs("$('.slickRCarousel').slick('unslick');")
  })

  # slickR carousel setup
  cP2 <- JS(
    "function(slick,index) {
            return '';
          }" )

  opts <-
    settings(
      initialSlide = 1,
      slidesToShow = 1,
      slidesToScroll = 1,
      centerMode = TRUE,
      focusOnSelect = TRUE,
      dots = TRUE,
      customPaging = cP2
    )

  output$slickRCarousel <- renderSlickR({
  slick_dots_thumb <- slickR(
      obj = df[,input$series],
      height = 100,
      width = "95%"
    ) + opts

  })

}

shinyApp(ui, server)

EDIT 2: Building on @ismirsehregal 's solution to the display and navigation
Last piece of the puzzle is returning the center or active slide value to the server.  The slickR documentation states you can access it like this:
input$mySlick_current$.center
It may be the case that the output$mySlick needs to be created by renderSlickR({}), not renderUI({}).
Here is some updated code from @ismirsehregal 's solution:
library(shiny)
library(htmlwidgets)
library(slickR)

fish <- c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
  "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg"
)

butterfly <- c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
)

bird <- c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
)

df <- data.frame(fish = fish,
                 butterfly = butterfly,
                 bird = bird)

ui <- fluidPage(uiOutput("mySlick"),
                radioButtons(
                  'series',
                  "Choose Series",
                  choices = c(
                    "fish" = "fish",
                    "butterfly" = "butterfly",
                    "bird" = "bird"
                  )
                ),
                uiOutput('imageInfo')
                )

server <- function(input, output, session) {
  output$mySlick <- renderUI({
    cP2 <- JS(
      "function(slick,index) {
          return '';
          }"
    )

    opts_dot_logo <-
      settings(
        initialSlide = 1,
        slidesToShow = 1,
        slidesToScroll = 3,
        centerMode = TRUE,
        focusOnSelect = TRUE,
        dots = TRUE,
        customPaging = cP2
      )

    s2 <- htmltools::tags$script(sprintf("var dotObj = %s", jsonlite::toJSON(df[[input$series]])))

    slick_dots_logo <- slickR(obj = df[[input$series]],
                              height = 100,
                              width = "95%") + opts_dot_logo

    htmltools::tagList(s2, slick_dots_logo)
  })

  observeEvent(input$series, ignoreInit = TRUE, {

  output$imageInfo <- renderPrint({
    paste("The center image is: ", input$mySlick_current$.center)
    })

  #print(input$mySlick_current$.center)
  })

}

shinyApp(ui, server)

Edit 3: Final Solution
Thanks to the link provided in the comment by @ismirsehregal I was able to pass the index of the center slide back to the server.
code:
library(shiny)
library(htmlwidgets)
library(slickR)

fish <- c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
  "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg"
)

butterfly <- c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
)

bird <- c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
)

js <- "
$(document).ready(function(){
  $('#mySlick').on('setPosition', function(event, slick) {
    var index = slick.currentSlide + 1;
    Shiny.setInputValue('imageIndex', index);
  });
})"

df <- data.frame(fish = fish,
                 butterfly = butterfly,
                 bird = bird)

ui <- fluidPage(
  tags$head(
    tags$script(HTML(js))
  ),

  uiOutput("mySlick"),
                radioButtons(
                  'series',
                  "Choose Series",
                  choices = c(
                    "fish" = "fish",
                    "butterfly" = "butterfly",
                    "bird" = "bird"
                  )
                ),
                uiOutput('imageInfo')
                )

server <- function(input, output, session) {
  output$mySlick <- renderUI({
    cP2 <- JS(
      "function(slick,index) {
          return '';
          }"
    )

    opts_dot_logo <-
      settings(
        initialSlide = 1,
        slidesToShow = 1,
        slidesToScroll = 3,
        centerMode = TRUE,
        focusOnSelect = TRUE,
        dots = TRUE,
        customPaging = cP2
      )

    s2 <- htmltools::tags$script(sprintf("var dotObj = %s", jsonlite::toJSON(df[[input$series]])))

    slick_dots_logo <- slickR(obj = df[[input$series]],
                              height = 100,
                              width = "95%") + opts_dot_logo

    htmltools::tagList(s2, slick_dots_logo)
  })

  observeEvent(input$series, ignoreInit = TRUE, {

  output$imageInfo <- renderPrint({
    paste("The center image is: ", df[[input$series]][input[['imageIndex']]])
    })
  print(input[['imageIndex']])
  print( df[[input$series]][input[['imageIndex']]] )
  })

}

shinyApp(ui, server)

A: To display the image in the middle, you could use carousel() function, and list the items in carouselItem() as shown below.
df <- data.frame(fish=fish, butterfly=butterfly, bird=bird)
pics <- df[,"fish"]

jscode <-"
$(document).ready(function(){
            $('#mycarousel').carousel( { interval:  false } );
});"

ui <- dashboardPagePlus(
  useShinyjs(),
  #tags$head(tags$script(HTML(jscode))),  ### to stop the autoplay; does not seem to work
  header = dashboardHeaderPlus(disable = TRUE ),
  sidebar = dashboardSidebar(

    radioButtons('series', "Choose Series",
                 choices = c("fish"="fish", "butterfly"="butterfly", "bird"="bird")
    )
  ),

  body = dashboardBody(

    tags$script( sprintf("var dotObj = %s", jsonlite::toJSON( 'dots')) ),

    slickROutput('slickRCarousel'), br(), br(), br(), br(), br(),

    uiOutput("carousell")
    # uiOutput('dots')

  )
)

server <- function(input, output, session) {

  # unslick to counteract slick generating multiple divs?
  observeEvent(input$series, ignoreInit = TRUE, {
    runjs("$('.slickRCarousel').slick('unslick');")
    print(df[,input$series])
  })

  # observe({
  #   print(input$slickROutput_current$.clicked)
  # })

  output$dots <- renderPrint({
    c(df[,input$series])
  })

  output$carousell <- renderUI({
    carousel(
      id = "mycarousel",
      carouselItem(
        caption = "First image",
        tags$img(src = df[1,input$series])
      ),
      carouselItem(
        caption = "An image file",
        tags$img(src = df[2,input$series])
      ),
      carouselItem(
        caption = "Item 3",
        tags$img(src = df[3,input$series])
      )
    )

  })

  # carousel setup
  cP2 <- JS("function(slick,index) {
          return '';
          }")

  opts <-
    settings(
      initialSlide = 1,
      slidesToShow = 3,
      slidesToScroll = 1,
      centerMode = TRUE,
      focusOnSelect = TRUE,
      dots = TRUE,
      customPaging = cP2
    )

  output$slickRCarousel <- renderSlickR({

    slick_dots_logo <- slickR(
      obj = df[,input$series],
      height = 100,
      width = "75%"
    ) + opts

  })

}

shinyApp(ui, server)

A: Here is what I think you are after (I didn't use shinydashboardPlus as it isn't relevant regarding the given problem)
Edit: After some fixes you can now achive the same using renderSlickR.
You need to install a version including the latest commit:
remotes::install_github("yonicd/slickR@417fd60e013b70540970c1b798897050c3580d2c")

Now also available in a branch:
remotes::install_github("yonicd/slickR@fix_shinyvignette")

Furthermore I found out, that you can avoid the jumping on re-rendering issue via passing the height argument as character (see ?slickR - valid css unit e.g. "100px" or "25vh").
library(shiny)
library(htmlwidgets)
library(slickR)

DF <- data.frame(fish = c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
  "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg"
),
butterfly = c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
),
bird = c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
))

ui <- fluidPage(slickROutput("mySlick", width = "50%"),
                radioButtons(
                  'series',
                  "Choose Series",
                  choices = c(
                    "fish" = "fish",
                    "butterfly" = "butterfly",
                    "bird" = "bird"
                  )
                ),
                textOutput("center"))

server <- function(input, output, session) {
  output$mySlick <- renderSlickR({

    cP2 <- JS(
      paste0("function(slick,index) {
      var dotObj = ", jsonlite::toJSON(DF[[input$series]]),";
          return '';
          }"))

    opts_dot_logo <-
      settings(
        initialSlide = 1,
        slidesToShow = 1,
        slidesToScroll = 3,
        centerMode = TRUE,
        focusOnSelect = TRUE,
        dots = TRUE,
        customPaging = cP2
      )

    slick_dots_logo <- slickR(obj = DF[[input$series]],
                              height = "100px") + opts_dot_logo

    slick_dots_logo
  })

  output$center <- renderText({
    paste("Center:", input$mySlick_current$.center)
  })

}

shinyApp(ui, server)

renderUI solution:
library(shiny)
library(htmlwidgets)
library(slickR)

fish <- c(
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banner.jpg",
  "https://www.hakaimagazine.com/wp-content/uploads/aquarium-reef-fish-banggai-cardinalfish.jpg",
  "https://www.sonomamag.com/wp-content/uploads/2016/12/fish.jpg"
)

butterfly <- c(
  "https://www.futurity.org/wp/wp-content/uploads/2019/02/viceroy-butterfly_1600.jpg",
  "https://harvardforest.fas.harvard.edu/sites/harvardforest.fas.harvard.edu/files/butterfly_giant_swallowtail_model.jpg",
  "https://www.butterflyidentification.com/wp-content/uploads/2019/02/Doris-Longwing-Butterfly-Images.jpg"
)

bird <- c(
  "http://www.cutepetname.com/wp-content/uploads/2018/11/funy-bird-names-feat-img.jpeg",
  "http://3.bp.blogspot.com/-mJ-Kw1mdLOo/UeLJx7vxsaI/AAAAAAAADkg/TfDHtuJnY7I/s1600/The-Cardinal-Bird.jpg",
  "https://images7.alphacoders.com/416/thumb-1920-416332.jpg"
)

df <- data.frame(fish = fish,
                 butterfly = butterfly,
                 bird = bird)

ui <- fluidPage(uiOutput("mySlick"),
                radioButtons(
                  'series',
                  "Choose Series",
                  choices = c(
                    "fish" = "fish",
                    "butterfly" = "butterfly",
                    "bird" = "bird"
                  )
                ))

server <- function(input, output, session) {
  output$mySlick <- renderUI({
    cP2 <- JS(
      "function(slick,index) {
          return '';
          }"
    )

    opts_dot_logo <-
      settings(
        initialSlide = 1,
        slidesToShow = 1,
        slidesToScroll = 3,
        centerMode = TRUE,
        focusOnSelect = TRUE,
        dots = TRUE,
        customPaging = cP2
      )

    s2 <- htmltools::tags$script(sprintf("var dotObj = %s", jsonlite::toJSON(df[[input$series]])))

    slick_dots_logo <- slickR(obj = df[[input$series]],
                              height = 100,
                              width = "95%") + opts_dot_logo

    htmltools::tagList(s2, slick_dots_logo)
  })

}

shinyApp(ui, server)


text:
Q: Handling mutually recursive GUI widgets with reactive-banana I am hunting for a library to write a GUI on top of GLFW and OpenGL. I'm doing this because I am dissatisfied with the common UI library bindings which I feel are too imperative, and I would also like tight control of the look and feel of my UIs. I'd like a declarative approach to defining UI's. I am experimenting with reactive-banana (and temporarily reactive-banana-wx) to see if it meets my needs. I have a problem with defining recursive widgets. Here's my simplest test case:

*

*A text widget that displays a counter.

*A button widget that increments the counter.

*A button widget that is inactive (so it is greyed out and does not respond to input at all) when the counter is 0 and otherwise active and resets the counter to 0.

The first and third widget have a recursive relationship. The first widget is intuitively a stepper of a union of events fed from the two buttons. However, the reset button is an fmap of the counter, and then the event stream relies on the reset button! What is to be done?
Beyond this question I have a concern about event handling: Since I want to handle device input and input focus within my code instead of relying on a framework, I see difficulties ahead in correctly dispatching events in a scalable way. Ideally I would define a data that encapsulates the hierarchical structure of a widget, a way to install event callbacks between the elements, and then write a function that traverses that data structure in order to define device input processing and graphical output. I am not sure how to take an event stream and split it as easily as event streams can be merged.

A: Recursion is allowed, as long as it is mutual recursion between a Behavior and an Event. The nice thing about Behaviors is that sampling them at the time of an update will return the old value.
For instance, your example can be expressed as follows
eClick1, eClick2 :: Event t ()

bCounter :: Behavior t Int
bCounter = accumB 0 $ mconcat [eIncrement, eReset]

eIncrement = (+1)      <$ eClick1
eReset     = (const 0) <$ whenE ((> 0) <$> bCounter) eClick2

See also the question "Can reactive-banana handle cycles in the network?"

As for your second question, you seem to be looking for the function filterE and its cousins filterApply and whenE?

As for your overall goal, I think it is quite ambitious. From what little experience I have gained so far, it seems to me that binding to an existing framework feels quite different from making an "clean-state" framework in FRP. Most likely, there are still some undiscovered (but exciting!) abstractions lurking there. I once started to write an application called BlackBoard that contains a nice abstraction about time-varying drawings.
However, if you care more about the result rather than the adventure, I would recommend a conservative approach: create the GUI toolkit in an imperative style and hook reactive-banana on top of that to get the benefits of FRP.
In case you just wish for any GUI, I am currently focussing on the web browser as a GUI. Here some preliminary experiments with Ji. The main benefit over wxHaskell is that it's a lot easier to get up and running and any  API design efforts will benefit a very wide audience.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does pycharm occupies more and more memory while debugging a TensorFlow program? I followed (sentdex's Youtube video) to create a TensorFlow program and it worked well. I started to tweak some parameters(converting all float32 to float 16 to try to make it faster) in it and got errors. So I tried to debug it with Pycharm. Then I discovered that during debug, even if I was pausing on one line and there was no other process running at the same time, python2.7 keeps occupying more and more memory until it hits 100% and my computer freezes.
Is it that TensorFlow should not be debugged this way? Or is it that something else is wrong?
import tensorflow as tf
import time
import numpy as np

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

n_node_hl1 = 500
n_node_hl2 = 500
n_node_hl3 = 500

n_classes = 10
batch_size = 100

x = tf.placeholder(tf.float16, [None, 784])
y = tf.placeholder(tf.float16)

def neural_network_model(data):
    hidden_1_layer = {'weights': tf.Variable(tf.random_normal([784,, n_node_hl1], dtype=tf.float16)),
                  'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))}
    hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl1, n_node_hl2], dtype=tf.float16)),
                  'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))}
    hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl2, n_node_hl3], dtype=tf.float16)),
                  'bias': tf.Variable(tf.random_normal([n_node_hl1], dtype=tf.float16))}
    output_layer = {'weights': tf.Variable(tf.random_normal([n_node_hl3, n_classes], dtype=tf.float16)),
                'bias': tf.Variable(tf.random_normal([n_classes], dtype=tf.float16))}

    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['bias'])
    l1 = tf.nn.relu(l1)
    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['bias'])
    l2 = tf.nn.relu(l2)
    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['bias'])
    l3 = tf.nn.relu(l3)
    output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['bias'])

    return output

def train_neural_network(x, y):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer(learning_rate=0.005).minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                epoch_x = epoch_x.astype(np.float16)
                epoch_y = epoch_y.astype(np.float16)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss = c
            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss:', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, tf.float16))
        print('Accuracy: ', accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
    file_writer = tf.summary.FileWriter('/home/ramon/PycharmProjects/test/graph', sess.graph)

t = time.time()
train_neural_network(x, y)
print(time.time()-t)

Thanks for the edit and suggestion. I didn't post the code in the first place because I want people to focus on the debugging question and see if they have similar experience instead of focusing on my code because I'm pretty sure there's something wrong with my code(but that should not affect the debugging behavior of Pycharm).


text:
Q: Getting info from .properties file Java I have to write a code which translates numbers into words and it's supposed to be universal for different languages. For this purpose I have a .properties file which looks something like this.
40=forty

50=fifty

80=eighty

teen=teen

tens-suffix=ty

tens-after-delimiter=-

This is my code so far:
 public String numberInWords(Integer number) {

    Properties properties = new Properties();
    FileInputStream is = null;

    try {
        is = new FileInputStream(filePath);

        InputStreamReader reader = new InputStreamReader(
                is, StandardCharsets.ISO_8859_1);

        properties.load(reader);
    } catch (Exception e) {
        // handle exceptions
    } finally {
        close(is);
    }

I know that I can get number values like this:
properties.getProperty(String.valueOf(number));

But how am I supposed to add the value "teen" to the result string?
I tried something along the lines like the last line of code but my IDE says it cannot resolve the symbol.
Thanks
Edit:
This was an example property file. I am well aware that adding "teen" won't work with other languages. In my property files I already have exceptions like 11 - eleven, 12 - twelve and so on. For example in my estonian property file I have a line:
teen=teist,
this will work on all estonian numbers. I need to find a way to add the teen value to a string. If an input is estonian, it will use the estonian property file and so on. This is determined in my other method.
I am trying to find a method that allows me to get the value teen="something" from a property file so I can add this to the string. Every property file is separate and has exceptions in them.
This line won't work, because it cannot resolve symbol teen:
properties.getProperty(String.valueOf(teen));
I am looking for a solution for this exact probleem

A: You need to work with bundle resources. That allows you to read the same property from different property files based on your current locale. Read this article: Backing a ResourceBundle with Properties Files

A: This won't work. I don't think you can create a universal translator like that because all languages treat their numbers differently. While the english language will append teen to numbers between 13 and 19, other languages don't do it like that. Also simply appending teen won't even work for English.
Append teen to three will be threeteen and not thirteen.


text:
Q: Linux Firewall + Loadbalancer distribution Can anyone recommend a Linux specialized distribution (or appliance) which provides both Firewall and Load-balancer?
Something similar to IPCop for example, but containing LB as well?
Thanks in advance.

A: The opensource firewall pfsense can do load balancing (see the link).   They have a VMWare appliance. You can buy commerical support etc.  It's based on FreeBSD though so if you have some absolute requirement for it to run on Linux then it may not be suitable.

A: I don't know of any (but I haven't really looked either) distributions that specializes in these unless you want to start paying some money. (F5 LTM for example). But any decent linux distribution can do both of these things easily. There are lots of free load balancing apps out there that run on Linux:
http://haproxy.1wt.eu/
http://www.ultramonkey.org/
http://www.linuxvirtualserver.org/
http://www.inlab.de/balance.html
And the firewall (iptables) part is just part of any standard Linux distro. There are also lots of apps out there to help simplify configuration of this too.

A: Not an appliance as such, but Shorewall does a good job to balance load over multiple connections. It can route traffic based on source, destination, port etc as well.

A: yo can use ZEN load balancer, distro based on debian, actually you can configure balancing over WEB GUI and firewall over iptable binary.
http://zenloadbalancer.sourceforge.net
you can subscribe to mailing list support
Regards


text:
Q: GAE Go tests - do datastore queries work in test environment? Recently I started writing some tests for sending emails in my Google App Engine Go application. Part of the email sending process is saving the email in the datastore with this function:
func PutInDatastoreFull(c appengine.Context, kind, stringID string, intID int64, parent *datastore.Key, variable interface{}) (*datastore.Key, error) {
    k := datastore.NewKey(c, kind, stringID, intID, parent)
    key, err := datastore.Put(c, k, variable)
    return key, err
}

My tests query the datastore with this function:
func QueryGetAllWithLimit(c appengine.Context, kind string, limit int, dst interface{}) ([]*datastore.Key, error) {
    q := datastore.NewQuery(kind).Limit(limit)
    return q.GetAll(c, dst)
}

When I run it in development environment, it returns last emails without a problem. However, when I run it with goapp test, it returns no error and no data. Is this an expected behaviour for the testing environment, or did I just find some bug?
EDIT:
The test is:
//Testing file
func TestEmails(t *testing.T) {
    c, err := aetest.NewContext(nil)
    if err != nil {
        t.Fatal(err)
    }
    defer c.Close()

    err := NotifyAdminOfLowBalance(c, []string{"WARNING1", "WARNING2"})
    if err != nil {
        t.Fatal(err)
    }
    emails, err := Data.LoadLastEmails(c, 100)
    if err != nil {
        t.Fatal(err)
    }
    if len(emails) == 0 { //test fails here
        t.Fatal("len(emails)==0")
    }
}

//Production code
func NotifyAdminOfLowBalance(c appengine.Context, warnings []string) error {
    not := Notification{}
    not.Warnings = warnings

    buff := new(bytes.Buffer)
    err := LowBalanceTemplate.Execute(buff, not);
    if err != nil {
        c.Errorf("Backend Notifications - NotifyAdminOfLowBalance - error 1 - %v", err)
        return err
    }
    emailBody := buff.String()
    c.Debugf("Backend Notifications - emailBody - %v", emailBody)
    emailSubject := "Low balance!"
    err = Email.SendHTMLEmail(c, emailSubject, DEFINE.AdminEmails, DEFINE.EmailSender, emailBody)
    if err != nil {
        c.Errorf("Backend Notifications - NotifyAdminOfLowBalance - error 2 - %v", err)
        return err
    }
    err = Data.CreateAndSaveEmail(c, emailBody, emailSubject, "ADMIN", "", "", "")
    if err != nil {
        c.Errorf("Backend Notifications - NotifyAdminOfLowBalance - error 3 - %v", err)
        return err
    }
    return nil
}

//Data/Email.go file:
var EmailStr string = "Email"

type Email struct {
    //Class for handling Emails of what is happening in the system
    EmailID           string //ISO date?
    Timestamp         time.Time
    Body              string `datastore:"-"`
    BodyByte          []byte
    Subject           string
    UserEmail         string
    RippleTxID        string
    CoinTxID          string
    Currency          string
}

func (l *Email) LoadStrings() {
    l.Body = mymath.Hex2ASCII(l.BodyByte)
}

func CreateAndSaveEmail(c appengine.Context, body, subject, userEmail, rippleTx, coinTx, currency string) error {
    email := new(Email)
    email.Timestamp = time.Now()
    email.EmailID = email.Timestamp.Format("2006-01-02T15:04:05:")+mymath.Int2Str(email.Timestamp.Nanosecond())
    email.Body = body
    email.BodyByte = mymath.ASCII2Hex(body)
    email.Subject = subject
    email.UserEmail = userEmail
    email.RippleTxID = rippleTx
    email.CoinTxID = coinTx
    email.Currency = currency

    keys, err := Datastore.PutInDatastoreFull(c, EmailStr, email.EmailID, 0, nil, email)
    c.Debugf("keys - %v, err - %v", keys, err)
    if err != nil {
        c.Errorf("Email - CreateAndSaveEmail error 1 - %v", err)
        return err
    }
    return nil
}

func LoadLastEmails(c appengine.Context, count int) ([]Email, error) {
    c.Debugf("LoadLastEmails - %v", count)
    dst := []Email{}
    keys, err := Datastore.QueryGetAllWithLimit(c, EmailStr, count, &dst)
    c.Debugf("keys - %v, err - %v", keys, err)
    if err != nil {
        c.Errorf("Email - LoadLastEmails error 1 - %v", err)
        return nil, err
    }
    c.Debugf("dst - %v", dst)
    return dst, nil
}

And the Datastore functions were already included above

A: I ran into this too and I believe it to be because you are doing a cross group query and the write has not been applied yet. I was able to reproduce this with the dev server too if I made a put then a query right after. I understand this to be how the dev server simulates production-like write visibility when you are not in a transaction or entity group. IOW, I think it's working as it should.
Adding a sleep between your calls (a bad idea) or performing a get() on any of the entities that had previously changed/created in the test will make them show up in the query.
For writes and data visibility rules see: https://developers.google.com/appengine/docs/go/datastore/#Go_Datastore_writes_and_data_visibility


text:
Q: Getting the error 'Timeouts are not supported on this stream' on the server When I saved a file I'm getting an error like this pic also I'm getting this error on the server. I have no problem on my local. Does anyone have an idea?

My save code is below;
public async Task<string> Upload(Stream stream, string filePath)
{
    filePath = PrepareServerPath(filePath);

    await CreateDirectoryIfNotExists(filePath);

    var fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
    stream.CopyTo(fileStream);
    fileStream.Flush();
    fileStream.Close();

    await Task.FromResult(true);
    return filePath;
}


text:
Q: How to use the Parseval's theorem to show this relationship? Problem
My goal is to show the following relationship holds:
$$
\mathcal{S} \triangleq \frac{\int\int_{-\infty}^{\infty}P(x,y)e^{j\phi(x,y)}dxdy}
{\int\int_{-\infty}^{\infty}P(x,y) dx dy}
=\frac{\int\int_{-\infty}^{\infty}\mathcal{H}(f_x, f_y) df_x df_y}
{\int\int_{-\infty}^{\infty}\mathcal{H}_0(f_x, f_y) df_x df_y} \tag{1}\label{eq:goal}
$$
where
$$
\mathcal{H}(f_x, f_y)= \mathcal{F}\{h(u,v)\} \tag{2}\label{eq:H}\\
\mathcal{H}_0(f_x,f_y)= \mathcal{F}\{h_0(u,v)\}
$$
Note that
$$
h(u,v) = \frac{1}{\lambda^2z^2}\left|\mathcal{F}\{P(x,y)e^{j\phi(x,y)}\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2 \\
h_0(u,v) = \frac{1}{\lambda^2z^2}\left|\mathcal{F}\{P(x,y)\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2 \tag{3}\label{eq:h}
$$

My attempt
First, I simply substitute \eqref{eq:h} into \eqref{eq:H} to get
$$
\mathcal{H}(f_x, f_y)= \frac{1}{\lambda^2z^2}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)e^{j\phi(x,y)}\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\}\\
\mathcal{H}_0(f_x, f_y)= \frac{1}{\lambda^2z^2}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\} \tag{4}\label{eq:H_simplify}
$$
I'd like to somehow reshape the RHS of \eqref{eq:goal} into LHS of \eqref{eq:goal}. So, using \eqref{eq:H_simplify}, it follows that
$$
\frac{\int\int_{-\infty}^{\infty}\mathcal{H}(f_x, f_y) df_x df_y}
{\int\int_{-\infty}^{\infty}\mathcal{H}_0(f_x, f_y) df_x df_y}
=\frac{\int\int_{-\infty}^{\infty}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)e^{j\phi(x,y)}\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\}df_x df_y}
{\int\int_{-\infty}^{\infty}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\}df_x df_y}\tag{5}\label{end}
$$
The remaining task is to somehow show the following relationship:
$$
\frac{\int\int_{-\infty}^{\infty}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)e^{j\phi(x,y)}\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\}df_x df_y}
{\int\int_{-\infty}^{\infty}\mathcal{F}\left\{\left|\mathcal{F}\{P(x,y)\}_{f_x=\frac{u}{\lambda z}, f_y=\frac{v}{\lambda z}} \right|^2\right\}df_x df_y}
=\frac{\int\int_{-\infty}^{\infty}P(x,y)e^{j\phi(x,y)}dxdy}
{\int\int_{-\infty}^{\infty}P(x,y) dx dy}\tag{6}\label{wannashow}
$$
but I have no idea how to proceed. I'm sure I need to use the Parseval's theorem in some way but the first thing is to simplify \eqref{end} in some way. Does anyone have an idea?


text:
Q: Redirect to page on button click in react I have a component which was previously working but no longer is for some reason.
This is my container :
import React , {useEffect} from 'react'
import {withRouter} from "react-router-dom"
import LoginView from './LoginView'

export default withRouter(function Login(props) {

    useEffect(() => {
        if(localStorage.getItem('jwt')){
            props.history.push('/dashboard');
        }
    })

    const handleLogin = () => {
        console.log(process.env.REACT_APP_AUTH_URL);
        window.location.href = process.env.REACT_APP_AUTH_URL;
    }

    return (
        <LoginView handleLogin={handleLogin}/>
    )
})

And my view :
import React from 'react';
import logo from '../../../assets/img/logo-red.png'
import '../Auth.css';

export default function LoginView({handleLogin}) {
    return (

Inloggen

Uitsluitend voor medewerkers en klanten van

                <button className="loginBtn loginBtn--google" onClick={handleLogin}>
                   Login met Google
                </button>

    )
}

When i click on my button the handle login function gets triggered. It logs the url from my .env.local file which is: *localhost:8000/api/auth/google*
But this line doesnt seem to fire : window.location.href = process.env.REACT_APP_AUTH_URL;


text:
Q: After successful migration from Magento 1 to Magento 2 with data migration tool, I don't see Cron Scheduler Option in the Admin After successful migration from Magento 1 to Magento 2.3.4, I don't see Cron Scheduler Option in the Admin. Please advise me as to how to bring it in.

A: Cron Scheduler Option not showing any personal tab but cron scheduler showing the follow path : -

*

*On the Admin sidebar, go to Stores > Settings > Configuration.

*In the left panel, expand Advanced and choose System.

*Expand Expansion selector the Cron section.
And more information refer this link :-
https://docs.magento.com/m2/ce/user_guide/system/cron.html


text:
Q: Jenkins and reporting, non-existent? I have been using Jenkins for a while now and coming from a .NET world using Team Foundation Server, one thing I miss the most is reporting through notifications. I know Jenkins is only a subset of TFS's functionality so the comparison is not fair.
However, if there is one thing that is important when leveraging these type of CI and QA tools then it is notifying the team about progress and quality. Jenkins can show some graphs on the dashboard, but I still haven't found a way to send my team emails containing unit test graphs, build stability graphs, pipeline graphs, etc. They simply do not exist, or have I just not found them? Sure, Jenkins can email content like failed tests, but that is too low-level. Teams need to see historical graphs about progress.

A: The format and content of the Email Ext plugin can be set as needed -
just set it to link to any page you like
(can add the link to the existing content of the mail, or replace it all together).
Apart from that, I don't recall support for any statistical graphs, sorry.


text:
Q: IWebBrowser2 control not getting created when tried to do it in seperate thread     void CUIPopupWnd::ieThreadProc(MSG* msg, LPVOID lpParameter){

    CUIPopupWnd *ptrPopUpWndCtrl = (CUIPopupWnd*)GetWindowLongPtr((HWND)msg->wParam , GWLP_USERDATA);
    switch(msg->message)
    {
    case WM_IECREATE:
        {
            REPORT_INTERNAL_SW_ERROR_EXT(L"HTML frame is going to be created.");
            ptrPopUpWndCtrl->m_htmlAttributes.pBrowser = new (nothrow)CUIHTMLFrameWnd((HWND)msg->wParam,ptrPopUpWndCtrl->m_ulPresentWidth,ptrPopUpWndCtrl->m_ulPresentHeight);

            if( NULL == ptrPopUpWndCtrl->m_htmlAttributes.pBrowser )
            {
                REPORT_INTERNAL_SW_ERROR_EXT(L"EmbeddedBrowser failed");
            }
            else
            {
                //m_htmlAttributes.pBrowser->createControl(this->m_hWnd,this->m_ulPresentWidth,this->m_ulPresentHeight);
                ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->m_currentURL = ptrPopUpWndCtrl->m_htmlAttributes.m_szHTMLPath;
                ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->RepaintBrowser();
                ptrPopUpWndCtrl->m_htmlWindowsList.push_front(ptrPopUpWndCtrl);
                ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->Navigate(ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->m_currentURL);
            }
        }
        break;
    case WM_IEREFRESH:
        {
            ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->Navigate(ptrPopUpWndCtrl->m_htmlAttributes.pBrowser->m_currentURL);
            ptrPopUpWndCtrl->m_htmlAttributes.m_fReloadRequired = false;

        }
        break;
    default:
        return;
    }

    CThreadController::getThreadController().createUIThread( ieThreadProc, IEThread,NULL );
            CThreadController::getThreadController().postThreadMessage(IEThread,WM_IECREATE,(_wparam)this->m_hWnd,0);

CThreadController::getThreadController().postThreadMessage(IEThread,WM_IEREFRESH,(_wparam)this->m_hWnd,0);

Here, ieThreadProc is a static thread proc.I have Win32 window (this->m_hWnd) which is suppose to be the parent of this IWebBrowser2 com control.Because of Cross thread problem, I post the message to the thread where the IE control is created and work with it. While debugging it doesn't show any breakage. But, the IE control simply displays blank and no page is displayed. Kindly help me with the solution.

A: The browser operates asynchronously via window messages.  Make sure that the message loop of the thread that owns the browser window is processing messages that are destined for the browser's window, such as by passing them to TranslateMessage() and DispatchMessage() after retreiving them from the thread's message queue (if it is not already doing so - it is hard to say since you do not show what createUIThread() does outside of ieThreadPorc()).


text:
Q: cloud.google.com/go/pubsub iterator.go:44: undefined: acker and puller I'm hitting the following error messages when I build codes that employ cloud.google.com/go/pubsub.
Am I working on a wrong package? Or it's just because of alpha?
$ go test
# cloud.google.com/go/pubsub
./iterator.go:44: undefined: acker
./iterator.go:46: undefined: puller
FAIL    cloud.google.com/go/pubsub [build failed]


text:
Q: NSKeyedArchiver.archiveRootObject fails to save I have a group of custom objects that I'm converting to NSMutableDictionary's, and then creating an array out of them (this part is currently working as expected).
I'm then attempting to save that array of data as a file using NSKeyedArchiver. However, the result of NSKeyedArchiver.archiveRootObject always returns false.
Below is my logic for saving - am I missing something obvious, or perhaps is this the wrong approach? Thank you!
    var groupsArray = [Any?]()

    for group in file!.groups{
        for obj in group.children {
            let objDict = obj.convertToDictionary()

            groupsArray.append(objDict)
        }
    }

    let documents: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let filePath: String = URL(fileURLWithPath: documents).appendingPathComponent("file.archive").absoluteString

    let save: Bool = NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath)

EDIT: This also fails if trying to save to the .desktop or the .caches directories.

A: The issue here is .absoultestring. If the URL object contains a file URL, then we should use .path for working with FileManager or PathUtilities etc. So here replacing .absoultestring with .path will solve the issue
for more details about their difference please refer this answer

A: try this method to save
1.Method returns filepath.
func filePath(key:String) -> String {
    let manager = FileManager.default
    let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
    return (url!.appendingPathComponent(key).path)
}

2.Code to save to a file using NSKeyedArchiver.
NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath(key: "file.archive"))


text:
Q: Eigenvalues/Eigenvectors of scaled matrix I have the following scaled matrix
$A = \frac{2}{3\sqrt{10}}
\begin{pmatrix}
5 & 0 \\
3 & 4
\end{pmatrix}$
Now I have to calculate the eigenvectors and values of $B = A^TA$
I'd like to make my life easier and get a better understanding of the influence of scaling on eigenvectors and values.
I defined $A' =
\begin{pmatrix}
5 & 0 \\
3 & 4
\end{pmatrix}, B' = A'^TA'$ and $z = (\frac{2}{3\sqrt{10}})^2 = \frac{4}{90}$
and figured that I can do: $B = zB' = z(A'^TA')$
Now my questions is if I can calculate the eigenvectors and values of $B'$ and then later scale it by $z$ or do I have to do $B = zB'$ and then calucate the eigenvectors and values of $B$

A: Go back to the fundamental definition of an eigenvector: it's a vector $\mathbf v$ such that $M\mathbf v=\lambda\mathbf v$ for some scalar $\lambda$. If $\mathbf v$ is an eigenvector of $M$, then $$(cM)\mathbf v = c(M\mathbf v)=c(\lambda\mathbf v)=(c\lambda)\mathbf v,$$ that is, $\mathbf v$ is also an eigenvector of the "scaled matrix" $cM$ with eigenvalue $c\lambda$.


text:
Q: How can I pass a data from UIViewController to a UITableViewController that is embedded in a container placed on that UIViewController? I have an ios app written in swift and there I have a UIViewController with a container on half of the screen. This container has embedded UITableViewController and I want to display there some data that I'm fetching from my webservice. The problem is that to fetch the data from web service I need an unique id number that I store in the UIViewController. So how can I pass that data from one controller to another?

A: I have a project on github (written in Objective-C) that does exactly what you want. It has the horribly unoriginal name "test".
It has a master view controller with 2 child view controllers, each of which is a subclass of UITableViewController set up to manage static table views. (That detail doesn't really matter. It's the method of setting up connections between parent and child view controllers that addresses your question.)
The idea is that you set up your child view controller in a container view and link it in with an embed segue.
When you use an embed segue then prepareForSegue fires when the views are loaded. In your prepareForSegue you save a reference to your child view controller(s) if you need to call it/them, and make yourself each child's delegate if you need it to call you.
The code would be different in Swift but the concept is identical.


text:
Q: Click bubbling all messed on radio buttons http://jsfiddle.net/7kb7n/
    function StorewideSaleModel() {

    this.radioOff = ko.observable(""+1);

}

ko.applyBindings(new StorewideSaleModel());

So, what I am trying to do here is enable/disable the text box depending on the radio button. I also assigned a click event to the div so if I click anywhere else in that div, the button gets checked. That all works fine.
BUT, if I click the radio button itself, it doesn't get checked, BUT the rest of the UI still updates. If you check the value, then the radio button goes back (magically) to the old value. How does it even remember the old value I have no idea.
So I tried clickBubble: false, and the event STILL bubbled to the enclosing div. I used alerts to figure that out.

A: By default, Knockout prevents the click event from taking any default action.
So you need to return true from your click event handler to allow the default click action:
data-bind="click: function() { radioOff('2'); return true;}"

and
data-bind="click: function() {radioOff('1'); return true;} "

Demo JSFiddle.


text:
Q: Multiple EC2 instances connecting to single SQS We are using cloudformation template to create multiple EC2 instances. We have Auto scaling and ELB defined. Each EC2 instance runs with its own Tomcat server and a web application. We connect to SQS to pull messages and write to RDS database from this web app.
Problem statement - We do not want both EC2 instances pulling the same message from SQS and writing to RDS. Could you please direct me on how to make this process efficient?

A: Your question is reasonable, check out an explanation below.
Immediately after the component receives the message, the message is still in the queue. In order to prevent a situation you described, Amazon SQS blocks them with a visibility timeout, which is a period of time during which Amazon SQS prevents other consuming components from receiving and processing that message. Once your instance processed a message it should invoke a command that deletes a message from the queue. If for some reason, instance didn't finish a job during visibility timeout, the message becomes available for other instances again.
You can find more information here:
http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html


text:
Q: Why does changing mapping properties in domain doesn't generate new changelog lines? class Donation {

    BigDecimal amount

    static constraints = {
        amount min: BigDecimal.ZERO
    }

    static mapping = {
    }

}

After the addition, the domain looked like below:
class Donation {

    BigDecimal amount

    static constraints = {
        amount min: BigDecimal.ZERO
    }

    static mapping = {
        amount scale: 4
    }

}

After making the change, i ran dbm-gorm-diff in the grails console but it printed no additional changelog lines. I was wondering if making mapping change will not produce new changelog lines. But looking at the data type of "amount" in mysql database, it showed decimal(19,2). I thought making scale 4 will change the datatype to decimal(19, 4). I appreciate any help in this dilemma. Thanks!

A: While db-migration can detect changes in your domains and can generate the desired changelog to update your database schema. It is not smart enough to locate correct changes all the time. Specifically while you are renaming a table/column or changing the datatype of a column. In these kind of scenarios you need to make manula migrations.
Make a manual changelog to update schema using db-migration:
databaseChangeLog = {

    changeSet(author: "sandeep (manual)", id: "20150901124635-01") {
        modifyDataType(columnName: "amount", newDataType: "decimal(19,4)", tableName: "donation")
    }
}

So always, after generating the changelog, verify whether it contains the correct changes or not.


text:
Q: Sublime Text 2 doesn't save built SASS file I installed SASS build system for Sublime Text 2 just as described in the readme and everything succeeded (also SASS installation). Now, if I try to build my .scss file ST2 prints out something like "[Finished in 0.2s]" without showing me any result or save a .css file. I also can write some wrong code and it will not complain about it, just give me a "finished" message again. Any idea what's causing this behaviour?

A: I had the same problem on my Mountain Lion.
I fixed it by changing the "cmd" line in the SASS.sublime-build (and all the others build files I have for SASS) from
["sass", "--update", "$file:${file_path}/${file_base_name}.css"]

to
["sass --update $file:${file_path}/${file_base_name}.css"]

Don't know why, but practically if you write the command in an array with more than one item, it won't work, while the command all in one string does work.

A: gem install sass
in ST2 /tools/build system/new build system...
{
  "cmd": ["cmd", "/c", "sass --style compressed", "$file", "$file_base_name.css.min"]
}

or
{
  "cmd": ["cmd", "/c", "sass", "$file", "$file_base_name.css"]
}

save as "sass.sublime-build"


text:
Q: Weird characters in perf output... I'm trying to debug a webkit build with Linux perf that I compiled with symbols.
The output of "perf report -g" has the symbols with half human readable and the other half alphanumeric values.
For example:
_ZN7WebCore12RenderObject18setAnimatableStyleEN3WTF10PassRefPtrINS_11RenderStyleEEE
    |
    |--91.30%-- _ZN7WebCore4Node14setRenderStyleEN3WTF10PassRefPtrINS_11RenderStyleEEE
    |          _ZN7WebCore7Element11recalcStyleENS_4Node11StyleChangeE
    |          _ZN7WebCore7Element11recalcStyleENS_4Node11StyleChangeE
    |          _ZN7WebCore7Element11recalcStyleENS_4Node11StyleChangeE

What's happening here?
What's _ZN7?
My hunch is that this is something to do with C++ and maybe I need to compile with more options to get the symbols to be represented in perf correctly.
ANY pointers here would be appreciated. I can't find anything about this anywhere in the documentation.

A: These are so-called "mangled names":  The C++ compiler encodes type information into symbol names, so that the linker can correctly implement overloading, class scoping and namespaces without having to actually understand the C++ type system, and without having to support characters outside of basic alphanumerics and underscores.
You can turn these back into human-readable names with tools such as c++filt under Linux.
For example:
$ echo _ZN7WebCore12RenderObject18setAnimatableStyleEN3WTF10PassRefPtrINS_11RenderStyleEEE | c++filt
WebCore::RenderObject::setAnimatableStyle(WTF::PassRefPtr<WebCore::RenderStyle>)

Or in your case, perf report -g | c++filt will probably do what you want.


text:
Q: Best way to update array with new values by Id Performance is very key and I was hoping there would be a better way to update an array via an Id. I'm looking for a better version of the update function (shown below) that doesn't need to iterate through the 2nd array so many times.
I've added example snippet below to show what I'm trying to do. Keep in mind that these arrays can potentially contain potentially hundreds of objects and need to be updated several times a second.

var array1 = [{
 id:"asd4567wds8",
  x: 109,
  y: 763,
  /* These values also have other properties that I need to keep */
}, {
 id:"df567wgfdz4",
  x: 450,
  y: 132,
  /* These values also have other properties that I need to keep */
}, {
 id: "cvbz5476zzg",
  x: 903,
  y: 865,
  /* These values also have other properties that I need to keep */
}]

var array2 = [{
 id:"df567wgfdz4",
  x: 450,
  y: 137
},{
 id:"asd4567wds8",
  x: 114,
  y: 763
}, {
 id: "cvbz5476zzg",
  x: 908,
  y: 870
}]

$("document").ready(function(){
 display();
  $("#update").click(function(){
   update();
    display();
  })
})

/*************************************
* Is there a better way to do this? *
*************************************/

function update(){
 array1.forEach(function(element){
   var temp = array2.find(function(element2){
     return element.id === element2.id
    })

    element.x = temp.x
    element.y = temp.y
  })
}

function display(){
 $("#Array1").empty();
  $("#Array2").empty();
 array1.forEach(function(element){
   var p = $("").text(`[${element.x}, ${element.y}]`)
    $("#Array1").append(p)
  })
  array2.forEach(function(element){
   var p = $("").text(`[${element.x}, ${element.y}]`)
    $("#Array2").append(p)
  })
  if(test(array1, array2)){
    $("#test").text("Success!")
  } else {
    $("#test").text("Values do not match")
  }
}

/* Test function do not change */
function test(array1, array2){
  var clear = true;
  array1.forEach(function(element){
    var temp = array2.find(function(element2){
      return element.id === element2.id
    });

    clear = (element.x === temp.x && element.y === temp.y)?clear:false
  });

  return clear;
}

Array 1:

Array 2:

<button id="update">
Update
</button>

Context: I'm creating a game utilizing sockets and I want to update the client with the new locations of the other objects of the game in one huge chunk.

A: You could also run the map function on one or both of the arrays so that you can get the structure that @Doug mentioned.
object2 = { "df567wgfdz4" : { x: 450, y: 137 }, "asd4567wds8" : { x: 114, y: 763 }, "cvbz5476zzg": { x: 908, y: 870 }

The map function to get the above would look something like this:
array2.map(newObj => {
    var rObj = {};
    var sObj = {};
    sObj['x'] = newObj.x;
    sObj['y'] = newObj.y;
    rObj[newObj.id] = sObj;
    return rObj;
});


text:
Q: Applescript loop through result of "ls" with "do shell script" I have selected a list of files in Applescript using:
set variableName to do shell script "cd /; cd dev/; ls tty.usb*"

When I print out variableName, it shows this list:
file1
file2
From here, I want to loop through each of them using:
repeat with theItem in variableName
   display dialog theItem
end repeat

Instead of showing "file1" and "file2" one by one, it shows "f, i, l, e, 1," and so forth.
How can I loop the list to get a complete file name?

A: Thanks for the helpful responses! I have found out the solution.
set variableName to do shell script "find /dev/tty.usb*"
display dialog variableName

set testArray to paragraphs of the variableName

repeat with theItem in testArray
   display dialog theItem
end repeat

By using paragraphs, I'm able to split by newline and covert the result into a list.


text:
Q: Is the inverse of a continuous bijective function also continuous? Is the inverse of a continuous bijective function also continuous?
How to prove it?

A: Take the function $f(x)=x^2$ for $x\in(-1,0]\cup[1,2]$. Then $f:(-1,0]\cup[1,2]\to[0,4]$ is continuous and bijective, but the inverse is not continuous. We can see the inverse is not continuous since $[0,4]$ is connected but $(-1,0]\cup[1,2]$ is not connected.

A: Take any set $S$. Let $X$ be $S$ with the discrete topology and $Y$ be $S$ with the coarse topology. Note that the identity $i:X\to Y$ is continuous, but its inverse, the identity $i:Y\to X$, is not.

A: Define $f: [0,1) \cup [2,3] \rightarrow [0,2]$ by
$$f(x)=\begin{cases} x & x \in [0,1) \\ x-1 & x \in [2,3] \end{cases}$$
This is a counter-example from TonyK.


text:
Q: Writing a python script to fetch content of a datastore entity in GCP I am trying to fetch a column of a datastore entity in Google Cloud Platform. I can do it by writing a GQL query from the console, but I want to do the same using a python script and use the same GQL query and run it through the cloudshell of GCP.
Here is a table similar to the one used in datastore :

I have to find out the names whose Salary is more than 280000.
I wrote a GQL query in the console :
SELECT Name from Person where Salary>280000 ;

I got the result, but I want to do the same using Python script which could run in the cloudshell.

A: Its pretty simple.
from google.cloud import datastore
client = datastore.Client()
query = client.query(kind='Kindname')
query = query.add_filter('Salary', '>', 280000)
l = query.fetch()
l = list(l)
if not l:
    print("No result is returned")
else:
    d = dict(l[0])
    print(d['name'])

A: What you are looking for is the Python client library for Cloud Datastore.
You can use it to query data from a Python script, in your example it would be something similar to this:
from google.cloud import datastore
client = datastore.Client()
query = client.query(kind='Person')
query = query.add_filter('Salary', '>', 280000)

To learn more, I recommend you to take a look at the documentation for queries and on how to set up authentication.


text:
Q: Find the points lying between Start and End Angle of an ARC. I am trying to find the points which lie within the Sector A of the ARC. I am using D3 to draw the arc on the svg and in a circle where points are plotted. When I move the arc with their start angle or End Angle, the points confined to the ARC changes some property says color or opacity.

What I am doing is, I am calculating the angle (P_A) of the all the points (X, Y) from the center(CX,CY) and trying to check that points lies between the angle of the ARC hands i.e startAngle S_A and end Angle E_A. This is the formula I am using
P_A = atan(Y-CY,X-CX)*180.0/PI;

then I am doing the check:
if (P_A < E_A && P_A > S_A)
{
/// SAY Color of Points are changing.
}

Code I have used to genrate the ARC in D3 is given below
    var startAng = 20;
    var arcWidth = 1.5;

    var vis = Space.append("svg")
    var pi = Math.PI;

    var arc = d3.svg.arc()
      .innerRadius(0)
      .outerRadius(radiusC)
      .startAngle(S_A* (pi/180)) //converting from degs to radians
      .endAngle(E_A) //just radians

    vis.attr("width", "400").attr("height", "400") // Added height and width so arc is visible
      .append("path")
      .attr("d", arc)
      .attr("fill", "white")
      .style("stroke","black")
      .style("opacity",0.2)
      .attr("transform", "translate(200,200)");

But it is not working properly.. Nothing is happening as such.

A: For angle approach you should use atan2 function and account for cyclic behaviour (when sector includes 180 or 360 border)
Coordinate approach:
make vectors
s = (Cos(startangle), Sin(startangle))
e = (Cos(endangle), Sin(endangle))

for every point make vector
 d = (p.x - center.x, p.y - center.y)

and check that both d lies CCW (counterclockwise) relative to s and d lies CW (clockwise) relative to e using cross product
 if (s.x * d.y - s.y * d.x >= 0)  && (e.x * d.y - e.y * d.x <= 0)
     then point lies inside sector


text:
Q: Excel Add-In Office-JS is asking about Certificate Revocation List I'm trying to get my Add-In distributed via Office 365 Admin Center. It's been a real pain as they force SSL upon me even though the Add-In works fine via HTTP currently.
The reason I use HTTP is that my Add-In prompts each start that there is no "CRL List" for the SSL Cert of internal API.

I found how to disable this check, but it appears to be system wide.
Is there a reason that it works fine in the browser, but prompts in Excel Add-In?
Is there a way to disable just for Excel vs system wide?
This will likely be a separate post, but is there a way to disable for just one certificate vs system wide?
Disabling system wide may work, but it's clearly not the correct approach. I'm aware the best approach would be to resolve/setup the CRL, but that is a tall ask just for "my add-in". If I could at least pitch disabling check on a lower/smaller level, it might be accepted.
I haven't tested running in Web just yet to see if I get the SSL prompt in the browser, this is currently on Desktop which is my main target audience.
Update: I've reaserched more and noticed that the internal API uses LDAP for the CRL List. This appears to be working via the browser, but the Excel Add-In isn't passing my Credentials is my guess. I'm not sure how to configure this step at all.
Update: This issue is inconsistent which makes it even harder to diagnose. One possible fix was simply runnung "certutil" to query the list seemed to fix, but as the issue is inconsistent, its hard to say without further testing. I have setup on other terminals and not had the prompt. Then I rebooted after Windows Update and had the prompt, then ran CertUtil and then prompt went away. Other users just never have gotten the prompt.


text:
Q: Troubleshooting "The type parameter T is hiding the type T" warning I am getting a warning in eclipse (the most recent version) for the following code.
public interface A<T> extends B<T> {
     public T getObject();
}

The warning appears at 'T' in 'A' and reads:  "The type parameter T is hiding the type T".
The weird part is that the following code generates no errors or warnings.
public interface A extends B<T> {
     public T getObject();
}

But now I can't extend A while telling it what type T is.
I am completely confused. Anyone know why this is happening?

A: Just to expand last answer (I know question is old and closed), I'll provide a Simplest case where you can understand the error:
Imagine an interface with a generic method such as:
<T> Output<T> doSomething(Input<T> input);

If you try to override it as:
@Override
public <Object> Output<Object> soSomething(Input<Object> input){
    /*..*/
}

The compiler warns you:

The type parameter Object is hiding the type Object

What it means is that "Object" is a generic label here, it is not java.lang.Object. If you changed Object type to V or whatever arbitrary letter, that would not happen. But you are using and appelative which collides with an actual defined class, so compiler warns you that this Object of you is hiding what otherwise would be understood as the common Object class.

A: Do you somewhere have a class or interface named T, or are you using T as a concrete type name somewhere instead of as a type parameter (which means you might have forgotten somewhere else, for example in an enclosing class, to specify that T is a type parameter)? I can reproduce your problem with this:
class T {  // A concrete type T
}

interface B<T> {  // warning: The type parameter T is hiding the type T
}

interface A<T> extends B<T> {  // warning: The type parameter T is hiding the type T
    T getObject();
}

If I remove class T, it disappears.

A: Even though this question is already answered , since the subject line is about  ("The type parameter T is hiding the type T") , just want to add that this warning does not always mean that there is a class or actual type "T" declared somewhere in the classpath (or inner class) as all the answers/comments suggest.
Consider the following:
public class Cache<K extends Comparable<K>,V> {

  private final  ConcurrentHashMap<K,V> _concurrentMap =  new ConcurrentHashMap<K,V>();

  public <K,V> void add(K key ,V  value){ // Compiler warning - The type parameter V is hiding type V (as also for K)

    _concurrentMap.put(key, value); //Compiler error - K and V passed to add are now being considered different
                                    //from whats declared for _concurrentMap variable
  }

  public V get(K key){
    return _concurrentMap.get(key);
  }

  public int size(){
    return _concurrentMap.size();
  }
}

Because K ,V is declared at class level , the method add also "inherits" it. So you end up getting the same warning.
Below removes the warning and compiler error of course
public <E,F> void add(K key ,V  value){
    _concurrentMap.put(key, value);
}

And my original method is this. (Don't require additional generic types for my method)
public void add(K key ,V  value){
    _concurrentMap.put(key, value);
}

A: I try:
public interface B<T> {
    T getObject();

    public  interface A<T> extends B<T>{
        T getObject();
    }
}

on eclipse Indigo Service Release 2 and there is no warning or error

A: Just Removing the generic <T> in front of return type removed the warning.
This is the earlier code :
private <T> LocalDate convertToDate(Root<T> root, String name, String value) {
    ..........
    ..........
    return LocalDate.parse(value, dtf);
}

Warning disappeared with below
private LocalDate convertToDate(Root<T> root, String name, String value) {
    ..........
    ..........
    return LocalDate.parse(value, dtf);
}


text:
Q: Problems after successful reformat and installation I gave up on recovering my hard drive from a crash that corrupted my entire drive.
I went ahead and bought a new copy of Windows 8.
Affter I bought it, I preinstalled Window WinXP to ensure that it will go smoothly.
Installation went smoothly, and when it was done it told me to activate.
I got a valid key from my trusted hardware store, and I checked if it's the official Win8 by comparing the MD5 hashes with the ones on the Microsoft website.
What did I do wrong?

A: This is how Windows normally works. You're alright.
A product key is a 25-character code that's used to activate Windows. Activation helps verify that Windows hasn't been used on more PCs than the Microsoft Software License Terms allow.
http://windows.microsoft.com/en-au/windows-8/what-is-product-key


text:
Q: WWVB simple receiver help I am trying to experiment with WWVB receiver design...
The antenna I am using is from another WWVB receiver module.  It is a loop antenna with a capacitor that I assume is tuned to 60kHz.
Questions-

*

*When I a probe the antenna with the Oscilloscope I don't see the ON/OFF 60k signal I expect. It looks more like a bunch of noise.

*When I connect the antenna to an emitter follower it changes the signal. Could the decoupling capacitor be effecting the antenna's tuned frequency?

A: The 60 kHz signal from WWVB is very weak over most areas of the country, so it isn't surprising that putting an oscilloscope across the antenna doesn't show anything. We're talking about a microvolt-level signal here, and your scope can probably only show signals down to tens of millivolts or so, about 3-4 orders of magnitude too large. You need a lot of selectivity and a lot of gain to pull a usable signal out of the noise and interference.
An emitter follower would not be my first choice as the first gain stage connected to a high-impedance antenna. You need to carefully match source and load impedances here, and take into account the detuning effect that the connection will have. Either the first gain stage needs to have a very high input impedance, or you need to create a lower-impedance tap (or auxiliary winding) on the antenna coil to drive the amplifier.


text:
Q: Syntax error when trying to create a stored procedure in MySQL I'm trying to create a stored procedure in MySQL to check if a given POINT is inside a POLYGON but I get the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 7
This is my query:
CREATE PROCEDURE IsInsidePolygon(
    IN polygon_coordinates VARCHAR(200),
    IN point_coordinates VARCHAR(200)
)
BEGIN
    DECLARE
        polygonData GEOMETRYCOLLECTION;
    DECLARE
        pointData POINT;
    SET
        polygonData = ST_GEOMFROMTEXT(
            CONCAT('POLYGON((', polygon_coordinates, '))')
        );
    SET
        pointData = ST_GEOFROMTEXT(
            CONCAT('POINT(', point_coordinates, ')')
        );
    SELECT
        post_id
    FROM
        wp_postmeta
    WHERE
        ST_CONTAINS(polygonData, pointData);
END;

I'm a beginner in SQL so I can't tell what I'm doing wrong here.
Thanks in advance!

A: You had an undeclared variable coordinates that is subbed with polygon_coordinates and a missing semicolon after the query at the end:
CREATE PROCEDURE IsInsidePolygon(
    IN polygon_coordinates VARCHAR(200),
    IN point_coordinates VARCHAR(200)
)
BEGIN
    DECLARE
        polygonData GEOMETRYCOLLECTION;
    DECLARE
        pointData POINT;
    SET
        polygonData = ST_GEOMFROMTEXT(
            CONCAT('POLYGON((', polygon_coordinates, '))')
        );
    SET
        pointData = ST_GEOFROMTEXT(
            CONCAT('POINT(', point_coordinates, ')')
        );
    SELECT
        post_id
    FROM
        wp_postmeta
    WHERE
        ST_CONTAINS(polygonData, pointData);
END

A: The problem was a typo in the naming of one of the variable and a missing 'DELIMITER $$' at the beginning.
DELIMITER $$

CREATE PROCEDURE IsInsidePolygon(
    IN polygon_coordinates VARCHAR(200),
    IN point_coordinates VARCHAR(200)
)
BEGIN
    DECLARE
        polygonData GEOMETRYCOLLECTION;
    DECLARE
        pointData POINT;
    SET
        polygonData = ST_GEOMFROMTEXT(
            CONCAT('POLYGON((', polygon_coordinates, '))')
        );
    SET
        pointData = ST_GEOFROMTEXT(
            CONCAT('POINT(', point_coordinates, ')')
        );
    SELECT
        post_id
    FROM
        wp_postmeta
    WHERE
        ST_CONTAINS(polygonData, pointData);
END

Thanks everyone for the help!
Ps. This query was run in "phpmyadmin".


text:
Q: snakemake: Run some tasks on cluster and some locally I'm using snakemake to orchestrate an analysis pipeline. Some tasks are very small (e.g. create some symlinks) while others take hours. Is there a way to use --cluster for some of them but execute others just locally?

A: localrules does just this. When the example below is run with --cluster, bar jobs are run in cluster and foo jobs are run locally.
localrules: foo

rule foo:
    ...

rule bar:
    ...


text:
Q: Scala + Spark - How to cast from 'scala.collection.mutable.WrappedArray$ofRef' to our custom object? We are using spark along with Scala in our project.
We are using custom encoders to create spark datasets.
Our dataset schema is of type as below:
(String, util.ArrayList[MyObject])

When  we do df.printSchema, we get following:
root
 |-- key: string (nullable = true)
 |-- listOfMyObject: array (nullable = true)
 |    |-- element: binary (containsNull = true)

MyObject is scala case class as below:
case class MyObject(key: String, dataList: java.util.ArrayList[MyObject2])

When we apply map function on this dataframe,
df.map((row) => {
val key  = row.get(0)
val values = row.get(1)
})

At runtime, row contains following schema:
StructField(key,StringType,true)
StructField(myObject,ArrayType(BinaryType,true),true)

We are able to retrieve the String value, but when trying to retrieve the util.ArrayList[MyObject], we are getting scala.collection.mutable.WrappedArray$ofRef.
We got this by using ref.getClass method.
Any pointers to solve this issue?
Thanks
Anuj

A: Try to use Scala objects that spark can manage with the encoders, in your case you can change the java.util.ArrayList to a simple List of scala, and then if the order of the columns and the type is correct, transform your dataframe to a dataset of the type of your class only with this simple line:
case class MyObject(key: String, dataList: List[MyObject2])
val ds: Dataset[MyObject] = df.as[MyObject]

Keep in mind that if the schema you have an Array, yo can only transform it to List, no to arrays.

A: I would change java.util.ArrayList by scala.collection.immutable.List
package playground

import org.apache.spark.sql.SparkSession
// import java.util.ArrayList

object Casting {

  val spark = SparkSession.builder()
    .appName("Casting")
    .config("spark.master", "local[*]")
    .getOrCreate()

  case class MyObject2(fname: String, age: Int)

  // case class MyObject(key: String, dataList: ArrayList[MyObject2])
  case class MyObject(key: String, dataList: List[MyObject2])

  // val arrLst = new util.ArrayList[MyObject2]()
  // arrLst.add(MyObject2("Marie", 25))
  // arrLst.add(MyObject2("Peter", 27))

  val lst = List(MyObject2("Marie", 25),MyObject2("Peter", 27))

  // val data: Seq[MyObject] = Seq(MyObject("key",arrLst))
  val data: Seq[MyObject] = Seq(MyObject("key",lst))

  def main(args: Array[String]): Unit = {

    import spark.implicits._

    try {
      val df = spark.createDataFrame(data)

      df.printSchema()
      df.map(row => {
        val key  = row.key
        val values = row.dataList
        (key, values)
      }).show(false)

      df.show()
    } finally {
      spark.stop()
      println("Spark Session has stopped.")
    }
  }
}

root
 |-- key: string (nullable = true)
 |-- dataList: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- fname: string (nullable = true)
 |    |    |-- age: integer (nullable = false)

+-----+--------------------------+
|_1   |_2                        |
+-----+--------------------------+
|Lucia|[[Marie, 25], [Peter, 27]]|
+-----+--------------------------+

ArrayList it's not a member of Scala collection.
I would try to work with Scala objects that Spark can manage with its encoders.


text:
Q: How to calculate the variance using least square method if the regression line is vertical to x-axis I have some data in a 2D plane. I want to calculate their variance but the regression line could be vertical to x-axis, what's the proper way to obtain the variance?

A: If you are fitting a line to data but are okay with it being vertical, this looks less like linear regression (which assumes y is a function of x) and more like principal component analysis.  Which can be done with sklearn as follows, computing the variance along the way.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

data = np.random.multivariate_normal([1, 1], [[0.2, 0], [0, 4]], size=100)
pca = PCA(n_components=2)
pca.fit(data)
print('Residual variance', pca.explained_variance_[1])

I fit two components here, which together explain all the variance since the data is 2D. The first component is the line that takes place of the regression line in this model. The second is where the residuals are, so the residual variance comes from there. Visualization:
line_direction = pca.components_[0]
M = np.abs(data).max()
t = np.linspace(-M, M)
center = data.mean(axis=0)
line = line_direction*t[:, None] + center
plt.plot(line[:, 0], line[:, 1], 'r')
plt.plot(data[:, 0], data[:, 1], '.')
plt.axes().set_aspect('equal', 'datalim')
plt.show()

The simulated data is random, but this is what it can look like:

Residual variance 0.23184791439896069

This is the variance in the direction perpendicular to the chosen line, not in the vertical direction (which wouldn't be appropriate here).
Related: Total least squares


text:
Q: When should you use different numeric types in Postgres? What are the pros and cons of different numeric types? In particular when should you use inexact floating values vs exact floating values?
And is there a difference between decimal and numeric? When should each be used?
Thanks!

A: The manual actually is pretty good at explaining it: http://www.postgresql.org/docs/9.3/static/datatype-numeric.html
decimal and numeric are the same.
Floating point by definition is inexact. It is faster and usually it's precision is good enough. For example if we use real type and store a distance in kilometres it would still be precise down to one milimetre.
However there are places when you need to use precise numbers, for example money transactions.


text:
Q: Infinite Embedded Lists input: list of [integers, lists of integers, lists of lists of integers ad infinitum]
output: list of [integers]
heres my initial solution:
x = [[1, 2], 1, [1], [2, 1, [1, 2]]]
numb = []
for l in x:
  if type(l) is int:
    numb.append(l)
else:
    for l2 in l:
        if type(l2) is int:
            numb.append(l2)
        else:
            for l3 in l2:
                numb.append(l3)
print(numb)

however this solution is only good up to three embedded lists...
i wonder if there is a way of dealing with possibly infinite embedded lists....
i.e. is there a way of coding this solution without n nested for loops for n embedded lists


text:
Q: Dynamic LINQ Where query with joining other tables I have several tables (the exact number is not known when the program is build) looking like this (the number of rows and columns may differ from table to table):

The source data is stored in a data set. Now I want to generate a new table where all data of all ids is stored (the picture shows only the result for id 10 and 20 but the target table should contain the data for all ids):

The equivalent SQLite statement for that looks like this:
SELECT * FROM Dataset
JOIN Datensatz2 ON (Dataset.ID=Datensatz2.ID)
JOIN Datensatz3 ON (Datensatz3.ID=Dataset.ID)
JOIN Datensatz4 ON (Datensatz4.ID=Dataset.ID)
WHERE Dataset.Id=10
UNION
SELECT * FROM Dataset
JOIN Datensatz2 ON (Dataset.ID=Datensatz2.ID)
JOIN Datensatz3 ON (Datensatz3.ID=Dataset.ID)
JOIN Datensatz4 ON (Datensatz4.ID=Dataset.ID)
WHERE Dataset.Id=20
...

The double id columns will be removed afterwards so don´t worry about that. The questions is now how to convert it as a dynamic LINQ query?

A: There are plenty of open question but maybe this helps to solve it. Since the tables are already stored in a DataSet you could use Linq-To-DataSet and Enumerable.GroupBy to group by ID:
var idTables = ds.Tables.Cast<DataTable>().Where(t => t.Columns.Contains("Id"));
if(!idTables.Any()){ MessageBox.Show("No id-tables"); return; }

var idRowGroups = idTables.SelectMany(t => t.AsEnumerable())
    .GroupBy(row => row.Field<int>("Id"))
    .Select(grp => new { ID = grp.Key, Rows = grp });

foreach(var idGroup in idRowGroups)
{
  Console.WriteLine("ID:{0} Rows:{1}"
      , idGroup.ID
      , String.Join(" | ", idGroup.Rows.Select(row => String.Join(",", row.ItemArray))));
}

Sample data:
var ds = new DataSet();
DataTable t1 = new DataTable();
t1.Columns.Add("Id", typeof(int));
t1.Columns.Add("Data", typeof(int));
t1.Rows.Add(1, 1);
t1.Rows.Add(2, 10);
t1.Rows.Add(3, 100);
t1.Rows.Add(4, 1000);
ds.Tables.Add(t1);
t1 = new DataTable();
t1.Columns.Add("Id", typeof(int));
t1.Columns.Add("Data", typeof(int));
t1.Rows.Add(4, 5);
t1.Rows.Add(5, 50);
t1.Rows.Add(7, 500);
t1.Rows.Add(3, 5997);
ds.Tables.Add(t1);
t1 = new DataTable();
t1.Columns.Add("Id", typeof(int));
t1.Columns.Add("Data1", typeof(int));
t1.Columns.Add("Data2", typeof(int));
t1.Rows.Add(1, 5, 0);
t1.Rows.Add(3, 7, 1);
t1.Rows.Add(5, 9, 11);
t1.Rows.Add(7, 11, 222);
ds.Tables.Add(t1);

Output:
ID:1 Rows:1,1 | 1,5,0
ID:2 Rows:2,10
ID:3 Rows:3,100 | 3,5997 | 3,7,1
ID:4 Rows:4,1000 | 4,5
ID:5 Rows:5,50 | 5,9,11
ID:7 Rows:7,500 | 7,11,222

A: Ok, I finally made it but it seems to be much too complicated. If someone is able to help me improve the solution he is very welcome.
DataSet dsResult = new DataSet();
        var idTables = ds.Tables.Cast<DataTable>().Where(t => t.Columns.Contains("ID"));
        if (!idTables.Any()) { MessageBox.Show("No id-tables"); return; }

        var idRowGroups = idTables.SelectMany(t => t.AsEnumerable())
            .GroupBy(row => row.Field<Int64>("ID"))
            .Select(grp => new { ID = grp.Key, Rows = grp });

        foreach (var idGroup in idRowGroups)
        {
            var liste = idGroup.Rows.ToList();
            for (int i = 0; i < liste.Count; i++)
            {
                if (!dsResult.Tables.Contains(liste[i].Table.TableName))
                {
                    dsResult.Tables.Add(liste[i].Table.TableName);
                    foreach (DataColumn dtCol in liste[i].Table.Columns)
                    {
                        if (dsResult.Tables[liste[i].Table.TableName].Columns.Contains("ID"))
                            dsResult.Tables[liste[i].Table.TableName].Columns.Add(dtCol.ColumnName+i.ToString());
                        else
                        {
                            dsResult.Tables[liste[i].Table.TableName].Columns.Add(dtCol.ColumnName);
                        }
                        dsResult.Tables[liste[i].Table.TableName].Columns[dtCol.ColumnName].DataType = dtCol.DataType;
                    }
                 }
                DataRow dRow = dsResult.Tables[liste[i].Table.TableName].NewRow();
                dRow.ItemArray = liste[i].ItemArray;
                dsResult.Tables[liste[i].Table.TableName].Rows.Add(dRow);
            }

            IEnumerable<IEnumerable<DataRow>> allTablesRows = dsResult.Tables.Cast<DataTable>()
            .Select(table => table.AsEnumerable())
            .CartesianProduct();

            int k = 0;

            foreach (var rows in allTablesRows)
            {
                DataRow zRow = dsErgebnis.Tables[2].NewRow();
                foreach (DataRow dRow in rows)
                {
                    for (int i = 0; i < dRow.ItemArray.Length; i++)
                    {
                        zRow[k] = dRow.ItemArray[i];
                        k++;
                    }
                }
                k = 0;
                dsErgebnis.Tables[2].Rows.Add(zRow);
            }
            dsResult.Clear();
       }

First I filter the content by ID.
Then I put the result in a new tables (all rows with the ID 10 I found in 'Datasatz2' in dataset 'ds' for example I put to a new table 'Datasatz2' in the dataset 'dsResult').
At least I build the cartesian product of all tables and store it in dtaset dsErgebnis.
The result is what I expect but as mentioned before I am not satisfied with the solution.


text:
Q: Associative Container as Function Template Parameter I would like to know how I would write a function that can accept as a parameter an associative container that itself accepts two or more template parameters. For example, if I want to write a function that works for std::map, I could write something like what is shown below.
template <class Map, class Key, class Value, class Compare, class Allocator>
void foo(Map<Key, Value, Compare, Allocator>& map);

However, this will not work for boost::unordered_map, since boost::unordered_map accepts five template parameters. I could accept the map as a single template parameter and use the traits that it should support in order to deduce the key and value types later, but for nested maps, the code becomes very verbose and difficult to maintain. Is there an easier way to write such a function but still have it work for any associative container that accepts any number of template parameters greater than or equal to two?
Please note that accepting iterators instead of containers as parameters will not suffice, because I need more information about the container on which the iterator operates than what the iterator can provide.
Thank you very much!

A: Why not just use the simple approach with a single template parameter:
template <typename C> void foo(const C & container)
{
  typedef typename C::key_type key_type;
  typedef typename C::mapped_type mapped_type;

  // etc.
}

You can add some member-type-checking typetraits is you want additional checks that those member types exist, but that might not give any additional benefit.
Alternatively, you could do some generic pattern matching, though only with classes, not functions:
 template <typename> struct AtLeastTwo;

 template <typename K, typename V, typename ...Args>
 struct AtLeastTo<K, V, Args...>
 {
   // now have types K and V
 };

 typedef std::unordered_map<int, Foo, MyHash> map_type;
 AtLeastTwo<map_type> m;
 // ...

A: A type does not convey information on whether it is an associative sequence, such is a semantic meaning. If you wan't to support all kinds of associative sequence, as per the standard interface, your best bet is to go with a single template parameter and use traits to introspect its key/value type and so on.


text:
Q: ORA-06564 When accessing External table across schemas We have 2 schemas in our DB and I am trying to access the external table row count in schema A from schema B.
The external table has a grant GRANT SELECT ON A.LETTER TO B WITH GRANT OPTION;
When I call: SELECT COUNT(*) FROM A.LETTER; from Schema B I always get ORA-06564: object A does not exist
This is the same grant we have on regular tables and we are able to get counts from these tables. I'm not sure what the problem is here or how best to fix it?

A: Schema B needs to be granted read privileges on the external table's directory (at least; it also needs write unless the table has NOBADFILE and NOLOGFILE):
GRANT READ,WRITE ON DIRECTORY A TO B;

It isn't clear if you actually have a directory object with the same name as the schema, or if you mixed up the names a bit hiding them in the question. But the object name in the ORA-06564 should be a directory object name.
It's also possible the external table references more than one directory - for the data file, logs file, etc. - and appropriate privileges would need to be granted to all of them if so.
If you don't want B to be able to access the directory you could create a view and grant select on that instead:
CREATE VIEW A.V_LETTER AS SELECT * FROM A.LETTER;
GRANT SELECT ON A.V_LETTER TO B;

Then B can SELECT COUNT(*) FROM A.V_LETTER, without needing directory privs; but having a different name may be an issue for you (or at least be slightly confusing). B could create a synonym for A.V_LETTER of course, but then you'd have SELECT COUNT(*) FROM LETTER or FROM B.LETTER, which still don't match the pattern you seem to be using.


text:
Q: How can I raise Exception using eventlet in Python? I have a simply code:
import eventlet
def execute():
    print("Start")
    timeout = Timeout(3)
    try:
        print("First")
        sleep(4)
        print("Second")
    except:
        raise TimeoutException("Error")
    finally:
        timeout.cancel()
    print("Third")

This code should throw TimeoutException, because code in 'try' block executing more than 3 seconds.
But this exception shallows in the loop. I can't see it in the output
This is output:
Start
First

Process finished with exit code 0

How can I raise this exception to the output?

A: Change sleep(4) to
eventlet.sleep(4)

A: This code will not output Start... because nobody calls execute(), also sleep is not defined. Show real code, I will edit answer.
For now, several speculations:

*

*maybe you have from time import sleep, then it's a duplicate of Eventlet timeout not exiting and the problem is that you don't give Eventlet a chance to run and realize there was a timeout, solutions: eventlet.sleep() everywhere or eventlet.monkey_patch() once.

*maybe you don't import sleep at all, then it's a NameError: sleep and all exceptions from execute are hidden by caller.

*maybe you run this code with stderr redirected to file or /dev/null.

Let's also fix other issues.
try:
  # ...
  sleeep()  # with 3 'e', invalid name
  open('file', 'rb')
  raise Http404
except:
  # here you catch *all* exceptions
  # in Python 2.x even SystemExit, KeyboardInterrupt, GeneratorExit
  #  - things you normally don't want to catch
  # but in any Python version, also NameError, IOError, OSError,
  # your application errors, etc, all irrelevant to timeout
  raise TimeoutException("Error")

In Python 2.x you never write except: only except Exception:.
So let's catch only proper exceptions.
try:
  # ...
  execute_other() # also has Timeout, but shorter, it will fire first
except eventlet.Timeout:
  # Now there may be other timeout inside `try` block and
  # you will accidentally handle someone else's timeout.
  raise TimeoutException("Error")

So let's verify that it was yours.
timeout = eventlet.Timeout(3)
try:
  # ...
except eventlet.Timeout as t:
  if t is timeout:
    raise TimeoutException("Error")
  # else, reraise and give owner of another timeout a chance to handle it
  raise

Here's same code with shorter syntax:
with eventlet.Timeout(3, TimeoutException("Error")):
  print("First")
  eventlet.sleep(4)
  print("Second")
print("Third")

I hope you really need to substitute one timeout exception for another.


text:
Q: How do I get rid of global $var; ? - PHP some people keep telling me that globals in a function aren't a really good idea.
I am not THAT good in PHP5 or OOP but i'm still learning. Now, my question to you is:
Is there a better way than doing this? :
<?php
class Name {
     final public function Example() {
          global $db;
          $db->query("SELECT * FROM users");
          ....
     }
}
?>

Thanks!


text:
Q: How to make restart this loop , when user enters 1, and stop when 0 I've  tried to get a number '6' generated inside a while loop, then count how many times this loop had to run before getting number 6, then if user inputs 1 this loop will run again, generate number 6 again and count how many tries, but the problem I'am facing is that when I enter 1 I'm getting same results as in previous loop.
#include <iostream>

#include <cstdlib>    // random numbers header file//
#include <ctime>    // used to get date and time information
using namespace std;
int main()
{

int counter = 0;
int roll = 0;
int userChoice =1;
int total = 0;
float average = 0;
int programCounter = 0;
srand(time(0));

while (userChoice > 0)
{

    while (roll != 6)
    {

        roll = rand() % 6 + 1; // generate a random number
        counter++;

    }
    total = total + counter;

    cout << "Do you want to continue?" << endl;
    cout << "Enter positive number to continue" << endl;
    cout << "To terminate enter 0" << endl;

    cin >> userChoice;

    programCounter++;

}

average = total / programCounter;
cout << "Avarage number of rolls before getting 6 is " <<  average;

}
my expected result is to get random number generator working again inside while loop and  to generate number 6 again, so later I can use number of rolls to count the average number of rolls before 6 was rolled.

A: Here:
while (roll != 6)

you check the condition before you roll the number. Once you rolled a 6, the condition will never be false.
In general it is good practice to declare variables only when you need them, and this would have avoided the bug in your code (also counter is not properly reset in your code):
int roll = 0;
int counter = 0;
while (roll != 6)
{
     roll = rand() % 6 + 1; // generate a random number
     counter++;
}

Also note that for anything beyond simple toy randomness rand should be avoided. Use the facilities provided in <random> instead.


text:
Q: Vercel NodeJS App Deployment Error: Cannot find module './dist/cli.js' and etc I made a Sapper App, a NodeJS APP which works fine on my localhost and linux server, but when I try to deploy this on vercel, it keeps giving me this error.
10:19:52.559    Running "npm run build"
10:19:52.742    > HAS-LIBRARY@0.0.1 build /vercel/6e2526b7
10:19:52.742    > CONFIG=./config.json sapper build --legacy
10:19:52.784    internal/modules/cjs/loader.js:983
10:19:52.784      throw err;
10:19:52.784      ^
10:19:52.784    Error: Cannot find module './dist/cli.js'
10:19:52.784    Require stack:
10:19:52.784    - /vercel/6e2526b7/node_modules/.bin/sapper
10:19:52.784        at Function.Module._resolveFilename (internal/modules/cjs/loader.js:980:15)
10:19:52.784        at Function.Module._load (internal/modules/cjs/loader.js:862:27)
10:19:52.784        at Module.require (internal/modules/cjs/loader.js:1042:19)
10:19:52.784        at require (internal/modules/cjs/helpers.js:77:18)
10:19:52.784        at Object.<anonymous> (/vercel/6e2526b7/node_modules/.bin/sapper:2:1)
10:19:52.784        at Module._compile (internal/modules/cjs/loader.js:1156:30)
10:19:52.784        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1176:10)
10:19:52.784        at Module.load (internal/modules/cjs/loader.js:1000:32)
10:19:52.784        at Function.Module._load (internal/modules/cjs/loader.js:899:14)
10:19:52.784        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
10:19:52.784      code: 'MODULE_NOT_FOUND',
10:19:52.784      requireStack: [ '/vercel/6e2526b7/node_modules/.bin/sapper' ]
10:19:52.784    }
10:19:52.786    npm ERR! code ELIFECYCLE
10:19:52.786    npm ERR! errno 1
10:19:52.787    npm ERR! HAS-LIBRARY@0.0.1 build: `CONFIG=./config.json sapper build --legacy`
10:19:52.787    npm ERR! Exit status 1
10:19:52.787    npm ERR!
10:19:52.787    npm ERR! Failed at the HAS-LIBRARY@0.0.1 build script.
10:19:52.787    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
10:19:52.790    npm ERR! A complete log of this run can be found in:
10:19:52.791    npm ERR!     /vercel/.npm/_logs/2020-08-01T01_19_52_787Z-debug.log
10:19:52.795    Error: Command "npm run build" exited with 1