text:
Q: How to loop through bookmark state inputs and restore in the right order? I have 3 modules to get histograms, boxplots and tables. The reactivity and saving the state works great, but I'm unable to restore them in the right order.
I've tried onRestored which jumbles the order or groups the modules. I've also tried to reset the inputs so that further saving and reloading doesn't change the order. onRestore is close but it reorders the output in the reverse order.
library(shiny)
library(janitor)

histogramUI <- function(id,var,bins) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var"), "Variable", choices = names(mtcars),selected=var),
                     numericInput(NS(id, "bins"), "bins", value = bins, min = 1)),
             column(8, plotOutput(NS(id, "hist"))))
  )
}

histogramServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var]])
    output$hist <- renderPlot({
      hist(data(), breaks = input$bins, main = input$var)
    }, res = 96)
  })
}

tableUI <- function(id,var,bins) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var"), "Variable", choices = names(mtcars),selected=var),

             column(8, tableOutput(NS(id, "tab")))))
  )
}

tableServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var]])
    output$tab <- renderTable({
      tabyl(data(), main = input$var)
    })
  })
}

boxUI <- function(id,var) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var2"), "Variable", choices = names(mtcars),selected=var),

             column(8, plotOutput(NS(id, "box"))))
  ))
}

boxServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var2]])
    output$box <- renderPlot({
      boxplot(data(), main = input$var2)
    })
  })
}

ui <- function(request){
  fluidPage(
    bookmarkButton(),
    actionButton("add", "Add Histogram"),
    actionButton("add2", "Add Boxplot"),
    actionButton("add3", "Add Table"),
    div(id = "add_here")
  )
}

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

  observeEvent(input$add, {
    bins <- 10
    histogramServer(paste0("hist_", input$add))
    insertUI(selector = "#add_here", ui = histogramUI(paste0("hist_", input$add),input$var,bins))#}
  })

  observeEvent(input$add2, {
     boxServer(paste0("box_", input$add2))
    insertUI(selector = "#add_here", ui = boxUI(paste0("box_", input$add2), input$var2))
  })

  observeEvent(input$add3, {
    tableServer(paste0("tab_", input$add3))
    insertUI(selector = "#add_here", ui = tableUI(paste0("tab_", input$add3), input$var))
  })

  onRestored(function(state){
    hist_var <- stringr::str_extract(names(state$input),'hist.*var')
    hist_var <- sort(hist_var[!is.na(hist_var)])

    hist_bin <- stringr::str_extract(names(state$input),'hist.*bin')
    hist_bin <- sort(hist_bin[!is.na(hist_bin)])

    box_var <- stringr::str_extract(names(state$input),'box.*var2')
    box_var <- sort(box_var[!is.na(box_var)])

    tab_var <- stringr::str_extract(names(state$input),'tab.*var')
    tab_var <- sort(tab_var[!is.na(tab_var)])

    print(hist_var)
    print(box_var)
    print(tab_var)

    if (length(hist_var)>1) {
      for (i in 1:(length(hist_var)-1)) {
        histogramServer(paste0("hist_", i))
        insertUI(selector = "#add_here", ui = histogramUI(paste0("hist_", i),state$input$hist_var[i],state$input$hist_bin[i]))
      }
    }

    if (length(box_var)>1) {
      for (i in 1:(length(box_var)-1)) {
        boxServer(paste0("box_", i))
        insertUI(selector = "#add_here", ui = boxUI(paste0("box_", i),state$input$box_var[i]))
      }
    }

    if (length(tab_var)>1) {
      for (i in 1:(length(tab_var)-1)) {
        tableServer(paste0("tab_", i))
        insertUI(selector = "#add_here", ui = tableUI(paste0("tab_", i),state$input$tab_var[i]))
      }
    }

    hist_var <- NULL
    hist_bin <- NULL
    box_var <- NULL
    tab_var <- NULL

  })

}

shinyApp(ui, server, enableBookmarking = "server")

A: You could use onBookmark to save state$exclude which gives the order of the modules.
The buttons should also be excluded from bookmarking with setBookmarkExclude :
library(shiny)
library(janitor)

histogramUI <- function(id,var,bins) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var"), "Variable", choices = names(mtcars),selected=var),
                     numericInput(NS(id, "bins"), "bins", value = bins, min = 1)),
             column(8, plotOutput(NS(id, "hist"))))
  )
}

histogramServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var]])
    output$hist <- renderPlot({
      hist(data(), breaks = input$bins, main = input$var)
    }, res = 96)
  })

}

tableUI <- function(id,var,bins) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var"), "Variable", choices = names(mtcars),selected=var),

                     column(8, tableOutput(NS(id, "tab")))))
  )
}

tableServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var]])
    output$tab <- renderTable({
      tabyl(data(), main = input$var)
    })
  })

}

boxUI <- function(id,var) {
  tagList(
    fluidRow(column( 4, selectInput(NS(id, "var2"), "Variable", choices = names(mtcars),selected=var),

                     column(8, plotOutput(NS(id, "box"))))
    ))

}

boxServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    data <- reactive(mtcars[[input$var2]])
    output$box <- renderPlot({
      boxplot(data(), main = input$var2)
    })
  })

}

ui <- function(request){
  fluidPage(
    bookmarkButton(),
    actionButton("add", "Add Histogram"),
    actionButton("add2", "Add Boxplot"),
    actionButton("add3", "Add Table"),
    div(id = "add_here")
  )
}

server <- function(input, output, session) {
  setBookmarkExclude(c('add','add2','add3'))
  add_id <- reactiveVal(0)
  add2_id <- reactiveVal(0)
  add3_id <- reactiveVal(0)

  observeEvent(input$add, {
    bins <- 10
    histogramServer(paste0("hist_", input$add+add_id()))
    insertUI(selector = "#add_here", ui = histogramUI(paste0("hist_", input$add+add_id()),input$var,bins))#}
  })

  observeEvent(input$add2, {
    boxServer(paste0("box_", input$add2+add2_id())) #changed add_id() to add2_id()
    insertUI(selector = "#add_here", ui = boxUI(paste0("box_", input$add2+add2_id()), input$var2))
  })

  observeEvent(input$add3, {
    tableServer(paste0("tab_", input$add3+add3_id()))
    insertUI(selector = "#add_here", ui = tableUI(paste0("tab_", input$add3+add3_id()), input$var))
  })
  onBookmark(function(state) {
    state$values$modules <- state$exclude
    state$values$add <- state$input$add + add_id()
    state$values$add2 <- state$input$add2 + add2_id()
    state$values$add3 <- state$input$add3 + add3_id()
  })

  onRestore(function(state){
    add_id(state$values$add)
    add2_id(state$values$add2)
    add3_id(state$values$add3)
    modules <- state$values$modules
    if (length(modules)>1) {
      for (i in 1:(length(modules))) {
        if (substr(modules[i],1,4)=='hist') {
          histogramServer(modules[i])
          insertUI(selector = "#add_here", ui = histogramUI(modules[i],paste0(modules[i],"-var"),paste0(modules[i],"-bin")))
        }
        if (substr(modules[i],1,3)=='box') {
          boxServer(modules[i])
          insertUI(selector = "#add_here", ui = boxUI(modules[i],paste0(modules[i],"-var")))
        }
        if (substr(modules[i],1,3)=='tab') {
          tableServer(modules[i])
          insertUI(selector = "#add_here", ui = tableUI(modules[i],paste0(modules[i],"-var")))
        }

      }
    }

  })

}

shinyApp(ui, server, enableBookmarking = "server")


text:
Q: Is it possible to publish a geoprocessing services that uses a custom gptool on ArcGIS Server 10? I have developed a custom GP tool in C# which does a bunch of processing on a given layer.
It works great in ArcMap on all machines that I have deployed it to. I created a model which uses this tool and want to publish it as a geoprocessing services. It worked without any problems on our testing machine (This was probably because the testing machine has Arcgis Desktop, as well as Server, & I published the service using the ArcCatalog on that machine itself).
Today I had to deploy it to our production server. This does not have ArcGIS Desktop. So I registered the DLL using ESRIRegasm on the server. But No matter what I do, I can't get a Geoprocessing service running using the custom tool. I tried placing the toolbox on the server and publishing it. It did get published, but when I conusmed it from ArcMAp, I got the error "ERROR 000816: The tool is not valid".
Over on ESRI forums, there have been just a few threads about this issue; And the only one which was marked as resolved, talked of registering the dll using the /codebase switch. (this was with ArcGIS 9.3.1)
Has anyone succesfully deployed a custom geoprocessing tool to a server, with ArcGIS server but not ArcGIS desktop?

A: You can't deploy this without access to the GAC libraries, which are installed as part of ArcGIS Desktop or ArcGIS Server for .NET; there is no way of deploying an ArcObjects toolkit without first installing the above.
We deployed it with all it's library files contained in the deployment.  This worked, but was completely at odds with ESRI licensing.
So in short, you can't do it without AGD or AGS 10 installed.
One other thing to note, regardless, and a major difference betwen 9.3.1 and 10, is that Once your tool model runs correctly, the tool needs to registered with the ESRI component categories before it can run within an ArcGIS Server 10 instance.
We have done this registration by creating a C# .Net setup project within our base C# .NET solution.  This project has changed completely as a result of differences in component category registration functionality between ArcGIS 9.3.1 and ArcGIS 10 products.
Esri recommend placing common component category registration functionality in a separate C# .NET project that produces a DLL.  This common DLL is then included within each setup project that needs it.
nerdy:
In ArcGIS 9 you used to register custom components with the ESRI component categories using the Windows registry.  That's all gone and you do it via the 'InvokeEsriRegAsm'.  It's the ESRI way of hooking the assembly in with COM without polluting the registry
E.g. Example of what I mean : ESRIRegAsmtility

A: The solution in the short term is to register the custom dll on the server with the codebase switch; i.e. Use the following syntax at the command path:

regasm ..[path to dll] /codebase

In the Long term, it is not a wise decision to continue with a custom geoprocessing tool, since god alone knows whether this will work with ArcGIS 10.1.
I'll be moving towards a custom SOE, to process my data on the server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Which compiler is used when building solution in Visual Studio? I was reading up on JIT and AOT compiler and found that CLR in .NET uses JIT compilation. But I also read that the build process in Visual Studio includes compilation and linking, among other things.
I assume JIT compilation happens when the request hits IIS. What kind of compilation happens during the build phase in Visual Studio?

A: JIT is a "Just-In-Time" compiler which is used to compile IL to the machine commands. Compiler compiles your code to the IL language.
Compiler used to compile solution is MSBuild/Roslyn. There are other compilers used to compile e.g. web pages like ASP.NET Compilation Tool.


text:
Q: Unable to run commands in docker container using docker-compose EDITED - Added folder structure
I'm trying to run a node.js app in a docker container using docker-compose, however, the container fails to run the specified command and exits.
I'm running docker-for-mac, version 17.09.0-ce-mac35 (19611)
This is my folder structure:
.
├── docker-compose.yml
├── backend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)
├── frontend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)

This is my docker-compose file:
version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - "./node_modules/.bin/nodemon --watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js"

And this is my Dockerfile:
FROM node:6-alpine

COPY ./package.json src/
COPY ./npm-shrinkwrap.json src/

RUN cd /src && npm install

COPY . /src

WORKDIR /src

CMD ["./bin/www"]

Notice that the docker-compose file overrides the command.
When I run it, I get the following error:
Cannot start service ihm-backend: oci runtime error: container_linux.go:265:
starting container process caused "exec: \"./node_modules/.bin/nodemon --watch
./ --inspect=0.0.0.0:9222 --nolazy ./app.js\": stat ./node_modules/.bin/nodemon
--watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js: no such file or directory"

I tried to play with the command a bit - when changing it to ls or pwd I got the expected output. However, once I try to use npm or anything from the file-system like ls ./node_modules, I get the same error. Also, if I just start the container into a shell, I'm able to run any command I want, including npm scripts

A: I found the problem. Seems like there's an issue with having spaces in the command attribute of the docker-compose file. The solution was to split it down to an array like this:
version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - /src/node_modules/.bin/nodemon
      - --watch
      - ./
      - --inspect=0.0.0.0:9222
      - --nolazy
      - ./app.js

A: Not sure if this helps, but this is what I use for my node app and it works .
Dockerfile
FROM node:carbon

# Create app directory
WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install
RUN npm install nodemon -g

# Bundle app source
COPY . .

docker-compose
web:
  build: .
  volumes:
    - ".:/src/app"
  ports:
    - "3000:3000"
  command:
      - "nodemon"


text:
Q: How to handle express.js csrf exception nicely? I have an expressjs server with csrf running.  I guess because I have three subdomains running on different expressjs servers, sometimes they got screw up on the cookie and throw this:

Error: Forbidden at Object.exports.error
  (/home/ubuntu/web/server/node_modules/express/node_modules/connect/lib/utils.js:63:13)
  at createToken
  (/home/ubuntu/web/server/node_modules/express/node_modules/connect/lib/middleware/csrf.js:82:55)
  at
  /home/ubuntu/web/server/node_modules/express/node_modules/connect/lib/middleware/csrf.js:54:7
  at Object.ondone
  (/home/ubuntu/web/server/node_modules/express/node_modules/connect/node_modules/uid2/index.js:46:8)

This is ugly.   So, how should I capture this exception / error nicely and just output a res.send() with some nicely error message?
In addition, in my case, because 3 subdomains (of the same domain) run by 3 different express servers, all use csrf.  It seems that it doesn't work nicely together.  Is there a way to solve that?
Thanks.


text:
Q: PowerShell - Limit the search to only one OU Ive got this cmdlet and I'd like to limit the results to only one OU:
Get-ADUser -Filter  {(Enabled -eq $false)} | ? { ($_.distinguishedname -notlike '*Disabled Users*') }

Now Ive tried to use
-searchbase "ou=FirstOU,dc=domain,dc=com"

But if I use -SearchBase I get this error:
Where-Object : A parameter cannot be found that matches parameter name 'searchb
ase'.
At line:1 char:114
+ Get-ADUser -Filter  {(Enabled -eq $false)} | ? { ($_.distinguishedname -notli
ke '*Disabled Users*') } -searchbase <<<<  "ou=FirstOU,dc=domain,dc=com"
    + CategoryInfo          : InvalidArgument: (:) [Where-Object], ParameterBi
   ndingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Comm
   ands.WhereObjectCommand

What Im trying to do is to get all the disabled users from a specific OU, BUT, there is an OU INSIDE that FirstOU that I want to exclude: the "Disabled Users" OU.
as you might have guessed I want to find disabled users in a specific OU that are not in the "Disabled Users" OU inside that OU.
my structure:
Forest
   FirstOU
      Users,groups,etc...
      Disabled Users OU

A: Easiest way would be to put the -SearchBase before the -Filter.
Get-ADUser -searchbase "ou=FirstOU,dc=domain,dc=com" -Filter {(Enabled -eq $false)} | ? { ($_.distinguishedname -notlike '*Disabled Users*') }

Gets around the problem of having to use -SearchBase with Get-ADUser, and not Where-Object (? is aliased to Where-Object in PowerShell) by running the Where-Object after you've already passed your -SearchBase to Get-ADUser.

A: The easiest way to limit the search to one OU is using SearchScope:
Get-ADUser -Filter  {(Enabled -eq $false)} -SearchScope OneLevel -SearchBase "ou=FirstOU,dc=domain,dc=com"

A: The -SearchBase parameter has to be used with Get-ADUser, not Where-Object (aliased by ?). This should work:
Get-ADUser -Filter {(Enabled -eq $false)} -SearchBase "ou=FirstOU,dc=domain,dc=com" | ? { ($_.distinguishedname -notlike '*Disabled Users*') }


text:
Q: Bandwidth vs Uplink Port Speed If a dedicated server has -
1. 1Gbps uplink port speed
2. 1Mbps unmetered bandwidth
Under what circumstances will bandwidth be a limiting factor for serving requests and under what circumstances will the uplink port speed be a limiting factor for serving requests?
What is the difference between bandwidth and uplink port speed?

A: I assume you're talking about paying monthly for a dedicated server that someone else hosts. The 1Gbps uplink port is the limit of the server. The 1Mbps is what they are limiting you to out of that 1Gbps. You could pay them for more bandwidth, up to a limit of 1Gbps.

A:
What is the difference between bandwidth and uplink port speed?

Uplink port speed is the physical connection between your server's network card (whether physical or virtual) and the switch it's connected to. The port speed has precious little to do with how much bandwidth is available to your server other than setting a top bound on that number.
In your case, your allotted bandwidth is 1Mbps, so that will be your limiting factor.


text:
Q: How do you emit multiple flow values as an object at the repository level? Say I have two flows:
val x: Flow<Long?> = dao.getValueX()
val y: Flow<Long?> = dao.getValueY()

Can I have a third flow, flow z which will emit these two as a pair?
Say I have XYObject() where XYObject looks like
X: Long?
Y: Long?

I want to basically emit a flow of z where it emits XYObject with X and Y populated from the two flows above. I actually have 3-4 things I want to emit, but kept it to two for the sake of the example.

A: You can use combine() transform function:

Returns a Flow whose values are generated with transform function by
combining the most recently emitted values by each flow.

source
And define z like this:
import kotlinx.coroutines.flow.combine

data class XYObject(val x: Long?, val y: Long?)

val x: Flow<Long?> = dao.getValueX()
val y: Flow<Long?> = dao.getValueY()
val z: Flow<XYObject> = x.combine(y) { _x: Long?, _y: Long? ->
    XYObject(_x, _y)
}


text:
Q: QuestaSim .desktop closes after a short time I have created a  .desktop file for an application I have installed. This is the code:
[Desktop Entry]
Encoding=UTF-8
Type=Application
Name=QuestaSim
Comment=QuestaSim
Icon=/usr/share/icons/QuestaSim.png
Path=/storage/questa/v10.7c/questasim/linux_x86_64
Exec=vsim
Terminal=false

However, when I double-click this file, the program opens but closes after without showing me the program itself, I just check whether it is opening or not from System Monitor. However, when I run vsim from the terminal, it runs perfectly. Also, when I change the last line of me .desktop file to Terminal=true it also runs perfectly with starting a terminal.
When I run the program by just writing vsim to the terminal or double-clicking the working .desktop file, this is the output on the terminal:
Reading pref.tcl
However, when I run the program from the not working .desktop file by writing gtk-launch <filename>.desktop, the output is:
Reading pref.tcl

# 10.7c

#
# <EOF>

and it does not terminate. What can be the reason, and what is your suggestion for the solution? Thanks.
Edit1: This is the screen that I want to see. When I run vsim from command line, it works fine. You can see the graphical interface, the output at terminal, and system monitor.

However, when I run it from the .desktop file I use, the output at terminal is different as you can see, and the vish process terminates after just a second. The programs graphical interface also does not show up.


text:
Q: ICMP replies captured but not considered by ping There is a host with a tunnel interface tunint1 with an assigned IP address. When I'm trying to ping via this interface I cannot see any replies but there are ICMP packets (both requests and replies), which I can capture using tshark. The questions are why the ping command does not consider these ICMP packets and how to fix this?
ping:
desktopuser@desktop:~$ ping -I tunint1 ya.ru
PING ya.ru (87.250.250.242) from 60.60.0.1 tunint1: 56(84) bytes of data.
^C
--- ya.ru ping statistics ---
9 packets transmitted, 0 received, 100% packet loss, time 8219ms

tshark's capture:
desktopuser@desktop:~$ sudo tshark -i tunint1
Running as user "root" and group "root". This could be dangerous.
Capturing on 'tunint1'
    1 07:27:53,679603780    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=1/256, ttl=64
    2 07:27:53,788377518 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=1/256, ttl=53 (request in 1)
    3 07:27:54,730464037    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=2/512, ttl=64
    4 07:27:54,832966645 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=2/512, ttl=53 (request in 3)
    5 07:27:55,754464273    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=3/768, ttl=64
    6 07:27:55,809589662 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=3/768, ttl=53 (request in 5)
    7 07:27:56,778472734    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=4/1024, ttl=64
    8 07:27:56,842580324 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=4/1024, ttl=53 (request in 7)
    9 07:27:57,802464734    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=5/1280, ttl=64
   10 07:27:57,875565627 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=5/1280, ttl=53 (request in 9)
   11 07:27:58,827464430    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=6/1536, ttl=64
   12 07:27:58,904626014 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=6/1536, ttl=53 (request in 11)
   13 07:27:59,851471889    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=7/1792, ttl=64
   14 07:27:59,947978524 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=7/1792, ttl=53 (request in 13)
   15 07:28:00,874467413    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=8/2048, ttl=64
   16 07:28:00,930381305 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=8/2048, ttl=53 (request in 15)
   17 07:28:01,899461748    60.60.0.1 → 87.250.250.242 ICMP 84 Echo (ping) request  id=0x6571, seq=9/2304, ttl=64
   18 07:28:01,981439474 87.250.250.242 → 60.60.0.1    ICMP 84 Echo (ping) reply    id=0x6571, seq=9/2304, ttl=53 (request in 17)
^C18 packets captured

ifconfig:
desktopuser@desktop:~$ ifconfig
enp6s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.23.17.21  netmask 255.255.0.0  broadcast 10.23.255.255
        inet6 fe80::94c6:8e21:7835:ce7c  prefixlen 64  scopeid 0x20<link>
        ether a8:a1:59:3e:9e:7a  txqueuelen 1000  (Ethernet)
        RX packets 36260578  bytes 39566996759 (39.5 GB)
        RX errors 0  dropped 2  overruns 0  frame 0
        TX packets 31232948  bytes 28182106819 (28.1 GB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Local Loopback)
        RX packets 69867276  bytes 3197422953678 (3.1 TB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 69867276  bytes 3197422953678 (3.1 TB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

tunint1: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 60.60.0.1  netmask 255.255.255.0  destination 60.60.0.1
        inet6 fe80::6bb4:1b6f:113c:786b  prefixlen 64  scopeid 0x20<link>
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen 500  (UNSPEC)
        RX packets 28  bytes 2352 (2.3 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 34  bytes 2640 (2.6 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

routes:
desktopuser@desktop:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.23.0.1       0.0.0.0         UG    100    0        0 enp6s0
10.23.0.0       0.0.0.0         255.255.0.0     U     100    0        0 enp6s0
60.60.0.0       0.0.0.0         255.255.255.0   U     0      0        0 tunint1
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 enp6s0
desktopuser@desktop:~$ ip route
default via 10.23.0.1 dev enp6s0 proto static metric 100
10.23.0.0/16 dev enp6s0 proto kernel scope link src 10.23.17.21 metric 100
60.60.0.0/24 dev tunint1 proto kernel scope link src 60.60.0.1
169.254.0.0/16 dev enp6s0 scope link metric 1000

iptables:
desktopuser@desktop:~$ sudo iptables -S
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
desktopuser@desktop:~$ sudo iptables -S -t nat
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT


text:
Q: how to print Statement (CallableStatement) in Java? How can I print this OracleCallableStatement ?
   ocstmt = (OracleCallableStatement) connection.prepareCall("{?= call
            package.method(id => ?, name=>?)}");
   ocstmt.registerOutParameter(1, OracleTypes.CURSOR);
   ocstmt.setInt(2, obj.getId());
   ocstmt.setString(3, obj.getName());
   ocstmt.execute();
   resultSet = ocstmt.getCursor(1);

What I mean is how can I know that what query goes to the database, how can I print the query? because sometimes it gives me error like "Wrong type" that is why I want to look at this query

A: Are you using log4j?
If so, add loggers for sql like below.
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG

If you are using a ORM framework such as ibatis, you could add additional logger like below.
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG

A: Yes, you can do this.  You can either wrap your callable statement in a proxy that can substitute the actual values when you print it (and show the sql), or hunt around for a driver that has a meaningful toString.  javaworld article There is also p6spy, and others.
Stored procedures are harder, but still doable.

A: You can't get the SQL by printing the Statement.
Is the example you posted one of the "sometimes" that triggers the error?
Why do you have to case this to an OracleCallableStatement?  What part of the call is not the standard CallableStatement?

A: In general, use myObject.toString() to see what it prints. You may or may not be able to see the full query though. If you can't get it to go, the first thing that I would look at is the API documentation(javadocs for that Oracle library or driver that you're using)

A: I'm not sure if I understand the question, but it seems like you want to see this:
  String sql = "{?= call package.method(id => ?, name=>?)}";
  System.out.println(sql);
  ocstmt = (OracleCallableStatement) connection.prepareCall(sql);
  ...

A: It's possible to use proxy jdbc driver to log all jdbc database actions.
this driver can prints all statements with values and all results.

A: My solution is use ProxyDataSourceBuilder(use it in Spring Boot project).
@Bean
public DataSource dataSource() {
    SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener();
    return ProxyDataSourceBuilder
            .create(datasource)
            .listener(loggingListener)
            .build();
}

...
@Autowired
private DataSource dataSource;

Connection connection = dataSource.getConnection();
ocstmt = (OracleCallableStatement) connection.prepareCall("{?= call
        package.method(id => ?, name=>?)}");

And just turn on logging in application.yml:
logging:
    level:
      net.ttddyy.dsproxy.listener.logging: debug

A: Try
 > java -classpath ojdbc8.jar oracle.jdbc.driver.OracleSql false false "<your sql here>"

That will print the SQL that the driver sends to the database, among other things. This is not documented nor supported, but it's been around forever.

A: I thought it might be useful if you are looking whether executed query has value or not
System.out.println("value : "+CallableStatement.execute());

i.e The "false" returned by "CallableStatement.execute()" means that the JDBC statement didn't read any rows, (so there's no ResultSet to read). This is what you'd expect, as stored procedures don't directly return ResultSets, they only return values for any OUT or INOUT parameters.


text:
Q: Split String to single variables between separators I am trying to find a more elegant / less memory intensive way to split a char array by separators.
The char array : "192.168.178\nWiFiSSID\nWiFiPassword\n123"
My idiot way of splitting:
void convertPayload()
{
qrData = (char*)mypayload;

String ssidtmp = qrData;
ssidtmp.remove(qrData.indexOf("\n"), qrData.length()+1);
EEPROM.writeString(ssidAddr,ssidtmp);
EEPROM.commit();

String passtmp = qrData;
passtmp.remove(0, passtmp.indexOf("\n")+1);
passtmp.remove(passtmp.indexOf("\n"),passtmp.length()+1);

EEPROM.writeString(passAddr, passtmp);
EEPROM.commit();

String modulenrtmp = qrData;
modulenrtmp.remove(0, modulenrtmp.indexOf("\n") + 1);
modulenrtmp.remove(0, modulenrtmp.indexOf("\n") + 1);
modulenrtmp.remove(modulenrtmp.indexOf("\n") , modulenrtmp.length());
int modNRINT = modulenrtmp.toInt();

EEPROM.write(moduleNraddress, modNRINT);
EEPROM.commit();

String ftptmp = qrData;
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(0, ftptmp.indexOf("\n") + 1);
ftptmp.remove(ftptmp.indexOf("\n") , ftptmp.length());

EEPROM.writeString(ftpAddr, ftptmp);
EEPROM.commit();

EEPROM.writeBool(configModeAddr, true);
EEPROM.commit();

//indicate QR succesfully read
blinkBurst(2, 300);

ESP.restart();
}

As you can see I'm creating unnecessary Strings. What would be the right way to do it?
Cheers and thanks for your time!

A: If you can edit mypayload you can use std::strtok
void convertPayload() {

String ssidtmp = std::strtok(mypayload, "\n");
EEPROM.writeString(ssidAddr,ssidtmp);
EEPROM.commit();

String passtmp = std::strtok(nullptr, "\n");
EEPROM.writeString(passAddr, passtmp);
EEPROM.commit();

String modulenrtmp = std::strtok(nullptr, "\n");
int modNRINT = modulenrtmp.toInt();
EEPROM.write(moduleNraddress, modNRINT);
EEPROM.commit();

String ftptmp =  = std::strtok(nullptr, "\n");
EEPROM.writeString(ftpAddr, ftptmp);
EEPROM.commit();

EEPROM.writeBool(configModeAddr, true);
EEPROM.commit();

//indicate QR succesfully read
blinkBurst(2, 300);

ESP.restart();
}


text:
Q: Booting multiple OSs from multiple disks with UEFI How does booting multiple OSs from multiple disks work in terms of UEFI? I have SSD0 on which Windows 7 is installed, and SSD1 on which I'd like to have Xubuntu and Arch Linux. I understand the process when one disk is involved, but have no idea when it comes to multiple disks.
Thank you.

A: There are really three issues:

*

*Boot loader location -- Boot loaders may be located on the primary disk's ESP, on the secondary disk's ESP, or on non-ESP partitions on either disk. Officially, the EFI spec allows the firmware to launch a boot loader from any ESP, but in practice non-ESP locations also often work if the partition in question uses FAT or if you've got a suitable driver installed. rEFIt, rEFInd, and GRUB 2 can redirect the boot process to boot loaders stored on other than the main ESP, although they need drivers to read non-FAT (or non-HFS+ on Mac) partitions. Some boot loaders, such as gummiboot, are limited to supporting the partition from which they launched, which could necessitate putting all your boot loaders on one ESP.

*OS installation location -- An ESP-resident boot loader must necessarily support launching an OS that's primarily resident on some other partition. In principle, there's no reason this partition can't reside on another physical disk entirely, and I don't know of any practical impediments to doing so. Thus, you can install a boot loader on the primary disk's ESP and have it boot your main OS from the secondary disk.

*Kernel location -- Linux boot loaders such as GRUB Legacy and GRUB 2 can load Linux kernels from locations other than the ESP, and in principle this other location can be a physically separate disk. In theory, ELILO can do the same, but I've never managed to get this to work. A kernel configured as an EFI stub loader must either be stored on an ESP or be loaded by an EFI that's less fussy about this or by a boot manager like rEFInd that can redirect to another partition or another disk. Thus, your kernel might need to be stored on the primary disk's ESP in some configurations. (Ubuntu uses GRUB 2 by default, so a standard Ubuntu installation is pretty flexible in this respect.)

In the end, there are few major limitations, at least in principle. You might run into some issues with buggy firmware implementations or if you use certain boot loader combinations, but you should be able to overcome these issues by proper placement of your boot loader and kernel files.

A: When using a boot manager such as rEFInd, it auto-detects all installed bootloaders across your disks, not just the disk where the rEFInd bootloader resides.


text:
Q: Push siblings out of view while keeping their width When hovering a flex element i now set the flex-basis to 100%. While doing this all siblings get resized to a width of 0 (i think) and this is showing in the animation.
Is it possible (preferred with just css) to let these sibling keep their width (nr of siblings is variable so in some scenarios there will be more columns then the example below) while the element that is hovered is expanding to 100% width? So that it looks as if they where pushed out of the container instead of resized to a width of 0.
Here is how it works now: https://jsfiddle.net/luffyyyyy/y8p9g2bs/8/
.container {
    width: 100vw;
    height: 60vh;
    display: flex;
    align-items: stretch;
    overflow: hidden;
}

.day-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    transition: flex-basis 1000ms ease-in-out;
}

.day-container:hover {
    flex-basis: 100%;
}

A: This is what could achieve so far. But for this to work you must know the number of sibling elements, in your case the .day-container. So, from your jsfiddle there are total of 5 .day-container elements so the 100/5 = 20% should be the flex-bases for .day-container elements.
now we will move all the .day-container elements before the hovered one to left by 20% when .container has hovered with the help of general sibling selector '~' . Here's the code:
.container:hover .day-container:not(:hover) {
  margin-left: -20%;
}

.container:hover .day-container:hover ~ .day-container {
  margin-left: 0;
}

finally, change transition to all for everything to move smoothly.
This is how the final code should look like:
body {
  margin: 0;
  padding: 0;
}

.container {
  width: 100vw;
  height: 60vh;
  display: flex;
  align-items: stretch;
  overflow: hidden;
}

.day-container {
  flex: 1 0 20%;
  display: flex;
  flex-direction: column;
  transition: all 1000ms ease-in-out;
}

.day-container:hover {
  flex-basis: 100%;
}

.item.small {
  flex: 1;
  background-color: royalblue;
}

.item.medium {
  flex: 2;
  background-color: rebeccapurple;
}
.item.big {
  flex: 3;
  background-color: goldenrod;
}

.container:hover .day-container:not(:hover) {
  margin-left: -20%;
}

.container:hover .day-container:hover ~ .day-container {
  margin-left: 0;
}

A: This is the farthest I've gotten, but I believe to get the centering right, you'll have to employ Javascript:
https://jsfiddle.net/xum8va4t/
it works by adding a second flexbox wrapper that grows on hover just like the day-container


text:
Q: How to write sequelize log to a file, instead of console? I want to write sequelize log to file instead of console. All sequelize logs are being written to console, which is default.
Thanks in advance.

A: This is the dirty way (use only in local environment):
import fs = require('fs');

const logStream = fs.createWriteStream('./sql.log', {'flags': 'a'});

const sequelize = new Sequelize('database', 'username', 'password', {
  logging: msg => logStream.write(msg),
});

A:

const sequelize = new Sequelize('sqlite::memory:', {
  // Choose one of the logging options
  logging: console.log,                  // Default, displays the first parameter of the log function call
  logging: (...msg) => console.log(msg), // Displays all log function call parameters
  logging: false,                        // Disables logging
  logging: msg => logger.debug(msg),     // Use custom logger (e.g. Winston or Bunyan), displays the first parameter
  logging: logger.debug.bind(logger)     // Alternative way to use custom logger, displays all messages
});

use any of one logger i used winston
logging:  msg => logger.log('info',msg)

this worked for me

A: Check out options.logging in the docs. The default value is
options.logging = console.log

which means all logging is passed to console.log(). So simply change logging to a function that append messages to a log / text file. Example
var sequelize = new Sequelize('database', 'username', 'password', {
  logging: myLogFunc
});

var myLogFunc = function(msg) {
}

winston is a good nodejs package for managing logs -> https://github.com/winstonjs/winston


text:
Q: AWK to compare columns in file1 to file2 I have a simple problem but have not been able to solve. I want to compare columns 2, 3, 4, 5 and 6 of File1 to the same columns of File2 and if they match then add Column1 of File2 to Column7 of File1.
I have tried awk NR == FNR-based solutions from previously posted similar issues but have not been able to adopt to get the corrrect output.
File1:
Column1 Column2 Column3 Column4 Column5 Column6
Genome1 1       1       2       1       2
Genome2 1       1       2       1       2
Genome3 1       2       2       1       2

File2:
Column1 Column2 Column3 Column4 Column5 Column6
Profile1 1       1       2       1       2
Profile2 1       2       2       1       2
Profile3 1       3       2       1       2

Expected results:
File1
Column1 Column2 Column3 Column4 Column5 Column6 Column7
Genome1 1       1       2       1       2       Profile1
Genome2 1       1       2       1       2       Profile1
Genome3 1       2       2       1       2       Profile2

Do you have suggestions?

A: You need hold all the columns you want to do match on the same columns on second file first then compare each for every line read from your first file:
awk 'NR==FNR {
    if(NR==1) $1="Column7"; file2[$2, $3, $4, $5, $6]=$1; next; };
    (($2, $3, $4, $5, $6) in file2){ print $0, file2[$2, $3, $4, $5, $6];
}' OFS='\t' file2 file1

Column1 Column2 Column3 Column4 Column5 Column6 Column7
Genome1 1       1       2       1       2       Profile1
Genome2 1       1       2       1       2       Profile1
Genome3 1       2       2       1       2       Profile2


text:
Q: Can't figure out "Thread 1: EXC_BAD_ACCESS" error while working with arrays I'm working on an algorithm that sorts inputted integers in ascending order.
The input should be of sort
5
32
45
32
55
67

and the output of sort
32
32
45
55
67

where the first integer input is the number of integers that will be inputted.
n.b. the integer inputted n is 1 <= n <= 10,000,000.
Here is my code:
#include <stdio.h>

int main() {
    int N;
    scanf("%d", &N); // receives the number of integers that will be inputted
    int countArray[10000000] = {0}; // creates an array that will store the number of times a number is inputted. the inputted number is the corresponding address e.g. countArray[number-1] stores the amount of times the number 'number' is inputted.

    int inputArray[N]; // creates an array of the numbers inputted
    for (int i=0; i<N; i++) {
        scanf("%d", &inputArray[i]); // receives the numbers inputted and stores them in the inputArray
    }
    for (int i=0;i<N;i++) {
        countArray[inputArray[i]-1]++; // counts the number of times a number occurs in inputArray and increments the corresponding value in the countArray.
    }
    int i=0;
    while (i<10000000) {
        if (countArray[i] > 0) {
            for (int j=0;j<countArray[i];j++) { // prints out the numbers only if count is greater than 0.
                printf("%d\n", i+1);
            }
        }
        i++;
    }
    return 0;
}

I know my code isn't the most efficient way to sort the inputs; I'm just curious as to why I get a "Thread 1: EXC_BAD_ACCESS" error when the size of the array is 10,000,000 but not when it is 1,000,000. It works just fine if the array is of size 1,000,000 but not when it is 10,000,000.

A: Your sample code does compile at least, but does not run. It seg-faults on start .
With GCC + Linux, and I get Segmentation fault (core dumped) and it exits with code 139 , while on my Mac with Clang, I get Segmentation fault: 11 with the same exit code. I suspect your EXEC_BAD_ACCESS is some version with the same basic issue underlying it.
As pointed out by @tevemadar , you are asking for ~ 40 MiB of data in your stack, which, very evidently, you are not going to get.
So, instead of this :
int countArray[10000000];
do this :
int *countArray = malloc(10000000*sizeof(int));
OR
static int countArray[10000000];
Which should work (don't forget to check for NULL ! ) , since malloc() will return a pointer to memory it allocated in the heap, and global variables are also put in the heap, where the size limits are not as restrictive as the stack, and for most practical purposes not important to keep in mind.

Now, onto some rambling of mine -
You are essentially going very much beyond the allowed stack size. I do not claim to be an expert, but by now this much is surely self-evident to you too.
Your attempt is somewhat of an abuse of the stack and perhaps arises from not being told the idea behind the stack's purpose - something most C textbooks and courses are guilty of :(
I am not an expert, and will not ruin the beauty of the concept for you, but to summarise -
The stack is for storing smaller, local variables of functions, like counters, strings to print, return values, etc. It's where everything, generally speaking, will go unless you malloc() , fopen() or static it. Its okay for small, handy variables which would be silly to malloc().
The heap is a huge region of memory , intended for bulk usage as in linked lists, long arrays, trees, big structs and what not. It's where you should store seriously-sized variables which store large amount of data.

So, TL;DR , use the heap for large datatypes, use the stack of small variables that would be silly to malloc().


text:
Q: NZEC in CRAZYSK spoj This is my code for the problem http://www.spoj.com/problems/CRAZYSK/ in python.
I am getting NZEC error.Is it due to the constraint X<=2^64 or something else?
n=raw_input()
for x in range(0,int(n)):
    raw_input()
    a,b=raw_input().split() #X,N
    print (int(a)-1)/(int(b)-1)+int(a)


text:
Q: How to import a class from a .py file which is in a subdirectory? I have a folder as follows:

The message.py file has a class Message that I would like to import and similarly segments.py file has a class Segment that I would like to import.
When I do:
from pydifact.message import Message
from pydifact.segments import Segment

I get the following error:
Traceback (most recent call last):

  File "<ipython-input-1-cc598c8ad3ca>", line 1, in <module>
    from pydifact.message import Message

ModuleNotFoundError: No module named 'pydifact.message'

But when I add:
import sys
sys.path.insert(0, r"C:\Users\Desktop\automatic-mscons-invoice-generator\edilite\pydifact")

from pydifact.message import Message
from pydifact.segments import Segment

it works fine.
Is there a way I can do the imports directly without having to add the sys.path.insert ?
My working directory is:
C:\Users\Desktop\automatic-mscons-invoice-generator

A: As you mentioned, adding to sys.path manually solved the problem.
Try adding that path to the PYTHONPATH environment variable, this tells the interpreter where are the scripts available for importing.


text:
Q: AttributeError: Module 'PyQt5' has no attribute '__version__' I was trying to warp a python file to an .exe file. But with these two lines, I encountered this problem.
import cv2
exit()

Traceback (most recent call last):
  File "d:\anaconda3\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "d:\anaconda3\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "D:\Anaconda3\Scripts\pyinstaller.exe\__main__.py", line 7, in <module>
  File "d:\anaconda3\lib\site-packages\PyInstaller\__main__.py", line 114, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "d:\anaconda3\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "d:\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 758, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "d:\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 705, in build
    exec(code, spec_namespace)
  File "D:\solar_cell\main.spec", line 7, in <module>
    a = Analysis(['main.py'],
  File "d:\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 254, in __init__
    self.__postinit__()
  File "d:\anaconda3\lib\site-packages\PyInstaller\building\datastruct.py", line 159, in __postinit__
    self.assemble()
  File "d:\anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 433, in assemble
    self.graph.process_post_graph_hooks(self)
  File "d:\anaconda3\lib\site-packages\PyInstaller\depend\analysis.py", line 373, in process_post_graph_hooks
    module_hook.post_graph(analysis)
  File "d:\anaconda3\lib\site-packages\PyInstaller\depend\imphook.py", line 451, in post_graph
    self._load_hook_module()
  File "d:\anaconda3\lib\site-packages\PyInstaller\depend\imphook.py", line 408, in _load_hook_module
    self._hook_module = importlib_load_source(
  File "d:\anaconda3\lib\site-packages\PyInstaller\compat.py", line 637, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 522, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 1027, in load_module
  File "<frozen importlib._bootstrap_external>", line 852, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 702, in _load
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 848, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "d:\anaconda3\lib\site-packages\PyInstaller\hooks\hook-PyQt5.py", line 14, in <module>
    from PyInstaller.utils.hooks.qt import pyqt5_library_info, get_qt_binaries
  File "d:\anaconda3\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 122, in <module>
    pyqt5_library_info = Qt5LibraryInfo('PyQt5')
  File "d:\anaconda3\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 50, in __init__
    if hooks.is_module_satisfies("PyQt5 >= 5.15.4"):
  File "d:\anaconda3\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 533, in is_module_satisfies
    version = get_module_attribute(module_name, version_attr)
  File "d:\anaconda3\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 329, in get_module_attribute
    raise AttributeError(
AttributeError: Module 'PyQt5' has no attribute '__version__'

If I just print something like: print('dsfdsfs'), then it can be wrapped to an .exe successfully.
My environment:
win10
pyinstaller     5.0.dev0
opencv-python   4.5.2.54
pyqt            5.9.2
And I was using anaconda prompt to do so.

A: Try using "pip install PyQt5" and then run again

A: I solved this problem by manually adding __version__ = "5.15.4" to venv/Lib/site-packages/PyQt5/__init__.py where venv is a virtual environment in which PyQt5 is installed.
Before:
...
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

# Support PyQt5 sub-packages that have been created by setuptools.
__path__ = __import__('pkgutil').extend_path(__path__, __name__)

def find_qt():
...

After:
...
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

# Support PyQt5 sub-packages that have been created by setuptools.
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
__version__ = "5.15.4"

def find_qt():
...

A: I'm using pyinstaller and anaconda prompt and found the same issue, to solve it you must
pip install PyQt5 --user --use-feature=2020-resolver
and then run pyinstaller again.

A: After loosing too many hours on this I updated PyInstaller and voilà it worked.

A: Unfortunately it seems that PyQt5 module on Anaconda is busted and missing various files that might be required by other modules, in my case PySimpleGui. The absolute easiest solution is to create a brand new environment, fortunately this is quite easy in anaconda, and pip install pyqt5. This should resolve any issues. Also install the rest of your packages and you should be good to go!

A: I'm seeing the same issue. pip install PyQt5 errored out... Pyinstaller team needs some serious help. Reverting back to previous version of Pyinstaller that works on my system.
Traceback (most recent call last):
  File "c:\progra~1\anacon~1\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\progra~1\anacon~1\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\PROGRA~1\Anaconda3\Scripts\pyinstaller.exe\__main__.py", line 9, in <module>
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\__main__.py", line 126, in run
    run_build(pyi_config, spec_file, **vars(args))
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build
    PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\building\build_main.py", line 815, in main
    build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build'))
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\building\build_main.py", line 762, in build
    exec(code, spec_namespace)
  File ".\tibcoAtlassian.spec", line 17, in <module>
    noarchive=False)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\building\build_main.py", line 294, in __init__
    self.__postinit__()
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\building\datastruct.py", line 159, in __postinit__
    self.assemble()
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\building\build_main.py", line 473, in assemble
    self.graph.process_post_graph_hooks(self)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\depend\analysis.py", line 373, in process_post_graph_hooks
    module_hook.post_graph(analysis)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\depend\imphook.py", line 451, in post_graph
    self._load_hook_module()
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\depend\imphook.py", line 409, in _load_hook_module
    self.hook_module_name, self.hook_filename)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\compat.py", line 632, in importlib_load_source
    return mod_loader.load_module()
  File "<frozen importlib._bootstrap_external>", line 407, in _check_name_wrapper
  File "<frozen importlib._bootstrap_external>", line 907, in load_module
  File "<frozen importlib._bootstrap_external>", line 732, in load_module
  File "<frozen importlib._bootstrap>", line 265, in _load_module_shim
  File "<frozen importlib._bootstrap>", line 696, in _load
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\hooks\hook-PyQt5.py", line 11, in <module>
    from PyInstaller.utils.hooks.qt import pyqt5_library_info, \
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 162, in <module>
    pyqt5_library_info = QtLibraryInfo('PyQt5')
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\utils\hooks\qt.py", line 54, in __init__
    if hooks.is_module_satisfies("PyQt5 >= 5.15.4"):
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 502, in is_module_satisfies
    version = get_module_attribute(module_name, version_attr)
  File "c:\progra~1\anacon~1\lib\site-packages\PyInstaller\utils\hooks\__init__.py", line 353, in get_module_attribute
    'Module %r has no attribute %r' % (module_name, attr_name))
AttributeError: Module 'PyQt5' has no attribute '__version__'

A: I figured out a fix. When you convert your .py file to .exe with auto-py-to-exe you have to click "advanced" then add "hidden-imports" there you add the things you import in your .py file, for example, my .py file imports "sounddevice" "numpy" and "os", so I add all of those into the "hidden-imports" in auto-py-to-exe" I hope this helped - here is a picture: example


text:
Q: How to run a Test synchronously which uses a shareIn Flow? Scenario
I am testing the emission of a StateFlow in myTest(). The test calls a function viewModel.initiateFlow() which kicks of a flow chain across 3 repositories and increments a buttons text.
Goal
I would like to have the test run sequentially, so that it runs the whole flow synchronously on the testDispatcher and waits for it to collected in ViewModel before continuing with runTest.
Issue
Currently the assertTextEquals is failing because the flow is ran asynchronously and does not have long enough to be collected and updated in MyViewModel().
Below is a diagram and corresponding code which best explains what is happening. FakeRepository2() is using shareIn() which I believe is causing the issue. The long-running code (simulated with delay) in onEach{} is being ran asynchronously on a separate default-dispacther. I am using GlobalScope() for this. I have tried passing in a testScope but in this case onEach{} is never ran. How can I fix this?

Code

@OptIn(ExperimentalCoroutinesApi::class)
@HiltAndroidTest
class MyTest {
    private val testScheduler = TestCoroutineScheduler()
    private val testDispatcher = StandardTestDispatcher(testScheduler)
    private val testScope = TestScope(testDispatcher)

    @get:Rule
    val hiltRule = HiltAndroidRule(this)

    @get:Rule
    val composeRule = createComposeRule()

    private lateinit var repository1: FakeRepository1
    private lateinit var repository2: FakeRepository2
    private lateinit var repository3: FakeRepository3
    private lateinit var viewModel: MyViewModel

    @Before
    fun setUp() {

        repository1 = FakeRepository1()
        repository2 = FakeRepository2(repository1, testScope)
        repository3 = FakeRepository3(repository2)

        viewModel = MyViewModel(repository1, repository3)

        composeRule.setContent {
            AppCompatTheme {
                MyComposableForTest(viewModel = viewModel)
            }
        }
    }

    @Test
    fun myTest() = testScope.runTest {

        composeRule.onRoot(useUnmergedTree = true).printToLog("MY_TAG")

        composeRule.onNodeWithContentDescription("Button One").assertIsDisplayed()

        //start the flow
        viewModel.initiateFlow()

        //assertion fails because Repository2 onEach{} block is taking long time to run and being ran asynchronously outside of test-Dispacther.
        composeRule.onNodeWithContentDescription("Button One")
            .assertTextEquals("1")

        //remaining test code

    }

}

class MyViewModel @Inject constructor(
    private val repository1: IRepository1,
    private val repository3: IRepository3
) : ViewModel() {

    private var _myInt = MutableStateFlow(0)
    val myInt = _myInt.asStateFlow()

    init {
        viewModelScope.launch{
            repository3.getFlow.collect{
                _myInt.value = it
                it.toString()
            }
        }
    }

    fun initiateFlow() = viewModelScope.launch {
        repository1.emitSharedFlow(_myInt.value)
    }

}

class FakeRepository1() : IRepository1 {

    override val _sharedFlow = MutableSharedFlow<Int>()
    override val sharedFlow = _sharedFlow.asSharedFlow()

    override suspend fun emitSharedFlow(myInt: Int) {
        _sharedFlow.emit(myInt)
    }
}

class FakeRepository2 @OptIn(ExperimentalCoroutinesApi::class) constructor(
    private val repository1: FakeRepository1,
    private val scope: TestScope
): IRepository2 {
    @OptIn(DelicateCoroutinesApi::class, ExperimentalCoroutinesApi::class)
    override val getFlow = repository1.sharedFlow
        .onEach {
            //doSomething
            delay(1000)
            delay(2000)
            delay(3000)
        }
        .shareIn(
            GlobalScope,
            SharingStarted.WhileSubscribed()
        )
}

class FakeRepository3(
    private val repository2: FakeRepository2
): IRepository3 {

    override val getFlow = repository2.getFlow
        .map {
            var increment = it
            increment += 1
            increment
        }
}

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    lateinit var viewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel =
            ViewModelProvider(
                this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.application)
            )[MyViewModel::class.java]
        setContent {
            MyComposableForTest(viewModel)
        }

    }
}

@Composable
fun MyComposableForTest(viewModel: MyViewModel) {

    val buttonOne by viewModel.myInt.collectAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .semantics {
                contentDescription = "Button Column"
            },
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {

        Button(
            modifier = Modifier
                .semantics {
                    contentDescription = "Button One"
                },
            onClick = { viewModel.initiateFlow() }
        ) {
            Text(
                text = buttonOne.toString(),
                modifier = Modifier
                    .semantics {
                        contentDescription = "Button One Text"
                    }
            )
        }
    }

}

A: To ensure FakeRepository2.onEach{} runs synchronously I used UnconfinedTestDispatcher() to launch coroutines on current (testing) thread immediately as per Testing Kotlin Flows with shareIn().


text:
Q: How to get the size of an image in Android? I'm able to get the height and width of an image. But is there a method to retrieve the size (in bytes or kb or mb) for an image stored in the phone?

A:  File file = new File("/sdcard/imageName.jpeg");
 long length = file.length();
 length = length/1024;
 System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");

A: Thank you for your answers. This is how I finally resolved it:
 Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
            R.drawable.ic_launcher);

     Bitmap bitmap = bitmapOrg;
     ByteArrayOutputStream stream = new ByteArrayOutputStream();
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
     byte[] imageInByte = stream.toByteArray();
     long lengthbmp = imageInByte.length;

Appreciate your time and answers :)

A: This returns the true size that is match in computers when you see file details with right click.
File file = new File("/sdcard/my_video.mp4");
long length = file.length() / 1024; // Size in KB

A: You just need to create a new File object such as...
String filepath = Environment.getExternalStorageDirectory() + "/file.png";
File file = new File(filepath);
long length = file.length();

A: Assuming your talking about a bitmap (and NOT an ImageView), there is a method Bitmap.getByteCount().


text:
Q: Compiling shared libraries into executable? I'm trying to cross compile some software I developed for my Nokia N900. It has an ARM7 processor, and is running Maemo (Based on Debian Etch and Lenny I believe).
To cross compile I am using Scratchbox, which has worked fine in the past for other software.
The software I developed uses libpcap. The latest version in the repo's is 0.8, but I need at least 1.0. So I compiled 1.0 within Scratchbox.
Within Scratchbox my softwarre compiles fine, but when I use the compiled binary on the N900 I get an error:
Error while loading shared libraries: libpcap.so.1 cannot open sharedobject file: No such file or directory.

Here is my Makefile:
TARGET = foncon
LIBS = -lpcap
CC = gcc
CFLAGS = -Wall -I include
OBJECTS = foncon.o src/pretty_print.o

$(TARGET):$(OBJECTS)
    $(CC) $(CFLAGS) $(OBJECTS) -o $(TARGET) $(LIBS)

%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@ $(LIBS)

clean:
    rm -f foncon.o
    rm -f src/pretty_print.o

Is it possible to build libpcap within the executable?


text:
Q: SQL Server 2008: Measure tps / select statements per second for a specific table? There is a discussion how to measure activity against an entire DB: https://stackoverflow.com/questions/5019593/sql-server-2008-transaction-per-second-for-specific-database
My question is narrower.
We are working on performance optimization of our application. To see how we are doing, we need to measure SELECT operations per second/minute/hour (prefer hour) on a specific table. (This way we can measure before and after implementing the optimization, to see how we are doing.)
What is the method or tool to do this?
Thank you!

A: OK, here is a cheap way, but it is not what I really want (I really want nice charts and graphs!):
-- First PASS
DECLARE @First BIGINT
DECLARE @Second BIGINT
SELECT @First = USER_SEEKS
FROM sys.dm_db_index_usage_stats
where object_id=14473333 AND index_id = 1

WAITFOR DELAY '00:00:15'

SELECT @Second = USER_SEEKS
FROM sys.dm_db_index_usage_stats
where object_id=14473333 AND index_id = 1
SELECT (@Second - @First) 'TableSeeks'
GO


text:
Q: UNNotificationServiceExtension - notifications stop presenting? Experimenting with new UNNotificationServiceExtension and notice interesting behaviour.
Start testing today in Xcode around 9:00 and notifications seems to flow. Content was modified and everything was fine.
In 13:30 all notifications just stop presenting for all of my apps(I'm  testing with more than one app from same team). I've send maybe 100 pushes for couple of hours (Normal behaviour when debugging, I will never do this at production,because of the limits of APNS.)
I'm testing on one device (iPhone 5S) and when testing on other device (iPhone 6) content was modified.
Also if remove "mutable-content" key notifications start showing up again
So is there a limitation for sending pushes, even if you we debug application?
Is anyone have similar issues?
Here is code of extension.It is almost same as template:
@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    self.bestAttemptContent.body = @"Modified content";
    self.contentHandler(self.bestAttemptContent);
}

- (void)serviceExtensionTimeWillExpire {
    self.contentHandler(self.bestAttemptContent);
}

And here is code of App delegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  [[UNUserNotificationCenter currentNotificationCenter]
   requestAuthorizationWithOptions:(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge)
   completionHandler:^(BOOL granted, NSError * _Nullable error) {
     if (granted) {
       [application registerForRemoteNotifications];
     }
   }];

  return YES;
}

-(void)applicationDidBecomeActive:(UIApplication *)application
{
  application.applicationIconBadgeNumber = 0;
}

-(void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSLog(@"Token %@",deviceToken);
}

-(void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  NSLog(@"Error %@",error);
}

It is very simple and dummy code with no additional calculations.
For a push sending I'm using javapns library like this:
HashMap<String, Object> finalContent = ...
JSONObject object = new JSONObject(finalContent);
PushNotificationBigPayload payload = PushNotificationBigPayload.fromJSON(object.toString());

List<PushedNotification> notifications = new ArrayList<PushedNotification>();
try {
    ArrayList<String> tokens = new ArrayList<String>();
    tokens.add("token ....");
    notifications = Push.payload(payload,
            "*.p12", "12345",
            false, tokens);
    for(PushedNotification notification : notifications){
        System.out.println(notification);
    }

} catch (CommunicationException e) {
    System.out.println(e);
} catch (KeystoreException e) {
    System.out.println(e);
}

EDIT: After device reboot, notfications modify content again.


text:
Q: How to check if Chrome extension has fully installed Using Chrome Web Store inline installation ( https://developers.google.com/chrome/web-store/docs/inline_installation ) it is possible to specify a callback for chrome.webstore.install() that will be executed when the extension is successfully installed.
Through some very tedious debugging I've learned that extensions are not neccessarily 100% installed when the callback is executed - maybe the background hasn't been loaded or content scripts aren't yet available.
In my particular case the problem presents itself in this way:

*

*User clicks install button with chrome.webstore.install() bound to onclick event.

*Success callback injects an iFrame.

*Content script is defined for the iFrame and injected to do some finishing work

*Content script returns with a completed installation dialog.

Step 3 is the problem. Some times the iFrame will be injected before content script is fully loaded and thus no script will be injected (content scripts are only injected inside newly created iFrames, not iFrames already existing when the extension is installed/enabled).
I know there are possible workarounds such as having the extension itself inject the iFrame or a simple setTimeout(), but for the sake of helping others I think it's worth asking the question:
How can I be certain that the extension is 100% installed, when the chrome.webstore.install() callback doesn't ensure it?
Using the famous <img> load method described in Checking if user has a certain extension installed doesn't work reliably (for those thinking that'd be a solution).

A: This is the way to do it :
http://code.google.com/chrome/extensions/extension.html#global-events
As mentioned in the last link below , you should be able to do :
var myPort=chrome.extension.connect('yourextensionid_qwerqweroijwefoijwef', some_object_to_send_on_connect);

You can also check Checking if an item is already installed section in the next link :
https://developers.google.com/chrome/web-store/docs/inline_installation
or you can follow what have been done in this post:
Check whether user has a Chrome extension installed
I also saw solutions talking about background page and localstorage:
http://developer.chrome.com/extensions/background_pages.html
Chrome extension post-install hook/API function: does it exist?

A: You sure your content script's work needs to be done from the same page where the user installed the extension? If not, simply have your extension call chrome.tabs.update or chrome.tabs.create (two of the few tabs methods that don't require the tabs permission) to open a page where your content script can be injected.
Otherwise, your extension can use programmatic injection to inject a content script which can  communicate with your page. You can use chrome.tabs.query to make sure you're injecting into the correct tab.


text:
Q: Deploying from local to dev: pages do not work So I have deployed a WP that was local to a dev environment. I have done the following:

*

*Deployed files via FTP

*Imported DB via PHPMyAdmin

*Modified home and siteurl values in the _options table

So far, the landing page works fine, however as soon as I try to change page, it doesn't work.
It may be interesting to say that I have deployed onto a URL like http://dev.example.com/project-name/. I cannot put it at the root, this dev servers is used to present multiple projects.
I am not at ease with databases, deployments or htaccess things, so if you must explain with these things, please be gentle with me. Any help is appreciated.

A: *

*Log into wp admin

*Open Settings -> Permanent links

*Check if site links works?

*if NO check permitions to .htaccess in root
folder. it shoudl be writable. and back to step 2.

A: You shouldn't import WordPress data via PHPMyAdmin. You should use the built-in WordPress importer/exporter, this way you will ensure that all permalinks are properly translated to your site's name. As Oleg suggested, try visiting permalink settings, this will flush the permalinks.


text:
Q: Rpraph is not showing in canvas <canvas id = "myCanvas" height = "385%" width = "100%">

</canvas>

Error: Uncaught TypeError: Cannot read property 'getContext' of null
      at new RGraph.Bar (file:///F:/New%20folder%20(2)/website/RGraph.bar.js:46:51)
      at file:///F:/New%20folder%20(2)/website/online_booking.html:149:14

A: There were a few problems with your configuration most notable of which was that the JavaScript code does not go between the canvas tags. The updated code is thus:

<canvas id="myCanvas" height="385" width="900"></canvas>

And, maybe, because of the style of configuration that you're using, I'm guessing that you may be using an older version of RGraph - and if you are you should download the latest copy here:
https://www.rgraph.net/download.html#stable


text:
Q: What is the difference between `Rational` and `BigNum` implementations There are a lot of such types for many languages. As far as I know, here is how it works.
Rational just stores two separate digits for numerator and denominator (like 3 and 10 for 0.3).
BigNum stores each digit of the number in some kind of an "array" and do the column-arithmetic as humans usually do. For example, 0.1 stores like [0, '.', 1]. If we would like to add 0.2 to it, it will result in something like this:
  [0, '.', 1]
+ [0, '.', 2]
= [0, '.', 3]

Am I right? Is there any other popular arbitrary-precision arithmetic? If so, how is it called?
I'm not talking about any specific implementation, but rather the general idea of what it usually does.

A: There are a couple of different approaches in wide use:

*

*Arbitrary-precision integers are typically stored as an array of integers. Examples are long integers in Python, BigInteger in Java, or mpz in the GMP library (and languages such as Julia and Mathematica which use GMP).

*Arbitrary-precision floats are stored as an arbitrary-precision integer and an exponent. This is available as either:

*

*base-2 (e.g. mpf in GMP, MPFR and languages which uses these libraries): tend to be favoured in technical and numerical areas as they act exactly like normal floating point numbers but with extra precision (so can be used to verify methods or calculations).

*base-10 (e.g. BigDecimal in Java, decimal in Python.) Tend to be favoured for financial applications (as there are fewer worries about round-off for currencies), and people who can't get their head around the fact that 0.1 + 0.2 != 0.3 (based on the frequency with which these are unnecessarily advocated on StackOverflow).

*Rationals (e.g. mpq in GMP, fractions in Python) stores a number as a ratio of (usually) arbitrary-precision integers. These are nice as the results for elementary arithmetic operations (+, -, *, /) are always exact, even for things like x/3. The downside is that they don't work for non-rational functions (such as sqrt or sin), and can quickly blow up if not used carefully (e.g. if used in an iterative algorithm such as Newton's method).

*Double-double arithmetic stores the number as a pair of floating point numbers (typically C doubles, hence the name). The idea is that the second element of the pair is less than the unit in last place of the first, so you have effectively doubled the available precision. These ideas go back to a paper by Dekker (1971), and can be extended to triple-double and quad-double. The advantage is that they can exploit existing floating point hardware, so can be much faster than arbitrary precision floats, however the downside is that the exponent range is still the same as the underlying floating point format (and the precision is still fixed, so not really "arbitrary"). I'm not sure which libraries are in common use, but David Bailey has a good summary of his software.


text:
Q: System.Drawing Parameter is not valid I'm currently using AForge dll to render the video on the picture box for the live view. I do have a video frame function to whether WriteFrame or Screenshot the current picturebox frame as a JPG.
But i met a problem when sometime the program will prompt out an error of Parameter is not valid or Object is been used elsewhere. I did try to find solution to solve it and i pretty sure i did dispose on the image and the clone image, but the problem still exist.
Could you assist me on what i had done wrong with my program?
void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            //your code using bmp object
            if (D1Pic.BackColor == Color.Green)
            {
                video = (Bitmap)eventArgs.Frame.Clone();
                if (livePreview.Image != null)
                {
                    //Dispose the resources
                    this.Invoke(new MethodInvoker(delegate() { livePreview.Image.Dispose(); }));
                }
                livePreview.Image = (Bitmap)eventArgs.Frame.Clone();
                imgclone = (Image)livePreview.Image.Clone();
                FileWriter.WriteVideoFrame(video);
            }
            else
            {
                video = (Bitmap)eventArgs.Frame.Clone();
                if (livePreview.Image != null)
                {
                    //Dispose the resources
                    this.Invoke(new MethodInvoker(delegate() { livePreview.Image.Dispose(); }));
                    this.Invoke(new MethodInvoker(delegate() { video.Dispose(); }));
                }
                livePreview.Image = (Bitmap)eventArgs.Frame.Clone();
                imgclone = (Image)livePreview.Image.Clone();
            }
            video.Dispose();
            livePreview.Refresh();

Here are the stack trace error :
{"Parameter is not valid."}
   at System.Drawing.Image.get_Width()
   at System.Windows.Forms.PictureBox.ImageRectangleFromSizeMode(PictureBoxSizeMode mode)
   at System.Windows.Forms.PictureBox.OnPaint(PaintEventArgs pe)
   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer)
   at System.Windows.Forms.Control.WmPaint(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

UPDATED CODE :
 var newFrame = (Bitmap)eventArgs.Frame.Clone();
                this.Invoke(new MethodInvoker(delegate()
                {
                    if (livePreview.Image != null)
                    {
                        livePreview.Image.Dispose();
                    }
                    livePreview.Image = newFrame;
                }));
                imgclone = (Bitmap)eventArgs.Frame.Clone();

                //Write frame into video
                if (D1Pic.BackColor == Color.Green)
                {
                    video = (Bitmap)eventArgs.Frame.Clone();
                    FileWriter.WriteVideoFrame(video);
                }

A: You are calling livePreview.Image.Dispose() in the UI thread, but you're not setting livePreview.Image to null afterwards.
So between the time that you dispose livePreview.Image and the time that you assign a new image to it, livePreview.Image points to a disposed object.
So I think occasionally your picturebox tries to draw itself during this time, and fails when it attempts to access its (disposed) Image property.
The solution would be:
if (livePreview.Image != null)
{
    //Dispose the resources
    this.Invoke(new MethodInvoker(delegate() {
        livePreview.Image.Dispose();
        livePreview.Image = null;
    }));
}

Or even better, assign the new image in the same step:
var newFrame = (Bitmap)eventArgs.Frame.Clone();
this.Invoke(new MethodInvoker(delegate() {
    if (livePreview.Image != null)
    {
        livePreview.Image.Dispose();
    }
    livePreview.Image = newFrame;
}));

In general, you need to understand what's happening with your various Bitmap objects. Anything that keeps a reference to a Bitmap that has been disposed will be a problem.


text:
Q: Depth First Search Perform Depth-first Search on the graph shown starting with vertex a. When you traverse the neighbours, process them in alphabetical order.
The question is to find the DFI, Level and the Parent of each vertex.
Here is a picture of it:

I'm unsure of how to get going with this, it is a practice question for an upcoming exam. I know for depth first search, it uses a stack and it will start at vertex a and go in alphabetical order in the stack but i'm not sure how I would get the values for each of the columns. Can someone explain further or help me with this?

A: So you start at 'a' and must traverse the nodes in alphabetical order so from a you either have the option of going to b or g so you choose b because it is first alphabetically. from b your only choice is g and so on....
now for your values. the parent of a is null since you have no previous nodes the parent of b is a and the parent of g is b and so on.
the dfs level is the level that it would end up on a tree. so imagine that you do your traversal then erase all lines that weren't part of the traversal. and then you take your root and 'shake it out' what i mean is you rearrange it so that it looks like a tree. (this particular graph is very uninteresting) and then you assign levels based on that tree.
And the dfs index is simply the order in which you touched the nodes.
The folowing are for your graph but using g as a starting point....I think it makes it slightly more intersting

the numbers are the order in which the edges were taken.

Here is what i was talking about when i said 'shake it out' this is what your tree looks like and in blue i show the level of each node(0 based). I hope the images make it a little more understandable.

the one i drew( the terrible free hand one) was formed by deleting all of the edges that weren't used and then rearranging them to look like a tree.
You can think of the depth as how many steps did i have to take from the root to get to the current node. so from g to b is 1 step so depth of 1 from g to i 3 because we go from g->c->d->i 3 steps. after you have made your traversal you ignore the fact that you can in fact get from g to i in two steps(g->h->i) because it wasnt part of the traversal

A: The index is simply the number in order that the node is visited. a is first, write 1 there. Knowing depth first search as you do, you should know what the second node is; so write 2 under that. Depth is how high a node is; every time you deepen the depth, it increases, and whenever you go shallower, it's less. So a is on depth 1; the next node and its sister will be on depth 2, etc. The parent is the letter identifying the node that you just came from; so a has no parent, and the node with index 2 will have a as parent.
If your class uses a zero-based numbering system, replace 2 in the above paragraph with 1, and 1 with 0. If you have no idea what "zero-based numbering system" is, ignore this paragraph.


text:
Q: Validate only one spring annotation on form field and independently from others field i have a specific requirement even if it seems to be pretty straightforward.
I have a form for a user (give you a simplify version of it).
public class Form{
  @NotEmpty(message = "{empty}")
  @Size(min = 3, max = 32, message = "{size}")
  private String firstName;
  @NotEmpty(message = "{empty}")
  @Size(min = 3, max = 32, message = "{size}")
  private String lastName;
}

I want both field to be validate independently, fail at first error (only display one error message then).
For exemple, if i send firstName="" and lastName="aa", i want to get empty message for firstName and size message for lastName.
But by doing that i get 2 error messages for firstName (size and empty).
First alternative i found is using a @groupsequences but still cannot validate field independently.
So i created a new annotation :
@Documented
@Constraint(validatedBy = {})
@Retention(RetentionPolicy.RUNTIME)
@NotEmpty(message = "{empty}", groups = Check.firstTry.class)
@Size(min = 5, max = 32, message = "{size}", groups = Check.secondTry.class)
@GroupSequence({ Check.firstTry.class, Check.secondTry.class, Name.class })
public @interface Name {
    public abstract String message() default "{empty}";

    public abstract Class<?>[] groups() default {};

    public abstract Class<?>[] payload() default {};
}

But it still validating every messages.
If i use @ReportAsSingleViolation it will always return the default message.
Did i miss something somewhere, form validation should be pretty easy for this case, it's not a weird case, is it ?
Thank You

A: Write a custom ConstraintValidator that checks the constraints one-by-one and reports the first one it finds. The (rather large) downside of this is that you end up reimplementing the checking mechanism for each component annotation, but you do get total control over the error messages.
public class MyConstraintValidator implements ConstraintValidator<Name, String> {

    private Name annotation;

    @Override
    public void initialize(MyConstraintAnnotation annotation) {
        this.annotation = annotation;
    }

    @Override
    public boolean isValid(String name, ConstraintValidatorContext context) {
        if (name == null) {
            context.buildConstraintViolationWithTemplate(emptyMessage).addConstraintViolation();
            return false;
        } else if (name.length() < getMinSize(annotation)) {
            context.buildConstraintViolationWithTemplate(tooShortMessage).addConstraintViolation();
            return false;
        } else if (name.length > getMaxSize(annotation)) {
            context.buildConstraintViolationWithTemplate(tooLongMessage).addConstraintViolation();
            return false;
        } else {
            return true;
        }
    }
}

Maybe if you could get a handle on the ConstraintValidatorFactory and get the ConstraintValidators you need for each composing annotation? Although that exposes you to the internals of the implementation. It's not a perfect answer at all, but it would get what you need.


text:
Q: Is there any pragmatic implication in 'Beaky has enjoyed London' here? It says on a grammar book that in some cases, the present perfect form has pragmatic meanings.

Joan has broken the teapot. (I have to get a new one.)
I've had a bath. (I'm now clean.)

Is there such implication in the following "Beaky has enjoyed London."? Or is Hagrid merely reporting the fact?
(A letter from Hagrid (in London) to Hermione (at Hogwarts) just after losing a case)

Dear Hermione,
We lost. I'm allowed to bring him back to Hogwarts.
Execution date to be fixed.
Beaky has enjoyed London.
I won't forget all the help you gave us.
Hagrid. (Harry Potter 3 [US Version]: p.291)

N.B.: Beaky is Hagrid's pet, a treasure to Hagrid, which was judged dangerous and received a death sentence. In the book, there're several teardrops smudging the letter.

A: Is there any pragmatic implication? Well, I wouldn't say so. Why? Because, if there were pragmatic implications, what would one do as a result of knowing that Beaky enjoyed London? Would we eat dinner? Would we sing and be happy?
Obviously not. This sentence, is different from the previous examples that you gave, in which there is an implication for another action to be performed (or that has been performed), for example "Joan has broken the teapot" implies that a replacement needs to be found. However, this is not the case with "Beaky has enjoyed London".
It's like making a statement "I have enjoyed my meal". No necessary action needs to take place after this statement (Unless, to burp)

A: The implication is just that what happens when someone enjoys something.
You would need some insight in how Beaky would react to enjoying a city, but there would probably just be an improvement in the mood:

Beaky has enjoyed London. (Beaky is now happy.)

There is of course also a deeper meaning that you can draw from the fact that Hagrid is mentioning Beaky at all, which would indicate the importance of Beaky to Hagrid.

A: I don't think there can be any pragmatic meaning. There is no direct result of Beaky liking the city of London (like being clean after taking a bath or being in need to buy new cup after someone broke the old one). Hagrid is simply stating the fact, nothing more, nothing less.


text:
Q: Maximum function nesting level in Yii I know there are duplicates to this question, tried all of them, none of them worked. At last I commented out the zend_extension in php.ini, Now the browser keeps on processing endlessly.
What I have
I'm a calling a simple widget from my view
 echo \sintret\chat\ChatRoom::widget([
      'url' => \yii\helpers\Url::to(['/site/send-chat']),
      'userModel'=>  \common\models\User::className(),
      'userField' => 'avatarImage'
    ]);

In my Controller:
public function actionSendChat() {
    if (!empty($_POST)) {
        echo \sintret\chat\ChatRoom::sendChat($_POST);
    }
}

Here is the Github link to ChatRoom.php which contains the main widget, it has only two main functions init() and run(). another is sendChat which we are calling in our controller.
Any thoughts to resolve the error are welcome.


text:
Q: Can users add records to the front-end of a split database in MS Access 2013? My company is looking to split our staff database to ensure constant access and readability for all departments who require it. We performed some research and found out splitting the database and potentially making it an executable (for the front-end) would be the best idea.
However, the snag in the line that we reached is that we have certain forms in our Access database that require users to add in new records (vendor receipts, training records, etc.). Is it possible for the front-end user to add a new record using their part of the split database, or is that only something internal staff can do?
Also, if this is possible, would any extra action be required on the internal systems staff's part to replicate/update the data to our back end?

A: The backend is what is accessed by all users via the frontend(s).
Thus, reading and writing data will go to the backend for any user. That's the idea of having a shared backend.


text:
Q: Performance of two meteor apps on one database I've created simple todo app from meteor.com website. Let's call it 'project A'.
Then duplicated directory with project. Let's call it 'project B'.
I've started project A normally.
After that I've started project B on port 3456 and connect to project's A database through env variables.
The problem is:

*

*when I add todo in project B, changes appears immidietly in project A.

*When I add todo in project A, in project B changes appears after few seconds.
Question is: Why?
There are two equally the same projects connected to the same database...

A: Because oplog tailing is disabled.
When there's no oplog tailing, Meteor uses "poll-and-diff" strategy that execute mongodb queries every 10 seconds and then do a diff to see if some data changed.
To solve it, you can activate oplog tailing this way: https://github.com/meteor/meteor/wiki/Oplog-Observe-Driver#oplogobservedriver-in-production


text:
Q: Conditionally load script depending on current admin page I am using load to enqueue scripts only on my plugin page.
https://developer.wordpress.org/reference/hooks/load-page_hook/
add_action("admin_menu", "sap_admin_menu");
function sap_admin_menu(){

    $menu = add_menu_page("Sticky Audio Player Player manager", "Sticky Audio Player", "manage_options", "sap_player_manager", "sap_player_manager_page", 'dashicons-playlist-audio');

    $submenu = add_submenu_page("sap_player_manager", "Sticky Audio Player Player manager", "Player manager", "manage_options", 'sap_player_manager', "sap_player_manager_page");
    $submenu2 = add_submenu_page("sap_player_manager", "Sticky Audio Player Playlist manager", "Playlist manager", "manage_options", 'sap_playlist_manager', 'sap_playlist_manager_page');

    add_action( 'load-' . $menu, 'sap_admin_enqueue_scripts' );
    add_action( 'load-' . $submenu, 'sap_admin_enqueue_scripts' );
    add_action( 'load-' . $submenu2, 'sap_admin_enqueue_scripts' );

}

This works well, however I would like to know how to detect on which page I am currently so  I can enqueue different scripts in sap_admin_enqueue_scripts function:
function sap_admin_enqueue_scripts() {

    //I need to detect page here

    if ( is_page( 'sap_player_manager' ) ) {//this doesnt work

    }

I tried using is_page but I cant make it work.

A: You can do something like this
add_action( 'admin_menu', 'my_admin_menus' );

function my_admin_menus() {
   $GLOBALS['my_page'] = add_menu_page( 'Page Title', 'Menu Title',
   MY_ADMIN_CAPABILITY, 'menu-slug', 'show_page_content');
}

add_action( 'admin_enqueue_scripts', 'enqueue_admin_js');

function enqueue_admin_js($hook) {
  if($GLOBALS['my_page'] === $hook) {
    wp_enqueue_script( 'jquery-ui-core' );
    wp_enqueue_script( 'jquery-ui-tabs' );
    // Isn't it nice to use dependencies and the already registered core js files?
    wp_enqueue_script( 'my-script', INCLUDES_URI . '/js/my_script.js', array( 'jquery-ui-core', 'jquery-ui-tabs' ) );
  }
}

A: What about get_current_screen()?
$screen = get_current_screen();

if ( 'sap_player_manager' === $screen->id ) {

}

A: look into  get_current_screen();
Some notes from codex:

This function is defined on most admin pages, but not all. Thus there are cases where is_admin() will return true, but attempting to call get_current_screen() will result in a fatal error because it is not defined. One known example is wp-admin/customize.php.

There is also a current_screen hook for a different approach.
Both make available a WP_Screen. in example:
WP_Screen Object {
    ["action"] => string(0) ""
    ["base"] => string(4) "post"
    ["columns":"WP_Screen":private] => int(0)
    ["id"] => string(12) "someposttype"
    ["in_admin":protected] => string(4) "site"
    ["is_network"] => bool(false)
    ["is_user"] => bool(false)
    ["parent_base"] => NULL
    ["parent_file"] => NULL
    ["post_type"] => string(12) "someposttype"
    ["taxonomy"] => string(0) ""
    ["_help_tabs":"WP_Screen":private] => array(0) { }
    ["_help_sidebar":"WP_Screen":private] => string(0) ""
    ["_options":"WP_Screen":private] => array(0) { }
    ["_show_screen_options":"WP_Screen":private] => NULL
    ["_screen_settings":"WP_Screen":private] => NULL
}


text:
Q: GridSearchCV not fetching mean_test_score in colab I ran randomForestClassifier using GridSearchCV in colab.
However, myGridSearchCV does not return mean_test_score and shows it does not exists.
When I tried to check clf.cvresults there is not mean_test_score.This works in Jupyter notebook not in Colab and I recently faced this issue.
[Parallel(n_jobs=1)]: Done 120 out of 120 | elapsed: 25.3min finished
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-128-1d8f6c95affb> in <module>()
      7 clf.fit(X_tr, y_train)
      8
----> 9 train_auc= clf.cv_results_['mean_train_score']
     10 cv_auc = clf.cv_results_['mean_test_score']

KeyError: 'mean_train_score'

A: Actually you are getting mean_train_score key error. Just set return_train_score=True in gridsearchcv parameters and it will do the job.

A: It may be worth noting that, you may still get the error with mean_train_score even if you have set return_train_score=True in the grid search, if you are using multiple scorers. Here is the reason. if you are running GridSearchCV with multiple scorers (e.g. you pass a parameter to the grid search such as in scoring= {'Accuracy': 'accuracy', 'F1': 'f1_macro', 'AUC': 'roc_auc'}) then you can expect that the mean_train_score variable name will depend on what you have set the refit to. For example, if you have set refit='AUC' then the appropriate variable name will then be mean_train_AUC, and others accordingly. These are very subtle changes that are documented in scikit-learn but can be painful to detect and deal with.

A:
mean_train_score is missing you can cross verify this using
scores = rf.cv_results_

pd.DataFrame(scores).head()

rf is your gridsearchcv
you will be getting error something like below
KeyError: 'mean_train_score'
solution
 set return_train_score=True in gridsearchcv
rf = GridSearchCV(rf, parameters, cv=n_folds,
   scoring="accuracy",return_train_score=True)


text:
Q: BAD URI when uploading S3 with carrierwave I'm getting the following error when trying to upload an image with S3 and carrierwave, and can't solve it.
URI::InvalidURIError (bad URI(is not URI?): ://s3.amazonaws.com:):
      app/controllers/shops_controller.rb:38:in `block in update'
    app/controllers/shops_controller.rb:37:in `update'

In my shops controller (Lines 35 to 46 ):
    def update
      @shop = Shop.find(params[:id])
    respond_to do |format|
      if @shop.update(shop_params)
        format.html { redirect_to "/sushiadmin", notice: 'Se ha editado el plato.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @shop.errors, status: :unprocessable_entity }
      end
    end
  end

My S3 configuration (Production.rb)
  CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
    aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    region: 'eu-west-1',
    :endpoint => 's3-eu-west-1.amazonaws.com'
  }

    config.fog_directory  = ENV['AWS_S3_BUCKET']
  end

////////////////EDIT
PARAMS- LOGS
2015-06-05T12:22:19.273490+00:00 app[web.1]: Started PATCH "/shops/1" for 80.30.158.93 at 2015-06-05 12:22:19 +0000
2015-06-05T12:22:19.277373+00:00 app[web.1]: Processing by ShopsController#update as HTML
2015-06-05T12:22:19.277485+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"t5UqatONHUmLhrGzMvj8HXHgcu2KLSGe8cLoEN3rgJs=", "shop"=>{"name"=>"C.C.Itaroa", "city"=>"", "direction"=>"Calle Intxaurdia 5, 31620, Huarte", "cover"=>#<ActionDispatch::Http::UploadedFile:0x007f26188839d0 @tempfile=#<Tempfile:/tmp/RackMultipart20150605-3-zm7xcj>, @original_filename="45.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"shop[cover]\"; filename=\"45.png\"\r\nContent-Type: image/png\r\n">, "printer_url"=>"192.168.1.1", "latitude"=>"", "longitude"=>"", "email"=>"navarra@mysite.es", "pc"=>"31016,31486,31600,31610,31620,31621,31699"}, "commit"=>"Editar", "id"=>"1"}
2015-06-05T12:22:20.004896+00:00 app[web.1]: Completed 500 Internal Server Error in 727ms
2015-06-05T12:22:20.007724+00:00 app[web.1]:
2015-06-05T12:22:20.007729+00:00 app[web.1]:   app/controllers/shops_controller.rb:38:in `block in update'
2015-06-05T12:22:20.007731+00:00 app[web.1]:
2015-06-05T12:22:20.007727+00:00 app[web.1]: URI::InvalidURIError (bad URI(is not URI?): ://s3.amazonaws.com:):
2015-06-05T12:22:20.007730+00:00 app[web.1]:   app/controllers/shops_controller.rb:37:in `update'
2015-06-05T12:22:20.007733+00:00 app[web.1]:
2015-06-05T12:22:20.011815+00:00 heroku[router]: at=info method=POST path="/shops/1" host=mysite-staging.herokuapp.com request_id=9e23541f-96d2-430c-95a7-5e77dbc2f69c fwd="80.30.158.93" dyno=web.1 connect=3ms service=20983ms status=500 bytes=1543