text:
Q: @tailrec optimisation and @Advice.OnMethodEnter behaviour I want to instrument a Scala method that is annotated with @tailrec. This causes the compiler to optimize the recursive method to a loop as long as it is tail recursive.
For example:
  @tailrec
  private def tailRecFunction(i: Int): Unit = {
    if (i > 0) {
      println(s"$i on Thread ${Thread.currentThread().getId}")
      Thread.sleep(20)
      tailRecFunction(i - 1)
    } else {
      println(s"0 on Thread ${Thread.currentThread().getId}")
      Thread.sleep(20)
      ()
    }
  }

And I have the method adviced as follows:
        @Override
        public ElementMatcher<? super MethodDescription> getMethodMatcher() {
            return named("tailRecFunction");
        }

        @Advice.OnMethodEnter(suppress = Throwable.class, inline = false)
        public static void onEnter() {
            logger.info("onMethodEnter");
        }

        @Advice.OnMethodExit(suppress = Throwable.class, inline = false)
        public static void onExit() {
            logger.info("onMethodExit");
        }

This causes the following log-output for tailRecFunction(10):
2021-08-01 22:28:03,364 [main] INFO onMethodEnter
10 on Thread 1
9 on Thread 1
8 on Thread 1
7 on Thread 1
6 on Thread 1
5 on Thread 1
4 on Thread 1
3 on Thread 1
2 on Thread 1
1 on Thread 1
0 on Thread 1
2021-08-01 22:28:03,633 [main] INFO onMethodExit

Would there be any way on how I could instrument this method and actually get the onMethodEnter and onMethodExit call on every method call instead of one enter and exit?

A: Because tail call elimination means, at the bytecode level,  that there's only one entry and exit (in terms of execution) of the method, for a tool like Byte Buddy which works at the level of the byte code can only ever see one entry/exit.
Note that Byte Buddy is designed for Java: it only really understands bytecode which would be similar to what a Java compiler would emit.  If Byte Buddy can instrument loop entry and exit, it might be able to work with a tail recursive method in Scala.
As far as I know, there's no annotation or compiler option to disable tail call elimination in Scala, so this couldn't be accomplished with Byte Buddy.  Assuming that you're trying to augment code which you own, it might be possible to instrument every iteration via a macro.


text:
Q: Deleting multiplie resources by mask using WEB DAV Is there any way to delete multiplie resources by mask with web dav protocol out of a box?
For example send some header with condition like regex, for example
'^some.*' - delete all resources starting with 'some'
Maybe somebody had thinking about that?

A: No, there is no part of the webdav or http11 standards for that. A DELETE is always issued to a single resource identified by the URL

redpajama_set_name: RedPajamaStackExchange


text:
Q: High load average with NO CPU usage I have a webserver running on a VM and often we have high server load whose root cause has not yet found.
I have sofar tried to dig out some Disk activity, memory usage, swap usage and CPU usage during the incident
So far i have found the following.
High pgscand/s, pgsteal/s    %vmeff noticed during the load.
%vmeff is 100 %
03:00:01 PM      1.06     65.63    662.44      0.00   1790.95      0.00      0.00      0.00      0.00
03:10:01 PM      4.39     56.46   1744.16      0.00   2370.19      0.00    221.60    221.60    100.00
The server runs on Redhat 7.5. Webserver is Apache and there are no outside hits to the webserver to cause any load. There are also no cronjobs running.
I would like to know the root cause of the issue


text:
Q: using supervisord to run lsyncd script I'm trying to run my lsynd's script with supervisord in order to have it always run.
I've coded this conf for my supervisor
[program:autostart_lsyncd]
command=bash -c "lsyncd /home/sync/lsyncd_script.lua"
autostart=true
autorestart=unexpected
numprocs=1
startsecs = 0
stderr_logfile=/var/log/autostart_sync.err.log
stdout_logfile=/var/log/autostart_sync.out.log

Script runs ok at startup but it exits always
2018-04-09 09:48:49,638 INFO success: autostart_lsyncd entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
2018-04-09 09:48:49,639 INFO exited: autostart_lsyncd (exit status 0; expected)

I can't understand if this is the correct way to keep alive a lsynd script or not.
Suggestions?

A: I'm using this configuration to supervisord in file /etc/supervisor/conf.d/lsyncd.conf
[program:lsyncd]
command=/usr/bin/lsyncd -nodaemon /etc/lsyncd/lsyncd.conf.lua
autostart=true
autorestart=unexpected
startretries=3

And this configuration to lsyncd (/etc/lsyncd/lsyncd.conf.lua):
settings {
    logfile = "/var/log/lsyncd/lsyncd.log",
    statusFile = "/var/log/lsyncd/lsyncd.status"
}

sync {
    default.rsync,
    source="/var/www/html/sites/default/files",
    target="root@cdn:/var/www/html/sites/default/files",
    exclude = {"*.php", "*.po", "\.ht*"},
    rsync = {
        archive = false,
        acls = false,
        compress = true,
        links = false,
        owner = false,
        perms = false,
        verbose = true,
        rsh = "/usr/bin/ssh -p 22 -o StrictHostKeyChecking=no"
    }
}

Also I had configure ssh keys and install rsync in the servers.


text:
Q: Interactive programming language? Is there a programming language which can be programmed entirely in interactive mode, without needing to write files which are interpreted or compiled. Think maybe something like IRB for Ruby, but a system which is designed to let you write the whole program from the command line.

A: Smalltalk can be programmed entirely interactively,  but I wouldn't call the smalltalk prompt a "command line".  Most lisp environments are like this as well.  Also postscript (as in printers) if memory serves.
Are you saying that you want to write a program while never seeing more code than what fits in  the scrollback buffer of your command window?

A: I assume you are looking for something similar to how BASIC used to work (boot up to a BASIC prompt and start coding).
IPython allows you to do this quite intuitively. Unix shells such as Bash use the same concept, but you cannot re-use and save your work nearly as intuitively as with IPython. Python is also a far better general-purpose language.
Edit: I was going to type up some examples and provide some links, but the IPython interactive tutorial seems to do this a lot better than I could. Good starting points for what you are looking for are the sections on source code handling tips and lightweight version control. Note this tutorial doesn't spell out how to do everything you are looking for precisely, but it does provide a jumping off point to understand the interactive features on the IPython shell.
Also take a look at the IPython "magic" reference, as it provides a lot of utilities that do things specific to what you want to do, and allows you to easily define your own. This is very "meta", but the example that shows how to create an IPython magic function is probably the most concise example of a "complete application" built in IPython.

A: There's always lisp, the original alternative to Smalltalk with this characteristic.

A: The only way to avoid writing any files is to move completely to a running interactive environment. When you program this way (that is, interactively such as in IRB or F# interactive), how do you distribute your programs? When you exit IRB or F# interactive console, you lose all code you interactively wrote.
Smalltalk (see modern implementation such as Squeak) solves this and I'm not aware of any other environment where you could fully avoid files. The solution is that you distribute an image of running environment (which includes your interactively created program). In Smalltalk, these are called images.

A: Any unix shell conforms to your question. This goes from bash, sh, csh, ksh to tclsh for TCL or wish for TK GUI writing.

A: As already mentioned, Python has a few good interactive shells, I would recommend bpython for starters instead of ipython, the advantage of bpython here is the support for autocompletion and help dialogs to help you know what arguments the function accepts or what it does (if it has docstrings).

*

*Screenshots: http://bpython-interpreter.org/screenshots/

A: This is really a question about implementations, not languages, but

*

*Smalltalk (try out the Squeak version) keeps all your work in an "interactive workspace", but it is graphical and not oriented toward the command line.

*APL, which was first deployed on IBM 360 and 370 systems, was entirely interactive, using a command line on a modified IBM Selectric typewriter!  Your APL functions were kept in a "workspace" which did not at all resemble an ordinary file.

*Many, many language implementations come with pure command-line interactive interpreters, like say Standard ML of New Jersey, but because they don't offer any sort of persistent namespace (i.e., when you exit the program, all your work is lost), I don't think they should really count.
Interestingly, the prime movers behind Smalltalk and APL (Kay and Iverson respectively) both won Turing Awards.  (Iverson got his Turing award after being denied tenure at Harvard.)

A: TCL can be programmed entirely interactivly, and you can cetainly define new tcl procs (or redefine existing ones) without saving to a file.
Of course if you are developing and entire application at some point you do want to save to a file, else you lose everything. Using TCLs introspective abilities its relatively easy to dump some or all of the current interpreter state into a tcl file (I've written a proc to make this easier before, however mostly I would just develop in the file in the first place, and have a function in the application to resources itself if its source changes).

A: Not sure about that, but this system is impressively interactive: http://rigsomelight.com/2014/05/01/interactive-programming-flappy-bird-clojurescript.html

A: Most variations of Lisp make it easy to save your interactive work product as program files, since code is just data.
Charles Simonyi's Intentional Programming concept might be part way there, too, but it's not like you can go and buy that yet. The Intentional Workbench project may be worth exploring.

A: Many Forths can be used like this.

A: Someone already mentioned Forth but I would like to elaborate a bit on the history of Forth. Traditionally, Forth is a programming language which is it's own operating system. The traditional Forth saves the program directly onto disk sectors without using a "real" filesystem. It could afford to do that because it didn't ran directly on the CPU without an operating system so it didn't need to play nice.
Indeed, some implementations have Forth as not only the operating system but also the CPU (a lot of more modern stack based CPUs are in fact designed as Forth machines).
In the original implementation of Forth, code is always compiled each time a line is entered and saved on disk. This is feasible because Forth is very easy to compile. You just start the interpreter, play around with Forth defining functions as necessary then simply quit the interpreter. The next time you start the interpreter again all your previous functions are still there. Of course, not all modern implementations of Forth works this way.

A: Clojure
It's a functional Lisp on the JVM. You can connect to a REPL server called nREPL, and from there you can start writing code in a text file and loading it up interactively as you go.
Clojure gives you something akin to interactive unit testing.
I think Clojure is more interactive then other Lisps because of it's strong emphasis of the functional paradigm. It's easier to hot-swap functions when they are pure.
The best way to try it out is here: http://web.clojurerepl.com/
ELM
ELM is probably the most interactive you can get that I know of. It's a very pure functional language with syntax close to Haskell. What makes it special is that it's designed around a reactive model that allows hot-swapping(modifying running code(functions or values)) of code. The reactive bit makes it that whenever you change one thing, everything is re-evaluated.
Now ELM is compiled to HTML-CSS-JavaScript. So you won't be able to use it for everything.
ELM gives you something akin to interactive integration testing.
The best way to try it out is here: http://elm-lang.org/try


text:
Q: ESXi Connection issue We have a server currently running VMware ESXi. The VMSphere client is having some issues connecting; giving the "Can not establish a secure connection" when clicking on Console as well as both lag issues when trying to perform any task such as clicking on tabs and windows. On top of this we are getting "Error connecting: A secure connection to the host could not be established. Try again?" every few moments.
Does anyone know what could be causing this problem? Is it on our side or on the server hosting side? Our server host is "Joe's Data Center" so if anyone has any idea on their reputation as well please feel free to input your experience.

A: Sounds like network bandwidth or latency problems.  Use vSphere client to look at the network topology and make sure that your vcenter NIC is not also used for data traffic.  I'm not sure how much you can see in the free version if you're using that, but using the same physical NIC for vcenter as you use for a high traffic VM will do this.  You can ping the service console or use a scp tool that shows traffic to see if there's latency or bandwidth clogs on the service console nic.
Install a small WinXP VM in your ESXi and load vsphere client.  Can it connect reliably?  If not, you need to know about the network topology to know what that means exactly, but it will rule out the internet as the problem.  If it does disconnect, does it disconnect in lockstep with your local vsphere client?

A: The console connection is very bandwidth intensive so I'm not surprised you are having slowness issues with that.  Our console connection is currently a 1GB connection but when it was 100MB we had some slowness and an occasional disconnect.
I would recommend contacting Joe's Data Center about not being able to establish a secure connection.

A: Please try this command
Log into console via ssh run this command
Service mgmt-vmware restart and try to connect via vsphere


text:
Q: F# Add New Item to Collections.Map? I want to create a map and a function to add item to that map.
This is what I did
let mymap = Map.empty

let myfunc nId nValue =
    mymap = Map.add nId nValue ;;

But this produced following Error
This expression was expected to have type Map<'a,'b> but here has type Map<'c,'d> -> Map<'c,'d>
What did I do wrong?

A: Maps are immutable so you need to do let mutable mymap.
Also, = does comparison, you need <- for assignment, which is why you got the error.
Something like
let mutable mymap = Map.empty

let myfunc nId nValue =
    mymap <- Map.add nId nValue mymap;;

is what you want

A: Apart from assigning mymap to a new value as in John's answer, you can do it using a more idiomatic FP way:
let mymap = Map.empty

let myfunc nId nValue =
    Map.add nId nValue mymap

Where John's myfunc has a signature of 'a -> 'b -> unit because of the assignment, mine has a signature of 'a -> 'b -> Map<'a, 'b>, which is more common in FP to return a new Map instead of modifying an existing map (mymap).


text:
Q: Converting a deeply nested list to a dataframe I have a deeply nested list I would like to convert to a data frame.
Here's what the structure looks like:
ls <- list('10' = list('123' = list('0.1' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8)),
                                    '0.2' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8))),
                       '456' = list ('0.1' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)),
                                     '0.2' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)))),
           '20' = list('123' = list('0.1' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8)),
                                    '0.2' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8))),
                       '456' = list ('0.1' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)),
                                     '0.2' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)))))

> ls[['10']][['123']][['0.1']]
$Gmax.val
[1] -0.1982298

$G2.val
[1] -0.2761515

$Gmax.vec
[1] -0.4732736 -0.5714809 -0.1600405 -0.7138532  0.3503852 -0.7367241  0.3024992 -0.4931045

$G2.vec
[1] -0.2374231 -0.7927135 -0.9554769  0.8733201 -0.4126742  1.8689940  0.1576750 -0.2184344

Each sublist name is a value for a different variable: in this example, maybe:
ls[[]] = time; 10 or 20
ls[[]][[]] = seed; 123 or 456
ls[[]][[]][[]] = treatment; 0.1 or 0.2

Ideally I'd like to have the names of sublists used as values in their own columns. I'd like the data frame to look like this:
#  time seed treatment  Gmax.val     G2.val    Gmax.vec     G2.vec
#1   10  123       0.1 0.1972457 -0.1224265  0.06121407  1.5102516
#2   10  123       0.1 0.1972457 -0.1224265 -2.53026477 -0.1320042
#3   10  123       0.1 0.1972457 -0.1224265  0.06648820 -0.2477285
#4   10  123       0.1 0.1972457 -0.1224265 -0.45594701 -0.8577670
#5   10  123       0.1 0.1972457 -0.1224265  0.90828911 -1.0710828
#6   10  123       0.1 0.1972457 -0.1224265  0.56427976  1.5086222

Thanks for the help.

A: Another approach is to:

*

*Melt the nested list to a data.frame with rrapply() in the rrapply-package (or similarly with reshape2::melt()).

*Reshape the data.frame to the required format using tidyr's pivot_wider() and unnest().

library(rrapply)
library(tidyverse)

rrapply(ls, how = "melt") %>%                            ## melt to long df
  pivot_wider(names_from = "L4") %>%                     ## reshape to wide df
  unnest(c(Gmax.val, G2.val, Gmax.vec, G2.vec)) %>%      ## unnest list columns
  rename(time = L1, seed = L2, treatment = L3)           ## rename columns

#> # A tibble: 64 x 7
#>    time  seed  treatment Gmax.val G2.val Gmax.vec  G2.vec
#>    <chr> <chr> <chr>        <dbl>  <dbl>    <dbl>   <dbl>
#>  1 10    123   0.1         -0.626  0.184   -0.836  1.51
#>  2 10    123   0.1         -0.626  0.184    1.60   0.390
#>  3 10    123   0.1         -0.626  0.184    0.330 -0.621
#>  4 10    123   0.1         -0.626  0.184   -0.820 -2.21
#>  5 10    123   0.1         -0.626  0.184    0.487  1.12
#>  6 10    123   0.1         -0.626  0.184    0.738 -0.0449
#>  7 10    123   0.1         -0.626  0.184    0.576 -0.0162
#>  8 10    123   0.1         -0.626  0.184   -0.305  0.944
#>  9 10    123   0.2          0.821  0.594    0.919 -0.478
#> 10 10    123   0.2          0.821  0.594    0.782  0.418
#> # … with 54 more rows

Or using data.table's dcast() to reshape the long table into wide format:
library(data.table)

long_dt <- as.data.table(rrapply(ls, how = "melt"))
wide_dt <- dcast(long_dt, L1 + L2 + L3 ~ L4)
wide_dt <- wide_dt[, lapply(.SD, unlist), by = list(L1, L2, L3), .SDcols = c("Gmax.val", "G2.val", "Gmax.vec", "G2.vec")]
setnames(wide_dt, old = c("L1", "L2", "L3"), new = c("time", "seed", "treatment"))

Some benchmarks
microbenchmark::microbenchmark(
  tidyr = {
    rrapply(ls, how = "melt") %>%
      pivot_wider(names_from = "L4") %>%
      unnest(c(Gmax.val, G2.val, Gmax.vec, G2.vec)) %>%
      rename(time = L1, seed = L2, treatment = L3)
  },
  data.table = {
    wide_dt <- dcast(as.data.table(rrapply(ls, how = "melt")), L1 + L2 + L3 ~ L4)
    wide_dt <- wide_dt[, lapply(.SD, unlist), by = list(L1, L2, L3), .SDcols = c("Gmax.val", "G2.val", "Gmax.vec", "G2.vec")]
    setnames(wide_dt, old = c("L1", "L2", "L3"), new = c("time", "seed", "treatment"))
    wide_dt
  },
  times = 25
)
#> Unit: milliseconds
#>        expr       min        lq      mean    median        uq       max neval
#>       tidyr 17.959197 20.072647 23.662698 21.278771 25.633581 40.593022    25
#>  data.table  2.061861  2.655782  2.966581  2.784425  2.988044  5.032524    25

A: Here's a solution that uses some of the newer "rectangling" methods in tidyr.  I'm posting this mainly as an exercise to gain and share some familiarity with these functions - my sense is that this approach could definitely be, well, tidied up a bit.  Still, it's a nice way to play with swinging back and forth between wide/long list unpacking.
library(tidyverse)
set.seed(1L)

tibble(time = names(data), data = data) %>%
  unnest_wider(data) %>%
  pivot_longer(-time, names_to = "seed", values_to = "treatment") %>%
  unnest_wider(treatment) %>%
  pivot_longer(-c(time, seed), names_to = "treatment", values_to = "g_data") %>%
  unnest_wider(g_data) %>%
  mutate(row_n = row_number()) %>%
  pivot_longer(c(Gmax.vec, G2.vec), names_to = "g", values_to = "g_val") %>%
  unnest_longer(g_val) %>%
  group_by(row_n, time, seed, treatment, Gmax.val, G2.val, g) %>%
  mutate(sub_n = row_number()) %>%
  pivot_wider(names_from = g, values_from = g_val) %>%
  ungroup() %>%
  select(-row_n, -sub_n)

  # A tibble: 64 x 7
   time  seed  treatment Gmax.val G2.val Gmax.vec  G2.vec
   <chr> <chr> <chr>        <dbl>  <dbl>    <dbl>   <dbl>
 1 10    123   0.1         -0.626  0.184   -0.836  1.51
 2 10    123   0.1         -0.626  0.184    1.60   0.390
 3 10    123   0.1         -0.626  0.184    0.330 -0.621
 4 10    123   0.1         -0.626  0.184   -0.820 -2.21
 5 10    123   0.1         -0.626  0.184    0.487  1.12
 6 10    123   0.1         -0.626  0.184    0.738 -0.0449
 7 10    123   0.1         -0.626  0.184    0.576 -0.0162
 8 10    123   0.1         -0.626  0.184   -0.305  0.944
 9 10    123   0.2          0.821  0.594    0.919 -0.478
10 10    123   0.2          0.821  0.594    0.782  0.418
# … with 54 more rows

A: Here is base R solution which is 5-94 times faster than other answers.
You can use a function like this one which will work even if you change the names of the inner-most lists:
# turns a deep nested list to a data.frame.
#
# Args:
#   x: list of nested lists. All needs to have identical setup and
#      names.
#   cnam: character vector with column names for the columns which are
#         from the non-terminal lists.
deep_nested_to_df <- function(x, cnam)
  .deep_nested_to_df(x, cnam)

# do not call this function
.deep_nested_to_df <- function(x, cnam, idx = 1L){
  # check if all elements are lists
  is_all_lists <- all(sapply(x, is.list))

  if(is_all_lists){
    # create data.frames out of elements
    out <- lapply(x, .deep_nested_to_df, cnam = cnam, idx = idx + 1L)

    # check that all column names match
    my_cnam <- colnames(out[[1L]])
    stopifnot(all(length(out[[1L]]) == sapply(out, length)),
              all(sapply(out, function(x) all(colnames(x) == my_cnam))))

    # create the new colum
    new_col <- c(mapply(rep, x = names(x), times = sapply(out, NROW)))

    # combine to one data.frame
    out <- do.call(rbind, out)

    # add the new column
    out <- do.call(cbind, list(
      as.data.frame(new_col, stringsAsFactors = FALSE), out))
    colnames(out)[1L] <- cnam[idx]
    if(idx == 1L)
      rownames(out) <- 1:NROW(out)
    return(out)
  }

  as.data.frame(x, stringsAsFactors = FALSE)
}

# use the function
res <- deep_nested_to_df(ls, c("time", "seed", "treatment"))
head(res, 16)
#R>    time seed treatment Gmax.val G2.val Gmax.vec G2.vec
#R> 1    10  123       0.1    -0.63   0.18   -0.836  1.512
#R> 2    10  123       0.1    -0.63   0.18    1.595  0.390
#R> 3    10  123       0.1    -0.63   0.18    0.330 -0.621
#R> 4    10  123       0.1    -0.63   0.18   -0.820 -2.215
#R> 5    10  123       0.1    -0.63   0.18    0.487  1.125
#R> 6    10  123       0.1    -0.63   0.18    0.738 -0.045
#R> 7    10  123       0.1    -0.63   0.18    0.576 -0.016
#R> 8    10  123       0.1    -0.63   0.18   -0.305  0.944
#R> 9    10  123       0.2     0.82   0.59    0.919 -0.478
#R> 10   10  123       0.2     0.82   0.59    0.782  0.418
#R> 11   10  123       0.2     0.82   0.59    0.075  1.359
#R> 12   10  123       0.2     0.82   0.59   -1.989 -0.103
#R> 13   10  123       0.2     0.82   0.59    0.620  0.388
#R> 14   10  123       0.2     0.82   0.59   -0.056 -0.054
#R> 15   10  123       0.2     0.82   0.59   -0.156 -1.377
#R> 16   10  123       0.2     0.82   0.59   -1.471 -0.415
str(res)
#R> 'data.frame':   64 obs. of  7 variables:
#R>  $ time     : chr  "10" "10" "10" "10" ...
#R>  $ seed     : chr  "123" "123" "123" "123" ...
#R>  $ treatment: chr  "0.1" "0.1" "0.1" "0.1" ...
#R>  $ Gmax.val : num  -0.626 -0.626 -0.626 -0.626 -0.626 ...
#R>  $ G2.val   : num  0.184 0.184 0.184 0.184 0.184 ...
#R>  $ Gmax.vec : num  -0.836 1.595 0.33 -0.82 0.487 ...
#R>  $ G2.vec   : num  1.512 0.39 -0.621 -2.215 1.125 ...

The function could be much faster. I suspect that the calls to as.data.frame and rbind slows the function down quite a bit. Nevertheless, it works.
Faster version
A faster version is something like:
deep_nested_to_df_fast <- function(x, cnam)
  .deep_nested_to_df_fast(x, cnam)

.deep_nested_to_df_fast <- function(x, cnam, idx = 1L){
  # check if all elements are list
  is_all_lists <- all(sapply(x, is.list))

  if(is_all_lists){
    # create data.frames out of elements
    out <- lapply(x, .deep_nested_to_df_fast, cnam = cnam, idx = idx + 1L)

    # check that all column names match
    my_cnam <- colnames(out[[1L]])
    stopifnot(all(length(out[[1L]]) == sapply(out, length)),
              all(sapply(out, function(x) all(colnames(x) == my_cnam))))

    # create the new colum
    new_col <- mapply(
      rep, x = names(x), times = sapply(out, function(x) length(x[[1L]])),
      SIMPLIFY = FALSE)
    new_col <- do.call(c, new_col)

    # combine to a list instead of a data.frame
    out <- do.call(mapply, c(list(FUN = c, SIMPLIFY = FALSE), out))

    # add the new colum
    out <- c(list(new_col), out)
    names(out)[1L] <- cnam[idx]

    if(idx == 1L)
      # turn it into a data.frame
      out <- structure(
        lapply(out, unname), names = names(out),
        row.names = 1:length(out[[1L]]), class = "data.frame")

    return(out)
  }

  # create list of element with an equal number
  ele_length <- sapply(x, length)

  # check that all have either the maximum number of elements or one
  # element
  max_len <- max(ele_length)
  stopifnot(all(ele_length %in% c(1L, max_len)))

  # return list like data.frame
  lapply(x, rep, length.out = max_len)
}

It gives the same and is faster in this case:
# gives the same
res_fast <- deep_nested_to_df_fast(ls, c("time", "seed", "treatment"))
all.equal(res, res_fast)
#R> [1] TRUE

# check computation time. We also compare with other answers
library(rrapply)
library(tidyverse)
library(data.table)

Joris_ans <- function()
  rrapply(ls, how = "melt") %>%
    pivot_wider(names_from = "L4") %>%
    unnest(c(Gmax.val, G2.val, Gmax.vec, G2.vec)) %>%
    rename(time = L1, seed = L2, treatment = L3)

Andrew_ans <- function(data = ls)
  tibble(time = names(data), data = data) %>%
    unnest_wider(data) %>%
    pivot_longer(-time, names_to = "seed", values_to = "treatment") %>%
    unnest_wider(treatment) %>%
    pivot_longer(-c(time, seed), names_to = "treatment", values_to = "g_data") %>%
    unnest_wider(g_data) %>%
    mutate(row_n = row_number()) %>%
    pivot_longer(c(Gmax.vec, G2.vec), names_to = "g", values_to = "g_val") %>%
    unnest_longer(g_val) %>%
    group_by(row_n, time, seed, treatment, Gmax.val, G2.val, g) %>%
    mutate(sub_n = row_number()) %>%
    pivot_wider(names_from = g, values_from = g_val) %>%
    ungroup() %>%
    select(-row_n, -sub_n)

hello_friend_ans <- function(){
  flat_long_df <- stack(data.frame(do.call("c", lapply(Map(function(x){
    do.call(c, x)}, ls), data.frame))))

  long_df <- cbind(within(flat_long_df, rm(ind)),
                   do.call("rbind", lapply(strsplit(as.character(flat_long_df$ind), "\\."), function(x){
                     data.frame(cbind(time = as.numeric(gsub("X", "", x[1])),
                                      seed = as.numeric(gsub("X", "", x[2])),
                                      treatment = as.numeric(paste(x[3], x[4], sep = ".")),
                                      var = paste(x[5], x[6], sep = ".")))
                   }
                   )
                   )
  )

  wide_df <- setNames(reshape(long_df,
                              idvar= c("time", "seed", "treatment"), timevar="var", direction="wide"),
                      c("time", "seed", "treatment", "Gmax.val", "G2.val", "Gmax.vec", "G2.vec"))
  wide_df
}

det_ans <- function(){
  nested_list <- function(ls, list_names = NULL){

    if(all(map_chr(ls, class) %in% c("numeric", "character", "integer", "logical"))){

      dt <- as.data.table(ls)
      dt[, (str_c("NAME_", seq_along(list_names))) := as.list(list_names)]

      return(dt)
    }

    ls %>% imap(~nested_list(.x, c(list_names, .y)))
  }

  NestedList <- function(ls, new_names){

    dt <- nested_list(ls) %>%
      {do.call(c, unlist(., recursive = FALSE))} %>%
      rbindlist()

    setnames(dt, str_subset(names(dt), "NAME_"), new_names)
    dt
  }

  NestedList(ls, c("time", "seed", "tretment"))
}

bench::mark(
  first = deep_nested_to_df     (ls, c("time", "seed", "treatment")),
  fast  = deep_nested_to_df_fast(ls, c("time", "seed", "treatment")),
  Joris_ans(), Andrew_ans(), hello_friend_ans(), det_ans(),
  min_time = 1, check = FALSE, relative = TRUE)
#R> # A tibble: 6 x 13
#R>   expression            min median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory time  gc
#R>   <bch:expr>          <dbl>  <dbl>     <dbl>     <dbl>    <dbl> <int> <dbl>   <bch:tm> <list> <list> <lis> <lis>
#R> 1 first                4.44   4.39     20.1       1.19     1      207     7    925.3ms <NULL> <Rpro… <bch… <tib…
#R> 2 fast                 1      1        89.2       1        1.28   923     9    930.3ms <NULL> <Rpro… <bch… <tib…
#R> 3 Joris_ans()          9.90   9.85      9.01      1.92     1.03    90     7    897.9ms <NULL> <Rpro… <bch… <tib…
#R> 4 Andrew_ans()        60.2   59.1       1.62     10.9      1.51    11     7    611.5ms <NULL> <Rpro… <bch… <tib…
#R> 5 hello_friend_ans() 103.    94.9       1       203.      14.7      1    10     89.9ms <NULL> <Rpro… <bch… <tib…
#R> 6 det_ans()            5.87   5.73     15.4     106.       1.01   157     7      914ms <NULL> <Rpro… <bch… <tib…

It is 4 times faster than the first version, 5-94 times faster than other answers.
We can make this much faster by using a C++/C implementation which preallocates the final vectors that we will write to. This way, we avoid the repeated memory allocation we make above.
Data
set.seed(1L)
ls <- list('10' = list('123' = list('0.1' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8)),
                                    '0.2' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8))),
                       '456' = list ('0.1' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)),
                                     '0.2' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)))),
           '20' = list('123' = list('0.1' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8)),
                                    '0.2' = list(Gmax.val = rnorm(1),
                                                 G2.val = rnorm(1),
                                                 Gmax.vec = rnorm(8),
                                                 G2.vec = rnorm(8))),
                       '456' = list ('0.1' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)),
                                     '0.2' = list(Gmax.val = rnorm(1),
                                                  G2.val = rnorm(1),
                                                  Gmax.vec = rnorm(8),
                                                  G2.vec = rnorm(8)))))

You might want to use another variable name than ls as there is a ls function.

A: Base R solution:
# Flatten the nested list: flat_long_df => data.frame
flat_long_df <- stack(data.frame(do.call("c", lapply(Map(function(x){
  do.call(c, x)}, ls), data.frame))))

# Derive the features: data.frame => console (stdout)
long_df <- cbind(within(flat_long_df, rm(ind)),
      do.call("rbind",
        lapply(strsplit(as.character(flat_long_df$ind), "\\."), function(x){
      data.frame(cbind(time = as.numeric(gsub("X", "", x[1])),
      seed = as.numeric(gsub("X", "", x[2])),
      treatment = as.numeric(paste(x[3], x[4], sep = ".")),
      var = paste(x[5], x[6], sep = ".")))
      }
    )
  )
)

# Split data by the var vector: df_list => list of data.frames
df_list <- split(long_df, long_df$var)

# Reshape from long to wide: wide_df => data.frame
wide_df <- do.call("cbind", lapply(seq_along(df_list), function(i){
          setNames(within(df_list[[i]], rm(var)),
             c(names(df_list)[i], "time", "seed", "treatment"))
    }
  )
)

A: With recursion:
nested_list <- function(ls, list_names = NULL){

  if(all(map_chr(ls, class) %in% c("numeric", "character", "integer", "logical"))){

    dt <- as.data.table(ls)
    dt[, (str_c("NAME_", seq_along(list_names))) := as.list(list_names)]

    return(dt)
  }

  ls %>% imap(~nested_list(.x, c(list_names, .y)))
}

NestedList <- function(ls, new_names){

  dt <- nested_list(ls) %>%
    {do.call(c, unlist(., recursive = FALSE))} %>%
    rbindlist()

  setnames(dt, str_subset(names(dt), "NAME_"), new_names)
  dt
}

NestedList(ls, c("time", "seed", "tretment"))


text:
Q: jQuery : Textbox empty or not I have several textbox on a page, imagine 10, 4 of these 10 have the class "myClass". I'd like to know if ALL these textbox with class "myClass" have length = 0, in one line command
Possible?
Thanks,
Update1
function MyValidation() {
    var res = true;
    if (!$("input:text.MyClass[value!='']").length) {
        alert("testing");
        res = false;
    }
    return res;
}

When you this code, I receive a "true" all the time never "false" and never "testing". I tried the code of every answer.

A: this should suffice
if ( $('.myClass').filter(function(){
                             return $(this).val() != '';
                           }).length == 0
   )
 {
  /* code to run when all are empty */

 }

demo http://jsfiddle.net/gaby/QasRK/

To accommodate for white-space in the string change
return $(this).val() != '';

to
return $(this).val().replace(/\s/g,'') != '';

This strips the text of white-space before comparing it to ''

A: You can write
if (!$(input.myClass).is(function() { return this.value.length > 0; }))

A: That can also be done with the appropriate attribute selector:
if (!$("input:text.myClass[value!='']").length) {
    // All the .myClass text boxes are empty.
}

A: If you want to values:
var any = $("input:text.myClass").map(function() {
    var value = $.trim($(this).val());
    if (value != "") return value;
}).length > 0;

http://jsfiddle.net/hunter/e6yEd/

If you don't:
var any = $("input:text.myClass").filter(function() {
    return $.trim($(this).val()) != "";
}).length > 0;

http://jsfiddle.net/hunter/e6yEd/5/


text:
Q: Can i put a setTimeout() in a dynamic class? I want to wait 1 second to add hidden to finish the transition transform. Otherwise it hides before the 150ms transition ends. It's a fixed overlay that that pops down from the top. So does anyone know how i should work this out?
className={` flex-col fixed h-full w-full z-20 ${
          navOpen
            ? "flex"
            : setTimeout(() => {
                "hidden";
              }, 1000)
        } `}

A: I'm not quite sure about your goal here but yeah sure you can use setTimeout inside className but not directly, here is what I tried :
const [navOpen,setNavOpen]=useState(false)

useEffect(()=>{
      setTimeout(() => {
        setNavOpen(!navOpen)
      }, 1000);
    },[])

return (
    <div className={` flex-col fixed  bg-red-800 h-full w-full z-20
              ${navOpen ? " flex " : " hidden "} `}>
    </div>
  )

the flex class will not be added but after setTimeout means after 1 second.


text:
Q: Drag & Drop File on input type file doesn't work any more ( Windows 10) I have upgraded my computer to Windows 10 and downloaded the latest Google Chrome : Version 49.0.2623.87 m
My application wasn't using any special scripts to enable drag and drop file upload. It was just using the default behaviour that when you drag a file over an <input type="file" /> field it got selected as if you would click on it and select the file manually.
This behaviour doesn't work any more -> When I drop the file above the input field, the file gets opened / downloaded within the browser.
Has any1 encountered the same issue ? Is it fixable?


text:
Q: shell with xml, grep and sed after searching a lot for solutions to my problem I finally must ask it and try to get some great answers
So, I have an xml file in the likes
< trigger name="ECUReset" value="0x11">
...
< /trigger>
< trigger name="ClearDTC" value="0x14">
...
< /trigger>

I want to parse this with shell script and to retrieve the trigger name and it's value in a associative array, or something close to perl hashes
The tools that I have available on the machine are only grep and sed, I don't have perl or awk
What I managed to get now is
trigger_name=$(sed -n '/trigger_name=/ s/[^\x22]*\x22\(\x22*\)//p' $FILENAME)

but that doesn't return what I wanted
I cannot use perl, though I would definitely like to because I'm a perl dev, and also no awk or something else, just shell with sed and grep.

A: If you have the cut utility:
$ grep "< trigger" test.xml \
> | cut --delimiter=" " --fields=3,4 \
> | cut --delimiter='"' --fields=2,4 --output-delimiter=" : "
ECUReset : 0x11
ClearDTC : 0x14

A: does this work for you? (just with sed)
sed -rn '/trigger name/{s/.*trigger name="([^"]*)" value="([^"]*)".*$/\1=\2/g;p}' file

test
kent$  echo '< trigger name="ECUReset" value="0x11">
...
< /trigger>
< trigger name="ClearDTC" value="0x14">
...
< /trigger>'|sed -rn '/trigger name/{s/.*trigger name="([^"]*)" value="([^"]*)".*$/\1=\2/g;p}'
ECUReset=0x11
ClearDTC=0x14

A: grep 'trigger name' your_file| cut -d'"' -f 2,4|sed 's/\"/ /g'

tested:
>cat temp
< trigger name="ECUReset" value="0x11">
...
< /trigger>
< trigger name="ClearDTC" value="0x14">
...
< /trigger>
> grep 'trigger name' temp | cut -d'"' -f 2,4 | sed 's/\"/ /g'
ECUReset 0x11
ClearDTC 0x14

A: Just using sed:
# names
$ sed -n 's/< trigger name="\([^"]*\).*/\1/p' file
ECUReset
ClearDTC

# values
$ sed -n 's/< trigger.*value="\([^"]*\).*/\1/p' file
0x11
0x14

# both
$ sed -n 's/.*< trigger name="\([^"]*\).*value="\([^"]*\).*/\1 \2/p' file
ECUReset 0x11
ClearDTC 0x14


text:
Q: Does the order in which you pick up items matter? Picking up Cricket's head gives you a x1.5 damage bonus. Some other items also have a multiplicative bonus, does that only count on the damage you already have at that point or is it also recalculated for later pickups?
For example: would picking up small rock and then crickets head give me more damage then first picking up crickets head and then the small rock?

A: No, the order in which you pick up items doesn't matter.

If you don't believe me, let's do some Math!
Now, I can't find the current formula used in Rebirth, but I think that we can still rely on the original Binding of Isaac damage calculation.
In the previous version of the game, the damage formula was something like:
Effective Damage = Damage_Multiplier * (1 + 1.2 * Basic_Damage)^1/2

Each character starts with a base damage of 3.5 multiplied by a character-specific multiplier, for the sake of simplicity we can use 3.5. And we can forget the square root.
Every multiplicative bonus affects Damage_Multiplier, every additive bonus affects Basic_Damage.
For example, Cricket Head gives you:
+0.5 Damage up
x1.5 Damage multiplier
1.5 * (1 + 1.2 * (3.5 + 0.5)) = 8.7

Small Rock instead gives you +1 damage,
1.5 * (1 + 1.2 * (3.5 + 0.5 + 1)) = 10.5

You can see that the result is not affected by the order in which you get an item.

A: No, the order in which you pick up items does not matter.
According to this Reddit post (/u/Twinge is pretty widely known around the subreddit and is pretty reliable), the damage multiplier is constantly being recalculated as opposed to being calculated once and then forgotten about, so the order you pick up items won't matter.


text:
Q: Complement of Sum of Sets I am able to prove that for an Operator $A$ and $\omega \in \mathbb{C}$ one has the following identity for the resolvent:
$$\varrho(A-\omega) = \rho(A)-\omega$$
However i want to have an identity for the spectrum of $A-\omega$. So i thought ok this could be
$$\sigma(A-\omega) = \sigma(A)-\omega$$
But i am totally stuck proving this. It would suffice to know if someone told me if the statement is true.
More general: Let $M \subset \mathbb{C}, \alpha \in \mathbb{C}$ and define the set
$$M-\alpha := \{ x = y - \alpha \colon y \in M \}$$
Does it hold that
$$(M-\alpha)^c = M^c-\alpha$$

A: Yes. More generally, the complementation operation on subsets of a set $C$ commutes with any bijection from $C$ onto $C$.  (So you'll be using the fact that $z\mapsto z-\alpha$ is a bijection from $\mathbb C$ onto $\mathbb C$.)


text:
Q: How to mirror the the THREE.js texture offset property in CSS? I have a 3d model in which an image is rendered as a texture. The THREE.js texture has an offset property which is used for positioning of the texture image. I am looking for a way to mirror this offset property in CSS for an <img> as I am rendering this same model as an image somewhere else.
I have tried using: object-fit: none; object-position: somevalue somevalue but this causes the image to be rendered as its original size which I do not want. I need to use percentage sizing for the image like (100%, etc.) as it is rendered inside a container.


text:
Q: Unable to Serilize Response Data I am developing an action filter using ASP.NET MVC. Now I am trying to serialize response data through below code, but I am getting null returned. So how to serialize the response from filter context into JSON?
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
   object ResponseData;
   var result = filterContext.Result;
   var queryString = filterContext.HttpContext.Request.QueryString.Value;
   var RequestMethod = filterContext.HttpContext.Request.Method;
   var RequestUrl = $"{filterContext.HttpContext.Request.Scheme}://{filterContext.HttpContext.Request.Host}{filterContext.HttpContext.Request.PathBase}{filterContext.HttpContext.Request.Path}{filterContext.HttpContext.Request.QueryString}";

    if (result is ObjectResult objectResult)
    {
      object x = objectResult.Value;
      if (x != null)
      {
        var Value = JsonConvert.SerializeObject(x);
        var value2 =  JsonConvert.SerializeObject(x, new JsonSerializerSettings() { Culture = CultureInfo.InvariantCulture, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

        var DesValue = JsonConvert.DeserializeObject<Response>(Value);
        if (DesValue.code != 1)
        {
          ResponseData = JsonConvert.SerializeObject(DesValue);

          LogContext.PushProperty("RequestEndTime", DateTime.Now);

          LogContext.PushProperty("ResponseHTTPCode", filterContext.HttpContext.Response.StatusCode);

 LogContext.PushProperty("ResponseData", result);

          _logger.Debug("Response Wrapper Not Found Data {RequestMethod} {RequestUrl} {RequestData} {ResponseData} {StatusCode} Information", RequestMethod, RequestUrl, ResponseData, filterContext.HttpContext.Response.StatusCode);
        }
        else
        {
          LogContext.PushProperty("RequestEndTime", DateTime.Now);
LogContext.PushProperty("ResponseHTTPCode", filterContext.HttpContext.Response.StatusCode);

LogContext.PushProperty("ResponseData", JsonConvert.SerializeObject(DesValue));

          _logger.Debug("Response Wrapper {RequestMethod} {RequestUrl} {RequestData} {ResponseData} {StatusCode} Information", RequestMethod, RequestUrl, JsonConvert.SerializeObject(DesValue), filterContext.HttpContext.Response.StatusCode);
      }
    }
  }

  base.OnActionExecuted(filterContext);
}


text:
Q: Does Microsoft SkyDrive have an API? So with the recent news that Microsoft Skydrive is going to get bumped to 25GB of storage per account, does anyone know if SkyDrive has an API?
(And if so, where are the docs?)

A: SkyDrive (renamed 'OneDrive') has an official API. Details can be found by going to The OneDrive Developer center.
You can also find code samples for working with the OneDrive API, along with source code for the SDKs, on GitHub


text:
Q: Trying to upgrade to v3. Unable to find 'admin' username for logging into mysagepay I am the web developer for a company who need to upgrade to v3 of mysagepay to continue trading.
However, the only username that I have been given, does not appear to give me admin rights in the control panel. I need to add the IP address of our shopping cart provider to allow it to continue to work after the end of the july.
My guess is that there is another username , which is the full admin rights one..
The one I have is payments, which allows you to view orders etc, but not access most of the settings.
Is there a standard username for the admin account on a given vendor name? I've tried 'retrieve username' using various emails of the company, but they only return the payments username, which isn't apparently an admin user.
I've filled out a couple of forms for online support but as yet have had no useful responses, and time is running out.
Can any one advise as to whether there is a standard username that gives full access rights (admin?) or whether there is a way of telling what the admin user is.
Many Thanks - pulling my hair out here.
Gavin

A: Call Sage Pay. They can add the IP for you, and/or probably sort out an admin user account. You'll probably need your Merchant number in order to prove you have something to do with that vendor account - you can get this from the authorisation details screen when viewing one of the payments that you have. Number is 0845 111 4455 - I recommend calling out of core business hours as they are pretty busy then (but phones are manned 24/7)


text:
Q: Process speech in Android browser, JavaScript API? Is there an in browser JavaScript API that will process speech in Android Browsers? Web Speech API doesn't seem to work.
Thanks.

A: If the vocabulary is restricted to a few words, you can install pocketsphinx or ATT toolkits and invoke it in javascript.
A far simpler (and realistic) way is to use cloud based speech recognition.  Most android speech recognition tasks, such as google map or speech input, are done on remote servers in the cloud, as the actual speech recognition task is far too CPU/memory/battery intensive to do it on Android. There are several hosted speech recognition services in the cloud you can use. See this answer here: Server-side Voice Recognition .
Your task is essentially reduced to write some javascript code to record the audio, post the audio file to a server and receive the text back.


text:
Q: Multi-threading within a JBoss Web service How can I invoke a query on multiple databases at the same time and wait for their results to return?
Setting
I'm using JAX-WS and JBoss 7 to provide a web service. My service invokes a query on multiple databases, combines their results and returns all the results combined to the caller.

What I've done so far
I have a working client and server (except that the server doesn't retrieve any results from the databases, but I'll get back to that). In the init method of my code, I create an ExecutorService that I reuse and to which I submit Callables (that do the query and return the results from the database).
These Callables perform the database query and return results.
Problem
My Futures return null (and I guess I haven't made any other mistakes). In addition to that, I read somewhere that you shouldn't use your own ExecutorService within a web service deployed on JBoss.
Question
How to solve the problem then? How can I invoke the query on multiple databases at the same time and wait for their results?

A: So using own threads is not advisable in JBoss. I found a few solutions to that:

*

*don't use JBoss, use e.g. the Java Endpoint interface. There you are be able to do everything manually - this means, however, that you miss the nice features coming with JBoss

*use Oracle Glassfish and its new ManagedExecutorService, see e.g. here for a nice example

*use BPEL (Business Process Execution Language) to orchestrate multiple/parallel processes, see e.g. here for some examples


text:
Q: How to carry out a backspace in a textarea using JavaScript? I'm making an online text editor with multiple line indent and unindent functions.
The indent part works almost as expected, except for the selectionEnd flows forward when the whole text is selected and indented.
The main problem comes from the unindent part. If I select the first line after \t, then this line  won't unindent because it doesn't have any \t to replace. It's quite unrealistic to ask the users to select lines from the tabs before the text. So I was thinking if I can add a \b to the start of each line so that every line will backspace one \t when returned. But, instead of backspace one \t, it prints a box.
Thanks for any clue.

$(document).delegate('#t_cont', 'keydown', function(e) {
    var keyCode = e.keyCode || e.which;
    let start = this.selectionStart;
    let end = this.selectionEnd;
    let lines = [];

    if(e.shiftKey && keyCode===9){ //Shift + Tab
        e.preventDefault();
        if(start!==end){
            $(this).val().substring(start,end).split("\n").forEach(function(line){
                lines.push(line);
            });
            lines.forEach(function(line,ind){
                let tablen = line.match(/^(\t)*/)[0].length;
                let tabs = '';
                for(let i=0;i<tablen-1;i++){
                    tabs += "\t";
                }
                //lines[ind] = line.replace(/^(\t)*/,tabs);
            lines[ind] = "\b" + line;
            });
            let txt = lines.join("\n");
            $(this).val($(this).val().substring(0,start) + txt + $(this).val().substring(end));
            this.selectionStart = start - 1;
            this.selectionEnd = end - 2;
        }
    }else if(keyCode==9){ //Tab
        e.preventDefault();
        if(start===end){
            $(this).val(
                $(this).val().substring(0,start) + "\t" + $(this).val().substring(end)
            );
            this.selectionStart = this.selectionEnd = start + 1;
        }else{
            $(this).val().substring(start,end).split("\n").forEach(function(line){
                lines.push(line);
            });
            lines.forEach(function(line,ind){
                lines[ind] = "\t" + line;
            });
            let txt = lines.join("\n");
            $(this).val($(this).val().substring(0,start) + txt + $(this).val().substring(end));
            this.selectionStart = start + 1;
            this.selectionEnd = end + 3;
        }
    }
});
textarea{
  height: 100px;
  width: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
    <head>
        <meta charset="utf-8">
        <title>Online editor</title>
    </head>
    <body class="opt">
        <textarea id="t_cont" name="t_cont" accesskey="x">
Press Tab key to indent selected part
Shift + Tab to unindent

Mary has a little lamb.
  Mary has a little lamb.
    Mary has a little lamb.
      Mary has a little lamb.
        Mary has a little lamb.</textarea>
    </body>
</html>

A: Rewrite the following code block
if(e.shiftKey && keyCode===9){ //Shift + Tab
 ...
}

to extend the selection with leading \t right before the selection, then replace leading \t on each line
if (e.shiftKey && keyCode === 9) { //Shift + Tab
    e.preventDefault();
    if (start !== end) {

        let backIndex = start - 1;
        while (backIndex >=0 && $(this).val().charAt(backIndex) === '\t') { backIndex--; }
        start = backIndex + 1;
        const txt = $(this).val().substring(start, end).split('\n').map(line => line.replace(/^\t/, '')).join('\n');

        $(this).val($(this).val().substring(0, start) + txt + $(this).val().substring(end));
        this.selectionStart = start;
        this.selectionEnd = start + txt.length;
    }
}


text:
Q: Prove an odd group's subgroup is normal let $H$ be a subgroup of a finite group $G$. Assume that $G$ is odd and $|G|=3|H|$  Prove that $H$ is normal in $G$
An hint is given for the solution as follows:
let $\ a \in G\ s.t. a \not\in H$
Define $\phi:H\rightarrow \mathbb{Z}_2\ s.t.\ \phi(h)=0$ if $\ haH=aH$, $\phi(h)=1$ if $\ haH=a^2H$
Then $\phi(H)=\{0\}$ so $\phi(H)=\{0\}=Ker(\phi)$ so $H$ is normal.
My misunderstanding:
Previously I had shown that if $a \not\in H$, there are 3 unique cosets of $H$ in $G$ ($H,aH,a^2H$). So if $h \in H$, and $\phi(h)=0$
$$(*)\implies haH=aH\implies h\in aH \implies H\cap aH\neq \emptyset\implies aH=H$$
Which is obviously a contradiction. Could help me understand

*

*Why is statement $(*)$ not true? (Edit: this has been made clear to me now)

*How would I show that $\phi(h)=0\ \forall h \in H$ ?

A: Assuming you have verified that $\phi$ is a homomorphism, recall that $H / \ker(\phi) \cong \text{im}(\phi)$, so $|H| / |\ker(\phi)| = |\text{im}(\phi)|$. Now $|G|$ is odd, so $|H|$ is odd, so $|H| / |\ker(\phi)|$ is odd, which means that $|\text{im}(\phi)|$ is odd. Since $\text{im}(\phi)$ is a subgroup of $\mathbb Z_2$, its order must be $1$ or $2$, and of these possibilities, only $1$ is odd. Therefore $|\text{im}(\phi)| = 1$, so $|\ker(\phi)| = |H|$, so $\ker(\phi) = H$.


text:
Q: What does 'PLA time' and 'CPB time' mean in SRS I use RTMP server of sys (https://github.com/smartdu/srs)
The log print like this:

[2016-06-26 10:27:00.025][trace][8812][6523] -> PLA time=3687059, msgs=22, okbps=1612,1608,1608, ikbps=0,0,0, mw=350
[2016-06-26 10:27:09.906][trace][8812][6523] -> PLA time=3697060, msgs=22, okbps=1611,1608,1608, ikbps=0,0,0, mw=350
[2016-06-26 10:27:18.081][trace][8812][6487] <- CPB time=5860079, okbps=0,0,0, ikbps=1641,1614,1610, mr=0/350, p1stpt=20000, pnt=20000
[2016-06-26 10:27:19.818][trace][8812][6532] -> PLA time=2748049, msgs=4, okbps=1601,1578,1609, ikbps=0,0,0, mw=350
[2016-06-26 10:27:30.149][trace][8812][6514] -> PLA time=4039065, msgs=24, okbps=1614,1575,1609, ikbps=0,0,0, mw=350
[2016-06-26 10:27:38.081][trace][8812][6487] <- CPB time=5880081, okbps=0,0,0, ikbps=1641,1629,1610, mr=0/350, p1stpt=20000, pnt=20000
[2016-06-26 10:27:39.972][trace][8812][6535] -> PLA time=1423026, msgs=21, okbps=1583,1618,1605, ikbps=0,0,0, mw=350
[2016-06-26 10:27:50.003][trace][8812][6535] -> PLA time=1433026, msgs=23, okbps=1584,1558,1605, ikbps=0,0,0, mw=350
[2016-06-26 10:27:58.081][trace][8812][6487] <- CPB time=5900082, okbps=0,0,0, ikbps=1640,1563,1610, mr=0/350, p1stpt=20000, pnt=20000
[2016-06-26 10:27:59.924][trace][8812][6514] -> PLA time=4069065, msgs=20, okbps=1614,1601,1609, ikbps=0,0,0, mw=350
[2016-06-26 10:28:10.118][trace][8812][6532] -> PLA time=2798050, msgs=24, okbps=1601,1594,1609, ikbps=0,0,0, mw=350

So, what's the items means in the log: 'PLA', 'CPB', 'mr', 'p1stpt', 'pnt', 'mw' and so on.
Thanks for any help!

A: The PLA and CPB is short-name that means the log is generated by different clients, for example player or publisher, which make the logs looks better.
For all short names, please search in GitHub repository, like PLA, which is SRS_CONSTS_LOG_PLAY, means a player:
trunk/src/kernel/srs_kernel_consts.hpp
// Play stream on edge/origin.
#define SRS_CONSTS_LOG_PLAY "PLA"

SRS use tracable logs for each connection/client, because for live streaming it's very very important to collect logs for a client, from a mix of lots of concurrency client logs. To archive this goal, the tracable log defines as:
[         time          ] [level] [pid]  [ cid ] Message.
[2016-06-26 10:27:18.081] [trace] [8812] [6487]  -> PLA time=3687059

So it enable us to quickly grep the player whose id is 6487 by:
grep 6487 objs/srs.log

Note that the cid right now is string format, not an increment number, to avoid conflict between servers.

It's really useful for debugging.
Well, about 'mr', 'p1stpt', 'pnt', 'mw', it's also some short-name to make the cycle log looks better, but you MUST take a look for the code, there is no simple answer about them.


text:
Q: How to get texdoc to return a particular document? I was interested in the layout package but when I did
texdoc layout

it returned the manual for pst-layout.
I have the layout package on my computer in
/usr/local/texlive/2021/texmf-dist/tex/latex/tools/layout.sty

I am waiting for the DVD before updating to the 2022 texlive.

A: I found that if I typed
texdoc -h

it responded with a list of options for the command, one of which was -l to give a list of all the results for name.
Usage: texdoc [OPTION]... NAME...
   or: texdoc [OPTION]... ACTION

Try to find appropriate TeX documentation for the specified NAME(s).
Alternatively, perform the given ACTION and exit.

Options:
  -w, --view        Use view mode: start a viewer. (default)
  -m, --mixed       Use mixed mode (view or list).
  -l, --list        Use list mode: show a list of results.
  -s, --showall     Use showall mode: show also "bad" results.

  -i, --interact    Use interactive menus. (default)
  -I, --nointeract  Use plain lists, no interaction required.
  -M, --machine     Machine-readable output for lists (implies -I).

  -q, --quiet       Suppress warnings and most error messages.
  -v, --verbose     Print additional information (e.g., viewer command).
  -D, --debug       Activate all debug output (equal to "--debug=all").
  -d LIST, --debug=LIST
                    Activate debug output restricted to LIST.
  -c NAME=VALUE     Set configuration item NAME to VALUE.

Actions:
  -h, --help        Print this help message.
  -V, --version     Print the version number.
  -f, --files       Print the list of configuration files used.
  --just-view FILE  Display FILE, given with full path (no searching).

Full manual available via `texdoc texdoc'.

Website: <https://tug.org/texdoc/>
Repository: <https://github.com/TeX-Live/texdoc>
Please email bugs to <texdoc@tug.org>.

I tried
texdoc -l layout

and got
1 /usr/local/texlive/2021/texmf-dist/doc/latex/pst-layout/pst-layout-doc.pdf
   = Package documentation
 2 /usr/local/texlive/2021/texmf-dist/doc/latex/tools/layout.pdf
 3 /usr/local/texlive/2021/texmf-dist/doc/context/third/layout/t-layout.pdf
   = Package documentation
 4 /usr/local/texlive/2021/texmf-dist/doc/latex/handin/layout.pdf
 5 /usr/local/texlive/2021/texmf-dist/doc/latex/latex-refsheet/layout.pdf
 6 /usr/local/texlive/2021/texmf-dist/doc/latex-dev/tools/layout.pdf
 7 /usr/local/texlive/2021/texmf-dist/doc/context/third/layout/VERSION
 8 /usr/local/texlive/2021/texmf-dist/doc/latex/refman/layout_d.pdf
   = [de] Layout-Anderungen mit LaTeX
 9 /usr/local/texlive/2021/texmf-dist/doc/latex/refman/layout_e.pdf
   = [en] Changing the layout with LaTeX
10 /usr/local/texlive/2021/texmf-dist/doc/latex/pst-layout/README
   = Readme
Enter number of file to view, RET to view 1, anything else to skip:

whereupon I entered 2 for the layout package which was the one I was interested in, not pst-layout.


text:
Q: How to replace values in entire column           SNP    CHR       BP         P
1 rs149201999      1 16050408 0.0654584
2 rs146752890 489381 16050612 0.1019340
3 rs139377059      3 16050678 0.0639282

Wanted to learn how to replace the CHR with the number 22 in each of the rows.
test <- replace(df$CHR, df$CHR==22, length=nrow(df))

A: You would just need to do
df$CHR <- 22

That replaces all the values in the CHR column.
Although the replace function would work as well you'd have to use it like this
replace(df$CHR, values = rep(x = 22, length(df$CHR)))

It is overkill in this case though.


text:
Q: Using the Paypal Mobile SDK UI in the REST API I was trying you the Paypal Rest Api here: https://devtools-paypal.com/guide/pay_paypal
In the third step, a link is given which takes you to the login screen of paypal. The link looks like this: https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-2AV07917JJ307845R
I saw the login screen in the ios mobile SDK here: https://github.com/paypal/PayPal-iOS-SDK, which has a really good UI. Is there some way in which the UI of the Mobile SDK can be used in the REST API?

A: The example in the first (and second) links are for building a web app on top of the REST SDK. The good news is that the Mobile SDKs are also built on top of the REST API.
However, the examples for mobile are not as complete. But there is a mobile backend example app in the Python SDK. It should play nicely with the payment verification step or capturing an authorization. Authorizations can be created on iOS by setting payment.intent = PayPalPaymentIntentAuthorize.


text:
Q: Using Tortoise SVN with C++ in Visual Studio 2008 I have an online repository with some .h and .cpp files that make up part of a project. I'm trying to check these out and use them in a new project, but am getting errors (C4627 and C1010). All the files have been added to the project (with Add>Existing Item...), and the subdirectories that contain these files have been added to the "Additional include directories" of the project.
Would I be better off having the entire project tree in the repository? My reason for not doing so is that my colleague and I are working on different parts of the code and so want to use different main methods to test things as we go, and I didn't see any need to be passing around any compiled code etc. since I assumed that given the .h and .cpp files (with the correct settings), visual studio would be able to compile the project.
What's the best way to make Visual Studio 2008 and TortoiseSVN work well together (without spending any money)?

A:
Would I be better off having the entire project tree in the repository?

Most certainly yes.  You should be able to check out and build without much effort.  Creating a new project every time you want to build the source and having to configure it is way too much work.

My reason for not doing so is that my colleague and I are working on different parts of the code and so want to use different main methods to test things as we go, and I didn't see any need to be passing around any compiled code etc.

Ok, just put more than one project in the solution.  There's no reason you can't have separate executable projects for separate tests.

I assumed that given the .h and .cpp files (with the correct settings), visual studio would be able to compile the project.

If all of the settings are the same, then, yes, it should compile fine, but why bother with the hassle when you don't have to?

A:
What's the best way to make Visual Studio 2008 and TortoiseSVN work well together (without spending any money)?

There are a bunch of programs that integrate SVN into Visual Studio. VisualSVN is one of them.

*

*Apologies for the VisualSVN recommendation. We used to use it in an old project and I'm positive it was free then. Maybe they changed their license?

A: Also AnkhSVN which isn't too bad and it's free.  Also, lots of the windows it displays look like TFS (if you're familiar with it)


text:
Q: Loading ng-src images with webpack I am loading an image with angular, e.g.

When I bundle my application with webpack the image URL is resolved in runtime, thus not bundled by webpack's loaders.
This is the image loader I am using:
  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loader: 'url?limit=8192!img'
  }

How can webpack bundle those images resolved in runtime?

A: I created a uiImage directive which requires the images.
 function uiImage() {
    return {
      restrict: 'A',
      link: function(scope, element, attr) {
        var src = attr.uiImage || attr.src;

        function loadImage(image) {
          return require(`Images/${image}`);
        }

        // required for webpack to pick up image
        element.attr('src', loadImage(src));
      }
    };
  }

  uiImage.$inject = [];
  export default uiImage;

Usage:

webpack.config.js
I have a Webpack resolve Images which points to the location of all my images.
resolve: {
  alias: {
   'Images': path.join(config.appDir, '/images')
  }
}

A: Because I also needed thus functionality and found the original answer was far from a perfect solution I ended up figuring it out on my own.
Write a function in the controller:
$scope.loadImage = function(image) {
    return require('/images/' + image);
};

And use it in your ng-src:

After that to make dynamic requires work you can use a context.
For example:
https://github.com/webpack/webpack/tree/master/examples/require.context#examplejs

A: If you need an image path that is programmatically generated, it means you have some logic expecting this image to exist. In other words, you should consider this image as a dependency of that piece of logic, thus you need to require it explicitely.
In your JS code (eg: controller)
this.imageUrl = require('path-to-image' + someDynamicValue + '.jpg');

In your template:

Webpack is smart enough to understand the dynamic require statement and bundle your images that will match that expression.
Check the documentation for more details: https://webpack.github.io/docs/context.html)

A: I needed to dynamically resolve images at runtime with hashes generated by webpack, e.g., imgA.bd79a5ba.png.
{
  test: /\.png$/,
  loader: 'file-loader?name=images/[name].[hash].[ext]',
}

I ended up creating a module to alias and required the images:
let map = {
  'imgA': require('./images/imgA.png'),
  'imgB': require('./images/imgB.png'),
  'imgC': require('./images/imgC.png')
}

This produces the map:
{
  'imgA': imgA.bd79a5ba.png,
  'imgB': imgB.e51f66a2.png,
  'imgC': imgC.d84ae37c.png
}

In my component I resolved the url from the map:
self.link = function link(scope) {
  scope.imageUrl = function(name) {
    function return map[name];
  }
};

It was then trivial to load the image:

The above is simplified. I found it useful to create a module for the map:
export default {
  'imgA': require('./images/imgA.png'),
  'imgB': require('./images/imgB.png'),
  'imgC': require('./images/imgC.png')
}

then import it into the component module:
import urlMap from './imageUrlMap'
console.log(urlMap.imgA)

> imgA.bd79a5ba.png

A: im just using CopyWebpackPlugin and no overhead at all
const CopyWebpackPlugin = require('copy-webpack-plugin');
// WriteFilePlugin  needed only for webpack 3-4 and webpack dev-server
const WriteFilePlugin = require('write-file-webpack-plugin');
plugins: [
  ...
  new WriteFilePlugin(),
  new CopyWebpackPlugin([
        {from: 'files', to: 'files'},
        {from: 'images-2x', to: 'images-2x'},
        {from: 'images', to: 'images'},
      ]),
]


text:
Q: Android Compatibility Library and New Software Releases QUESTION
I use a custom version of the Compatibility Support Library that enables me to use Google Maps with Fragments.
My question is, when new software releases happen, such as Jelly Bean just being released, will my compatibility library still work or will everything crash and break?

A: if it runs fine on your target version, it will run just fine on any greater version.
but its always a good thing to test it on real deive.
hope this answer your question.


text:
Q: Losing data in Chrome I use 2 systems (Windows 7 and 10).
After I launch Google Chrome on another system, I see that no installed extensions and no saved passwords (to login) while bookmarks are in place.
How do I fix this?


text:
Q: How long does Django's password reset link work? I just want to know after how much time does the link expire.
How long does Django's password reset link work?

A: there are two settings that control this, PASSWORD_RESET_TIMEOUT and PASSWORD_RESET_TIMEOUT_DAYS

A: Assuming you are using django-password-reset.
They are configurable but they expire after 48 hours by default.
Password reset links that expire in two days (configurable).


text:
Q: How to use below Firestore map field type to display price according to size Database:
enter image description here
I want to display the size (SizePrice field) in a list view and price should be changed according to the selected size.


text:
Q: What does this bashrc ffmpeg command do? Actually i had added this command in my bashrc a while ago, now i don't know what it does. I am a noob in ffmpeg so i have all the commands converted to bashrc aliases.
Does anyone know what this does?
ffmpeg -i "$1" -i "$2" -c:v copy -c:a aac "$3"

A: I have that command in my bashrc too.
It is used to merge the audio and video into one file. I use it to merge the audio and video from a youtube video downloaded from youtube-dl.
The $1 gets the video file $2 get the audio file and $3 is the name of the output file.
For example-
Let's say you want to merge audio.mp3, video.mp4 into final.mp4 then the command would look something like-
ffmpeg -i video.mp4 -i audio.mp3 -c:v copy -c:a aac final.mp4


text:
Q: What is java interface equivalent in Ruby? Can we expose interfaces in Ruby like we do in java and enforce the Ruby modules or classes to implement the methods defined by interface.
One way is to use inheritance and method_missing to achieve the same but is there any other more appropriate approach available ?

A: Ruby has Interfaces just like any other language.
Note that you have to be careful not to conflate the concept of the Interface, which is an abstract specification of the responsibilities, guarantees and protocols of a unit with the concept of the interface which is a keyword in the Java, C# and VB.NET programming languages. In Ruby, we use the former all the time, but the latter simply doesn't exist.
It is very important to distinguish the two. What's important is the Interface, not the interface. The interface tells you pretty much nothing useful. Nothing demonstrates this better than the marker interfaces in Java, which are interfaces that have no members at all: just take a look at java.io.Serializable and java.lang.Cloneable; those two interfaces mean very different things, yet they have the exact same signature.
So, if two interfaces that mean different things, have the same signature, what exactly is the interface even guaranteeing you?
Another good example:
package java.util;

interface List<E> implements Collection<E>, Iterable<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException;
}

What is the Interface of java.util.List<E>.add?

*

*that the length of the collection does not decrease

*that all the items that were in the collection before are still there

*that element is in the collection

And which of those actually shows up in the interface? None! There is nothing in the interface that says that the Add method must even add at all, it might just as well remove an element from the collection.
This is a perfectly valid implementation of that interface:
class MyCollection<E> implements java.util.List<E> {
    void add(int index, E element)
        throws UnsupportedOperationException, ClassCastException,
            NullPointerException, IllegalArgumentException,
            IndexOutOfBoundsException {
        remove(element);
    }
}

Another example: where in java.util.Set<E> does it actually say that it is, you know, a set? Nowhere! Or more precisely, in the documentation. In English.
In pretty much all cases of interfaces, both from Java and .NET, all the relevant information is actually in the docs, not in the types. So, if the types don't tell you anything interesting anyway, why keep them at all? Why not stick just to documentation? And that's exactly what Ruby does.
Note that there are other languages in which the Interface can actually be described in a meaningful way. However, those languages typically don't call the construct which describes the Interface "interface", they call it type. In a dependently-typed programming language, you can, for example, express the properties that a sort function returns a collection of the same length as the original, that every element which is in the original is also in the sorted collection and that no bigger element appears before a smaller element.
So, in short: Ruby does not have an equivalent to a Java interface. It does, however, have an equivalent to a Java Interface, and it's exactly the same as in Java: documentation.
Also, just like in Java, Acceptance Tests can be used to specify Interfaces as well.
In particular, in Ruby, the Interface of an object is determined by what it can do, not what class it is, or what module it mixes in. Any object that has a << method can be appended to. This is very useful in unit tests, where you can simply pass in an Array or a String instead of a more complicated Logger, even though Array and Logger do not share an explicit interface apart from the fact that they both have a method called <<.
Another example is StringIO, which implements the same Interface as IO and thus a large portion of the Interface of File, but without sharing any common ancestor besides Object.

A: Ruby 3 (2021)
Ruby 3.0 introduced a type system called RBS, which supports interfaces.
interface _IntegerConvertible
   def to_int: () -> Integer
end

Source: https://blog.appsignal.com/2021/01/27/rbs-the-new-ruby-3-typing-language-in-action.html
Sorbet (2020)
Stripe built a static type checker called Sorbet, which supports interfaces. See Abstract Classes and Interfaces in the sorbet docs.
RSpec (Original answer, 2012)
Try rspec's "shared examples":
https://www.relishapp.com/rspec/rspec-core/v/3-5/docs/example-groups/shared-examples
You write a spec for your interface and then put one line in each implementer's spec, eg.
it_behaves_like "my interface"

Complete example:
RSpec.shared_examples "a collection" do
  describe "#size" do
    it "returns number of elements" do
      collection = described_class.new([7, 2, 4])
      expect(collection.size).to eq(3)
    end
  end
end

RSpec.describe Array do
  it_behaves_like "a collection"
end

RSpec.describe Set do
  it_behaves_like "a collection"
end

A: As many answers indicate, there is no way in Ruby to force a class to implement a specific method, by inheriting from a class, including a module or anything similar. The reason for that is probably the prevalence of TDD in Ruby community, which is a different way of defining the interface - the tests not only specify the signatures of the methods, but also the behavior. Thus if you want to implement a different class, that implements some already defined interface, you have to make sure that all the tests pass.
Usually the tests are defined in isolation using mocks and stubs. But there are also tools like Bogus, allowing for defining contract tests. Such tests not only define the behavior of the "primary" class, but also check that the stubbed methods exist in the cooperating classes.
If you are really concerned with interfaces in Ruby I would recommend using a testing framework that implements contract testing.

A:
Can we expose interfaces in Ruby like we do in java and enforce the Ruby modules or classes to implement the methods defined by interface.

Ruby does not have that functionality. In principle, it does not need them as Ruby uses what is called duck typing.
There are few approaches you can take.
Write implementations that raise exceptions; if a subclass attempts to use the unimplemented method, it will fail
class CollectionInterface
  def add(something)
    raise 'not implemented'
  end
end

Along with above, you should write testing code that enforces your contracts (what other post here incorrectly call Interface)
If you find yourself writing void methods like above all the time, then write a helper module that captures that
module Interface
  def method(name)
    define_method(name) { |*args|
      raise "interface method #{name} not implemented"
    }
  end
end

class Collection
  extend Interface
  method :add
  method :remove
end

Now, combine the above with Ruby modules and you are close to what you want...
module Interface
  def method(name)
    define_method(name) { |*args|
      raise "interface method #{name} not implemented"
    }
  end
end

module Collection
  extend Interface
  method :add
  method :remove
end

col = Collection.new # <-- fails, as it should

And then you can do
class MyCollection
  include Collection

  def add(thing)
    puts "Adding #{thing}"
  end
end

c1 = MyCollection.new
c1.add(1)     # <-- output 'Adding 1'
c1.remove(1)  # <-- fails with not implemented

Let me emphasise once again: this is a rudimentary, as everything in Ruby happens at runtime; there is no compile time checking. If you couple this with testing, then you should be able to pick up errors. Even further, if you take the above further, you could probably be able to write an Interface that performs checking on the class first time an object of that class is created; making your tests as simple as calling MyCollection.new... yeah, over the top :)

A: There are no such things as interfaces in the Java way. But there are other things you can enjoy in ruby.
If you want to implement some kind of types and interface - so that the objects can be checked whether they has some methods/messages you require from them -, you can then take a look at rubycontracts. It defines a mechanism similar to the PyProtocols. A blog about type checking in ruby is here.
The mentioned approached are not living projects, although the goal seems to be nice at first, it seems that most of the ruby developers can live without strict type checking. But the flexibility of ruby enables to implement type checking.
If you want to extend objects or classes (the same thing in ruby) by certain behaviors or somewhat have the ruby way of multiple inheritance, use the include or extend mechanism. With include you can include methods from another class or module into an object. With extend you can add behavior to a class, so that its instances will have the added methods. That was a very short explanation though.
I my opinion the best way to resolve the Java interface need is to understand the ruby object model (see Dave Thomas lectures for instance). Probably you will forget about Java interfaces. Or you have an exceptional application on your schedule.

A: All examples here are interesting but missing the validation of the Interface contract, I mean if you want your object implement all Interface methods definition and only this ones you can't. So I propose you a quick simple example (can be improved for sure) for ensure you have exactly what you expect to have through your Interface (The contract).
consider your Interface with the defined methods like that
class FooInterface
  class NotDefinedMethod < StandardError; end
  REQUIRED_METHODS = %i(foo).freeze
  def initialize(object)
    @object = object
    ensure_method_are_defined!
  end
  def method_missing(method, *args, &block)
    ensure_asking_for_defined_method!(method)
    @object.public_send(method, *args, &block)
  end
  private
  def ensure_method_are_defined!
    REQUIRED_METHODS.each do |method|
      if !@object.respond_to?(method)
        raise NotImplementedError, "#{@object.class} must implement the method #{method}"
      end
    end
  end
  def ensure_asking_for_defined_method!(method)
    unless REQUIRED_METHODS.include?(method)
      raise NotDefinedMethod, "#{method} doesn't belong to Interface definition"
    end
  end
end

Then you can write a object with at least the Interface contract:
class FooImplementation
  def foo
    puts('foo')
  end
  def bar
    puts('bar')
  end
end

You can call your Object safely through your Interface for ensuring you are exactly what the Interface define
#  > FooInterface.new(FooImplementation.new).foo
# => foo

#  > FooInterface.new(FooImplementation.new).bar
# => FooInterface::NotDefinedMethod: bar doesn't belong to Interface definition

And you can as well ensure your Object implement all your Interface methods definition
class BadFooImplementation
end

#  > FooInterface.new(BadFooImplementation.new)
# => NotImplementedError: BadFooImplementation must implement the method foo

A: I've extended a bit on carlosayam's answer for my additional needs. This adds a couple additional enforcements and options to the Interface class:  required_variable and optional_variable which supports a default value.
I'm not sure that you would want to use this meta programming with something too large.
As other answers have stated, you're best off writing tests that properly enforce what you're looking for, especially once you want to start enforcing parameters and return values.
Caveat this method only throws an error upon the calling of the code. Tests would still be required for proper enforcement before runtime.
Code Example
interface.rb

module Interface
  def method(name)
    define_method(name) do
      raise "Interface method #{name} not implemented"
    end
  end

  def required_variable(name)
    define_method(name) do
      sub_class_var = instance_variable_get("@#{name}")
      throw "@#{name} must be defined" unless sub_class_var
      sub_class_var
    end
  end

  def optional_variable(name, default)
    define_method(name) do
      instance_variable_get("@#{name}") || default
    end
  end
end

plugin.rb
I used the singleton library for the given pattern I am utilizing. This way any subclasses inherit the singleton library when implementing this "interface".
require 'singleton'

class Plugin
  include Singleton

  class << self
    extend Interface

    required_variable(:name)
    required_variable(:description)
    optional_variable(:safe, false)
    optional_variable(:dependencies, [])

    method :run
  end
end

my_plugin.rb
For my needs this requires that the class implementing the "interface" subclasses it.
class MyPlugin < Plugin

  @name = 'My Plugin'
  @description = 'I am a plugin'
  @safe = true

  def self.run
    puts 'Do Stuff™'
  end
end

A: Ruby itself has no exact equivalent to interfaces in Java.
However, since such an interface can sometimes be very useful, I developed a gem for Ruby myself, which emulates Java interfaces in a very simple way.
It's called class_interface.
It works quite simply. First install the gem by gem install class_interface or add it to your Gemfile and rund bundle install.
Defining an interface:
require 'class_interface'

class IExample
  MIN_AGE = Integer
  DEFAULT_ENV = String
  SOME_CONSTANT = nil

  def self.some_static_method
  end

  def some_instance_method
  end
end

Implementing that interface:
class MyImplementation
  MIN_AGE = 21
  DEFAULT_ENV = 'dev'
  SOME_CONSTANT = 'some_value'

  def specific_method
    puts "very specific"
  end

  def self.some_static_method
    puts "static method is implemented!"
  end

  def some_instance_method
    # implementation
  end

  def self.another_methods
    # implementation
  end

  implements IExample
end

If you don't implement a certain constant or method or the parameter number doesn't match, a corresponding error will be raised before the Ruby program is executed. You can even determine the type of the constants by assigning a type in the interface. If nil, any type is allowed.
The "implements" method must be called at the last line of a class, because that is the code position where the implemented methods above are checked already.
More at:
https://github.com/magynhard/class_interface

A: As everyone here said, there is no interface system for ruby. But through introspection, you can implement it yourself quite easily. Here is a simple example that can be improved in many ways to help you get started:
class Object
  def interface(method_hash)
    obj = new
    method_hash.each do |k,v|
      if !obj.respond_to?(k) || !((instance_method(k).arity+1)*-1)
        raise NotImplementedError, "#{obj.class} must implement the method #{k} receiving #{v} parameters"
      end
    end
  end
end

class Person
  def work(one,two,three)
    one + two + three
  end

  def sleep
  end

  interface({:work => 3, :sleep => 0})
end

Removing one of the methods declared on Person or change it number of arguments will raise a NotImplementedError.

A: I realised that I was using the pattern "Not implemented error" too much for safety checks on objects that I wanted a specific behaviour. Ended up writing a gem that basically allows to use an interface like this:
require 'playable'

class Instrument
  implements Playable
end

Instrument.new #will throw: Interface::Error::NotImplementedError: Expected Instrument to implement play for interface Playable

It does not check for method arguments. It does as of version 0.2.0.
More detailed example at https://github.com/bluegod/rint


text:
Q: Keyboard preview in Winform calling a Wpf Usercontrol I have a Winform app from which I call a Wpf Usercontrol that is in fact a Viewport3D on which the Winform app draws 3D elements such as cylinders.
I need to access the keyboard from the Winform app in order to catch the ^+ and ^- keystrokes to Zoom In / Out, and the arrow keys to rotate the display.
The basic code appears below. The keyboardControl Handler is defined in Sub New. While mouseControl works well, the keyboard strokes are never received by Form1. Keyboard Preview is enabled in Form1.
Would anyone have a suggestion ?
Thanks in advance. Claude
        Private Sub Form1_Load(sender As System.Object, _
                               e      As System.EventArgs) Handles MyBase.Load

        ' Create the WPF UserControl.
        '
        WpfUc        = New UserControl1
        ' ==========================

        Host.Dock =  DockStyle.Fill
        Host.Name = "Host"

        ' Assign the WPF UserControl to the ElementHost control's
        ' Child property.
        '
        Host.Child = WpfUc

        ' Add the ElementHost control to the form's
        ' collection of child controls.
        '
        Me.Controls.Add(Host)

        Visual3d            = New ModelVisual3D
        Group3d             = New Model3DGroup

        Visual3d.Content      = Group3d
        WpfUc.myViewport.Children.Add(Visual3d)

        DefineCamera(TheCamera, WpfUC.myViewport)
        DefineModelCylinders(Group3d)
    End Sub

    Private Sub DefineCamera(ByRef iCamera     As OrthographicCamera,          _
                             ByRef viewport    As Windows.Controls.Viewport3D)

        iCamera                   = New OrthographicCamera
        CameraController          = New SphericalCameraController(iCamera, viewport, WpfUc, WpfUc, WpfUc)
        iCamera.FarPlaneDistance  = 100
        iCamera.NearPlaneDistance = 0
        iCamera.Position          = New Point3D(0, 0, 100)
        iCamera.Width             = 15

    End Sub

    Friend Sub New(ByVal Camera          As OrthographicCamera,           _
                   ByVal viewport        As Windows.Controls.Viewport3D,  _
                   ByVal keyboardControl As UIElement,                    _
                   ByVal wheelControl    As UIElement,                    _
                   ByVal mouseControl    As UIElement)

        TheCamera                   = Camera
        viewport.Camera             = TheCamera

        iKeyboardControl            = keyboardControl
        AddHandler KeyboardControl.PreviewKeyDown,      AddressOf KeyboardControl_KeyDown

        iWheelControl               = wheelControl
        AddHandler WheelControl.PreviewMouseWheel,      AddressOf WheelControl_PreviewMouseWheel

        iMouseControl               = mouseControl
        AddHandler iMouseControl.MouseDown,             AddressOf MouseControl_MouseDown

        PositionCamera()

    End Sub

  Private Sub KeyboardControl_KeyDown(ByVal sender As Object, _
                                      ByVal e      As KeyEventArgs)

        Select Case e.Key
            Case Key.Up
                IncreasePhi()
            Case Key.Down
                DecreasePhi()
            Case Key.Left
                IncreaseTheta()
            Case Key.Right
                DecreaseTheta()
            Case Key.Add, Key.OemPlus
                IncreaseR()
            Case Key.Subtract, Key.OemMinus
                DecreaseR()
        End Select

        PositionCamera()
    End Sub

The Wpf UserControl appears below.
<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="HostingWpfUserControlInWf.UserControl1"
    d:DesignWidth="477.396" d:DesignHeight="274.41"
    >
   <Grid Margin="0">
      <!-- Viewport3D is the rendering surface. -->
      <Viewport3D x:Name="myViewport" x:FieldModifier="Public" Margin="0,0,0,0">
      </Viewport3D>
   </Grid>
</UserControl>

A: Well, after quite a bit of research and Trial and Error, I found out that 2 settings of the Wpf Usercontrol are required for the keyboard inputs to be passed along to the hosting Form:
    WpfUc.Focusable = True

    WpfUC.myViewport.Focusable = True

Easy enough, but hard to find ...


text:
Q: What is the difference between declaring an object outside and inside of a loop I was wondering, what is the difference if any between these two ways of using an object obj. And what will happen to the memory in both examples?

*

*Example 1: Object is declared outside of the loop

*Example 2: Object is declared inside of the loop.

*In both example I call function func which takes as parameters a vector of type float. The dimension of this vector is no less than 9000 elements.

Example 1
MyObject obj;

for(int i = 0; i < n; i ++)
{
    obj.func(vector<float>);
}

Example 2
for(int i = 0; i < n; i ++)
{
    MyObject obj;
    obj.func(vector<float>);
}

A: When you declare the object inside the loop, a new object will be created on each iteration and the exising one destroyed at the end of each iteration. This is because the object will have a scope inside the {}.
When you declare it outside, a single object is created and you work with that, But when you put it inside a loop, a new object is created and destroyed on each iteration, which will affect the speed.
That is, when you use
MyObject obj;

for(int i = 0; i < n; i ++)
{
    obj.func(vector<float>);
}

you crate only one object. But when you use
for(int i = 0; i < n; i ++)
{
    MyObject obj;
    obj.func(vector<float>);
}

you create and destroy n objects. That will increase the execution time. So, it's better to use the first.


text:
Q: How to restart timer at the onPress in react native I have made a small functionality for timer, where a timer will countdown from 10. When it reaches 0, the timer will hide, and a restart button will come at that place. Till this far, I am able to do it.
But I wanted to restart the timer when Restart appears after countdown is completed.
Below is the code:
constructor(props) {
    super(props);
    this.state = {
      timer: 10,
      displayButton: 'none',
      displayTime: 'flex'
    };
  }
  componentDidMount() {
    this.clockCall = setInterval(() => {
      this.decrementClock();
    }, 1000);
  }
  decrementClock = () => {
    this.setState(
      (prevState) => ({timer: prevState.timer - 1}),
      () => {
        if (this.state.timer === 0) {
          this.setState({
            displayTime: "none",
            displayButton: "flex"
          })
        }
      },
    );
  };
  restartButton() {
    this.setState({
      displayTime: "flex",
      displayButton: "none",
      timer: 30,
    })
  }
<Text style={{display: this.state.displayTime}}>{this.state.timer}</Text>
<TouchableOpacity onPress={this.restartButton}>
    <Text style={{display:this.state.displayButton}}>Restart</Text>
</TouchableOpacity>

As you can see, Restart appears when countdown is finished, But when I click on Restart it is showing me error: Cannot read property 'setState' of undefined.

A: Bind your method
When you invoke the restartButton() function, it returns the value of this within the context which in this case is the null.
Since the this context of App is the one that restartButton() should be using, we have to use the .bind() method on it in the constructor.
constructor(props) {
    super(props);
    this.state = {
      timer: 10,
      displayButton: 'none',
      displayTime: 'flex'
    };
this.restartButton= this.restartButton.bind(this);
  }

and the other approach(arrow-function) is if you don't want to bind the function
restartButton =()=> {
    this.setState({
      displayTime: "flex",
      displayButton: "none",
      timer: 30,
    })
  }

A: In the class component, we cannot directly call the methods that use this keyword as an in-class component this keyword refers to the object it called from as here it called from touchable opacity in might refers as the touchable object because of that you are receiving the error for this.setState is not a function as there is no function such as setState in touchable. so you have to bind the methods with a component to update the state or you can simply call the function as below code
onPress={() => this.restartButton()}
To bind the function you can use the below code in your class constructor
this.restartButton= this.restartButton.bind(this);


text:
Q: How to symlink with password in python? I use python on macos. I want to create a symlink using os.symlink() , it works on regular directory but i want to link or mount folders into my /Volumes/ which need password. In terminal i have to do symlink using 'sudo' command.
How to do it in python ? What is the best mechanism to pass the password when i call os.symlink() ?


text:
Q: Serve static files from archive Is there a module for apache/nginx to serve static files from archive (zip, tgz, tbz …), so that if there is no file in specified location, then stated archive is asked for that file?

A: I'm not aware of such a module.
If you write your own, I would recommend that you take a look ate the try_files directive  http://wiki.nginx.org/HttpCoreModule#try_files and hand the request arguments off to a script, e.g. a php file (see on the wiki page the try_files line ending in: /index.php?q=$uri&$args;).
Performance:
That way you do some security checks with php, sort out search engine bots and maybe even memcache some files after you have them unpacked, but that depends on your specific request statistics/patterns.
Some tools or pear packages might allow you to extract files to pipe (stdout) and avoid dumping to the filesystem or unpacking can happen in a ramdisk to speed things up. But again, the way to go depends on your files sizes in order to make something like that reliable.

A: For the case of .tgz and .tbz, most of the performance loss (esp for large archives) should come from the fact you have to read from disk and uncompressing all data up to and including the file you asked for. If you ask for the last file in the archive, then whether a CGI script or a webserver, something will still have to spend the time reading, uncompressing, and discarding all the archive data just to get to your file.
Zip format does allow for random access. If your CGI script is very simple (can be a sh script), and essentially just calls "unzip" with the right argument, then the amount of speedup you could get from  having a server module do it would be rather small.
That said, it's kind of crazy if a module for doing this doesn't exist (but no, I haven't been able to find one).

A: Another possibility may be using a compressed filesystem, depending on types and distribution of the files also with deduplication.
Pro:
-Has almost the same effect als a .zip file ( Storage wise )
-No change on the Webserver part needed
Cons:
-Possibly new FS for the zip DIR
-Maybe not present under used OS ( e.g. ZFS )
Maybe there's another way if you clarify what you are trying to achieve.

A: You should have a look at SquashFS, it's a compressed filesystem.
You can think of it as a tar.gz archive, used mainly in LiveCD/DVD/USB ISOs but perfectly applicable to your situation.
Here is a HowTo.
PS: Contrary to other answers you don't need a particular OS to use SquashFS but if you happen to run Solaris or FreeBSD go for ZFS compression, it's just great !

A: I would suspect that there is not, especially as a fallback when regular files are not found.  That said, a CGI script to do it would be fairly simple.  The performance loss would most likely be noticeable when under load, however.