text:
Q: vba Excel 2010 - MouseDown event on Active X Controls Command Button On this page Microsoft explains how to know if a combinaison of Shift, Ctrl and Alt is pressed when MouseDown event occurs:
Private Sub Form_MouseDown(Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   ShiftTest = Shift And 7
   Select Case ShiftTest
      Case 1 ' or vbShiftMask
         Print "You pressed the SHIFT key."
      Case 2 ' or vbCtrlMask
         Print "You pressed the CTRL key."
      Case 4 ' or vbAltMask
         Print "You pressed the ALT key."
      Case 3
         Print "You pressed both SHIFT and CTRL."
      Case 5
         Print "You pressed both SHIFT and ALT."
      Case 6
         Print "You pressed both CTRL and ALT."
      Case 7
         Print "You pressed SHIFT, CTRL, and ALT."
      End Select
End Sub
It works just fine. I have many CommandButtons, would it be possible not to copy paste all these lines and replace them by a function called instead ?
This is the idea but it is not working:

Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    call test(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
End Sub
Private Sub CommandButton2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    call test(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
End Sub
Same for CommandButton3 and 4...
Private Sub test(Button As Integer, _
      Shift As Integer, X As Single, Y As Single)
   ShiftTest = Shift And 7
   Select Case ShiftTest
      Case 1 ' or vbShiftMask
         Print "You pressed the SHIFT key."
      Case 2 ' or vbCtrlMask
         Print "You pressed the CTRL key."
      Case 4 ' or vbAltMask
         Print "You pressed the ALT key."
      Case 3
         Print "You pressed both SHIFT and CTRL."
      Case 5
         Print "You pressed both SHIFT and ALT."
      Case 6
         Print "You pressed both CTRL and ALT."
      Case 7
         Print "You pressed SHIFT, CTRL, and ALT."
      End Select
End Sub

A: Private Sub CommandButton1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    test CommandButton1, Shift, X, Y
End Sub

Private Sub CommandButton2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    test CommandButton2, Shift, X, Y
End Sub


text:
Q: How to make a sublist refers to his original ArrayList? I have a homework to do in java about ArrayList and Generics types.
I have 2 classes :
-> CoupeDeA
-> TableauPartiel
CoupeDeA is just a describer from where to where an array is cut.
(It contains only two private integer variables "begin" and "end")
TableauPartiel is the class where the ArrayList is.
My problem is I need to create a method in TableauPartiel like this :
public TableauPartiel<E> coupe(CoupeDeA coupe)

And the TableauPartiel returned needs to be a reference of my intial TableauPartiel. Example :
Integer[] arr = {8,7,6,5};
TableauPartiel<E> tab = new TableauPartiel<>(arr);

TableauPartiel<E> tab2 = tab.coupe(1,3);
tab2.set(1,45);

This code is supposed to set 45 at index 1 of my tab2 and at the same time set 45 at index 2.
But I tried many different ways and I managed to get the sublist, but it is not pointing to my original ArrayList.
For example, I tried something like this :
private ArrayList<E> tableau;
...
public TableauPartiel<E> coupe(Coupe coupe)
            throws IndexOutOfBoundsException {
    if (coupe.getBegin() >= 0 && coupe.getEnd() <= tableau.size()) {

        TableauPartiel<E> tab = new TableauPartiel<>((E[]) new Object[coupe.getEnd()-coupe.getBegin()]);

        for (int i = 0; i < coupe.getEnd()-coupe.getBegin(); ++i) {
            tab.set(i, this.get(coupe.getBegin()+i));
        }

        return tab;

    } else {
        throw new IndexOutOfBoundsException();
    }
}

How can I do to get a sublist which refers to his original ArrayList?
I've found a solution for my code with the subList method and by switching the signature of my ArrayList to List but my teacher doesn't want us to use subList finally.
Here is my code with the subList method :
TableauPartiel<E> tab;

if (coupe.getDebut() >= 0 && coupe.getFin() <= taille()) {
    if (coupe.getFin() == -1)
        tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),taille()));
    else
        tab = new TableauPartiel<>(tableau.subList(coupe.getDebut(),coupe.getFin()));

     return tab;
    } else {
    throw new IndexOutOfBoundsException();
    }
}

A: Few small things first:

*

*stick to English words in your code. Especially in names of classes, functions, variables, etc - names have to reveal intentions (without Google Translate). Best not to obtain a bad habit by letting yourself do otherwise.

*I am not so sure how your Coupe is expected to work (is 0 a legal min number or 1?) but coupe.getEnd() <= tableau.size() might get out of hand

Now my suggestion for the solution:
I suggest you modify your TableauPartiel class to have start and end integer fields in addition to private ArrayList<E> tableau; reference you already have. Maybe add a new 'copy constructor' accepting an instance of
TableauPartiel (from which you can copy reference to tableau) and two int values indicating which part of the original tableau you can use (trick here is to also look at start and end values of the object you're 'sublisting' from). That way, when you're calling #coupe you can check for validity of the input numbers (as you already do) and simply return a new TableauPartiel object with a reference to this and method params - start and end values. Add some indexes manipulation logic using those start and end to whatever methods your TableauPartiel has and you should be good to go.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do I get an error when geting values from a jfreechart dataset? I have a method for updating a DialChart that lool like this...
public void updateDatasetSPLmaxSample(double newValue) {
    double currentValue = (double)(datasetSPLmaxSample.getValue()); //ERROR THIS LINE
    if (newValue > currentValue) {
        this.datasetSPLmaxSample.setValue((int)currentValue);
    }
}

However, for some reason I get the following error:
Exception in thread "Thread-9" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
datasetSPLmaxSample.getValue() returns a java Number so casting it to a double like I do shoudn't be a problem as far I know, but it is. Why?

A: java.lang.Number is the abstract superclass of both java.lang.Integer and java.lang.Double, but casting between such sibling classes is not permitted. As your dataset contains instances of Number, you can use the doubleValue() method.
double currentValue = datasetSPLmaxSample.getValue().doubleValue();


text:
Q: {fmt}: always compile-time check format string in function I am trying to create a custom error class, whose constructor creates error message by passing arguments to fmt::format(). I would prefer it to always compile-time check the format string against arguments, without me having to explicitly use FMT_STRING() each time I throw. Something like:
class Err : public std::exception
{
private:
    std::string m_text;
public:
    template <typename S, typename... Args>
    Err(const S& format, Args&&... args) {
        m_text = fmt::format(FMT_STRING(format), args...);
    }

    virtual const char* what() const noexcept {return m_text.c_str();}
};

// ------------------------

throw Err("Error {:d}", 10);     // works
throw Err("Error {:d}", "abc");  // cause Compile-time error

With the preceding code I get error on FMT_STRING() macro:
error C2326: 'Err::{ctor}::<lambda_1>::()::FMT_COMPILE_STRING::operator fmt::v7::basic_string_view<char>(void) const': function cannot access 'format'
message : see reference to function template instantiation 'Err::Err<char[11],int>(const S (&),int &&)' being compiled with [ S=char [11] ]

I have very little experience with template programming. How to have make this always compile-time check the format string without explicitly using FMT_STRING() every time?

A: You can do such compile-time checks in C++20 and recent versions of {fmt} as follows:
#include <fmt/core.h>

class Err : public std::exception {
 private:
  std::string m_text;

 public:
  template <typename... T>
  Err(fmt::format_string<T...> format_str, T&&... args) {
    m_text = fmt::format(format_str, std::forward<T>(args)...);
  }

  virtual const char* what() const noexcept { return m_text.c_str(); }
};

// ------------------------

throw Err("Error {:d}", 10);     // works
throw Err("Error {:d}", "abc");  // compile-time error

Godbolt demo: https://godbolt.org/z/ceGznTaEh

A: I faced this exact same problem today, but I think that the {fmt} library has improved since, and so here is my solution.
The idea here is to have the exact same call in the exception constructor as the fmt::format call: the construction of the fmt::format_string object, using C++20 consteval, will parse and check the format string at compile time. Then, the format string and the variadic parameters are passed to vformat, which is doing the real job.
#include <fmt/format.h>
#include <exception>
#include <iostream>

class Err : public std::exception
{
private:
    std::string m_text;
public:
    template <typename... Args>
    Err(fmt::format_string<Args...> fmt, Args&&... args) {
        m_text = fmt::vformat(fmt, fmt::make_format_args(args...));
    }

    virtual const char* what() const noexcept {return m_text.c_str();}
};

int main() {
    try {
        throw Err("Error {:d}", 10); // Works
        throw Err("Error {:d}", "abc"); // Compile error
    }
    catch(const std::exception& e){
        std::cout << e.what() << std::endl;
    }
}

In my version, I ended up providing a override for the constructor that takes a single string and skips the formatting altogether, and to change the formatting constructor to this:
Err(fmt::format_string<T, Args...> fmt, T&& p1, Args&&... args) {
    m_text = fmt::vformat(fmt, fmt::make_format_args(p1, args...));
}

This is to ensure that the other overload is always chosen when there is only one parameter.


text:
Q: Haproxy Postgresql SSL configuration I need ssl connection between postgresql (patroni cluster) and Haproxy but I didnt find any related docs. Is it possible to configure haproxy via ssl without using pgbouncer or pgpool tools.
I can connect directly to the database server with ssl configuration
but I can't connect by using Haproxy,
-bash-4.2$ psql -d "host=x.x.x.x port=7010 dbname=postgres user=test"
psql: error: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
-bash-4.2$

there is no log record on postgresql.
Thanks.


text:
Q: Integral $\int_{T_{1}}^{T_{2}} \sqrt{\cosh^2\bigg(\frac{x}{a}\bigg) +1} dx$ While doing an arc length problem I found the following integral:
$$Length = \int_{T_{1}}^{T_{2}} \sqrt{\cosh^2\bigg(\frac{x}{a}\bigg) +1} dx$$
I tried using $\cosh x = \frac{e^x + e^{-x}}{2}$ but I got nowhere. Also, I don't know if there's any useful identity like $\cosh^2 x - \sinh^2 x = 1$ that could be useful. Thanks.
EDIT:
Here's the original problem:

Find the arc length of a function defined by $\gamma = (x, a \sinh(\frac{x}{a}))$ in the interval $[T_1, T_2]$.

A: Using $\sinh^2(\frac{x}{a}) +2 = \cosh^2(\frac{x}{a}) + 1$ which directly follows from the identity you mentioned
$$=\int_{T_1}^{T_2} \sqrt{2} \sqrt{\frac{\sinh^2(\frac{x}{a})}{2} + 1}$$
Let $u = \frac{xi}{a}$ and $dx = -ia\text{ }du$ and use $\sinh(z) = -i\sin(iz)$
$$ = -\sqrt{2}ia\int_{T_1}^{T_2} \sqrt{1 - \frac{\sin^2(u)}{2}}du$$
The integral is the incomplete elliptic integral of the second kind $E(u \vert \frac{1}{2})$. Undoing the substitution and using this we get
$$-\sqrt{2}ia E\Big(\frac{xi}{a} \Big\vert \frac{1}{2}\Big) \Bigg\vert_{T_1}^{T_2}$$
Here is an article on the incomplete elliptic integrals


text:
Q: Setting up a minimalist linux environment All right, I've been messing around with various linux distros and a variety of window managers (I seem to change operating systems like most people change their pants), and I've gotten to the point where I know what I want but I'm not sure the best way to set it up. Here's what I want out of my programming machine:

*

*I don't want a status bar. I don't want a menu bar. When there are no windows open, the screen should show my desktop background and nothing else. I'll use alt+f2 to run things, and my shell prompt will tell me my battery life and the time. I'll open network controls and volume controls when I need them, no need for them to pollute the screen all the time.

*I want a good, simple terminal emulator. I'll be using it with tmux. It should have no title bar and, if possible, no app frame. It's ok if I have to run it in full screen mode to remove the app frame, but only if it still plays nicely with alt-tab and workspaces.

*I want a dirt-simple window manager. It needs to support transparency: I don't have a lot of screen real-estate and I often overlay the terminal on the browser and type out commands. I don't want a tiling-only system, for the above reason. Bonus points for tiling and overlaying.

*I'd like multiple workspaces. I prefer to have one gui per workspace. If I could 'pin' the terminal emulator to always show up in each workspace, that's bonus points. If not, I can have a terminal emulator in each workspace attached to the same tmux instance.

*I'd like a way to set up a keypress that always takes me to the current open terminal emulator. Currently, 90% of the time I only have two windows open: the terminal emulator and something else. In this scenario, alt-tab works like a toggle between the two. If I have another gui open (like a developer window with a web browser), this throws a wrench in my workflow. I'd like a way to assign, for example, 'super-T' to switch to the first open terminal emulator. Bonus points if I can also assign 'super-B' (or whatever) to switch to the first open browser.
So far I've been messing around with gnome and tweaking it heavily to match my preferences, but that seems like overkill and I can never get it quite right. I've toyed with xmonad, but it's more for handling many windows, and I usually only have the two.
and am considering fluxbox, but I was wondering if any of your minimalists out there had suggestions that might better match my workflow. I'm sick of fighting the window manager, I just want it to get out of my way.
Edit: To make things clear, I am not considering switching to a mac/windows environment. I find programming in windows to be a bore, and I have no interest in buying new (read: mac) hardware.
Thanks!
-Nate

A:
I don't want a status bar. I don't want a menu bar. When there are no
  windows open, the screen should show my desktop background and nothing
  else. I'll use alt+f2 to run things, and my shell prompt will tell me
  my battery life and the time. I'll open network controls and volume
  controls when I need them, no need for them to pollute the screen all
  the time.

Fluxbox or Openbox window manager.

I want a good, simple terminal emulator. I'll be using it with tmux.
  It should have no title bar and, if possible, no app frame. It's ok if
  I have to run it in full screen mode to remove the app frame, but only
  if it still plays nicely with alt-tab and workspaces.

I'd say xterm.

I want a dirt-simple window manager. It needs to support transparency:
  I don't have a lot of screen real-estate and I often overlay the
  terminal on the browser and type out commands. I don't want a
  tiling-only system, for the above reason. Bonus points for tiling and
  overlaying.

I don't know if Fluxbox and Openbox support all of those, but I'm pretty sure most of the features you requested are in one of them (sorry, I've worked with both of them, but I forgot wich one was Fluxbox and wich one was Openbox).

I'd like multiple workspaces. I prefer to have one gui per workspace.
  If I could 'pin' the terminal emulator to always show up in each
  workspace, that's bonus points. If not, I can have a terminal emulator
  in each workspace attached to the same tmux instance.

Once again, Fluxbox or Openbox :p

I'd like a way to set up a keypress that always takes me to the
  current open terminal emulator. Currently, 90% of the time I only have
  two windows open: the terminal emulator and something else. In this
  scenario, alt-tab works like a toggle between the two. If I have
  another gui open (like a developer window with a web browser), this
  throws a wrench in my workflow. I'd like a way to assign, for example,
  'super-T' to switch to the first open terminal emulator. Bonus points
  if I can also assign 'super-B' (or whatever) to switch to the first
  open browser.

I'm pretty sure it's possible, but I don't think there's an out-of-the-box solution available for that.

Seems that what you're looking for is a minimalistic distro on top of wich you can add the applications you want by yourself.
My suggestion would be that you installed a distro with basic functionality (Arch Linux if you've got time and want to customize everything, otherwise Debian-stable), installed the Fluxbox/Openbox windowmanager on it (you can configure them to get rid of the panel one of them comes with by default), get rid of the default (if one) desktop environment (and, if any, unneeded clutter and applications), reboot, and login to your new session.

A: Build it yourself.. sort of. I used to run a setup VERY similar to this ages ago

*

*openbox as a base WM, though you can replace this with whatever you want

*xcompmgr + transet for transparency and setting window transparency - this will work to add transparency to WMs that don't

*tilda for your terminal emulator (its lighter than guake, and iirc lacks a title bar.
I can't remember the multiple workspaces bit, i hardly used them

A: Also consider the "awesome" window manager - not sure it does all you want, but it is configurable via a turing-complete language (lua) so your more sophisticated keystroke-commands ought to be achievable.

A: I would use windows 7 and autohotkey for most of your problems... You can size windows so that their "superfluous" bars are hidden off your screen (but still exist if you decide you want them), and you can set up your workspace using a ahk script, you can swap windows, you can go to most recently opened terminal or first activated, whichever. I think you can do all this with windows 7 and ahk. Workspaces would simply be keypresses that minimize some windows and activate others again with ahk. The only thing this doesn't answer is that ... well it's not linux, it's windows 7.


text:
Q: Getting the index of a list for the first value that satisfies a criterion I have a list
a = [1.0, 1.2, 1.1, 1.4, 0.1]

and from that list I would like to get the index of the first value that satisfies some criterion, say x > 1.1
What would be a good way of doing this in python?

A: You can combine next and enumerate:
>>> next(i for i,x in enumerate(a) if x > 1.1)
1
>>> next(i for i,x in enumerate(a) if x > 1.3)
3

or
>>> next((i,x) for i,x in enumerate(a) if x > 1.3)
(3, 1.4)

if you wanted both.

A: You can do this:
def analyze(l, criteria):
    for idx in range(len(l)):
        if criteria(l[idx]):
            return idx

And then use it like this:
a = [1.0, 1.2, 1.1, 1.4, 0.1]
analyze(a, lambda x: x > 1.1)

I don't think it too pythonic. There are probably more pythonic ways.

A: I think this is perhaps a little more pythonic than some of the other answers - if that's what you're after.
a = [1.0, 1.2, 1.1, 1.4, 0.1]

def crit(x):
    return x > 1.3

index = None
for i,v in enumerate(a):
    if crit(v):
        index = i
        break

print index


text:
Q: what is kerning and tracking of header 1 in header I can't understand the what its mean and how to deal with it.
"kerning and tracking of Header 1 in header. Header 1 have id main to 5 and 10 respectively."


text:
Q: Change data type per dataframe column based on a dataframe of predefined data types in R I have values dataframe consisting of character columns and a properties dataframe consisting of the column names of the values dataframe and a predefined data type. I need to check if the values data types are consistent with the predefined data type. Therefore I want to change the data types in the values dataframe based on the predefined data types in the properties dataframe in an automated way using map(), apply() or a for loop, preferably a tidy(verse) solution.
Below is an example but the actual dataset has a lot more columns/properties.
# Libraries
library(dplyr)

# Seed
set.seed(12345)

# Property example
properties <-
  tibble(property = c("a", "b", "c"),
         datatype = c("logical", "integer", "double"))

# Values example
values <-
  tibble(a = sample(c("TRUE", "FALSE", "CORRECT"), 10, replace = TRUE),
         b = as.character(sample(c(1:9, 1.4), 10)),
         c = sample(c(-1.5:1.5, "word"), 10, replace = TRUE))

properties
## A tibble: 3 x 2
#  property datatype
#  <chr>    <chr>
#1 a        logical
#2 b        integer
#3 c        double

values
## A tibble: 10 x 3
#   a       b     c
#   <chr>   <chr> <chr>
# 1 FALSE   7     -1.5
# 2 CORRECT 1     word
# 3 FALSE   8     1.5
# 4 FALSE   1.4   -0.5
# 5 TRUE    6     -0.5
# 6 CORRECT 9     1.5
# 7 FALSE   4     0.5
# 8 FALSE   2     1.5
# 9 CORRECT 3     -1.5
#10 FALSE   5     -1.5

Part the my check will be to compare the amount of NAs per column before and after the transformation. This creates another problem as the double values will be automatically transformed to integers, while this is should become NA because it is a faulty data type (column b, row 4).
# Prefered result
tibble(a = c(FALSE, NA, FALSE, FALSE, TRUE, NA, FALSE, FALSE, NA, FALSE),
       b = c(7L, 1L, 8L, NA_integer_, 6L, 9L, 4L, 2L, 3L, 5L),
       c = c(-1.5, NA, 1.5, -0.5, -0.5, 1.5, 0.5, 1.5, -1.5, -1.5))
## A tibble: 10 x 3
#   a         b     c
#   <lgl> <int> <dbl>
# 1 FALSE     7  -1.5
# 2 NA        1  NA
# 3 FALSE     8   1.5
# 4 FALSE    NA  -0.5
# 5 TRUE      6  -0.5
# 6 NA        9   1.5
# 7 FALSE     4   0.5
# 8 FALSE     2   1.5
# 9 NA        3  -1.5
#10 FALSE     5  -1.5

All help is much appreciated!

A: EDIT:
Add a dplyr solution
properties <- mutate(properties,func_name =paste0("as.",datatype) )

values %>%
  mutate_all(function(x) match.fun(properties$func_name[match(deparse(substitute(x)),properties$property)])(x))
#> Warning in (function (x) : NAs introduced by coercion
#> # A tibble: 10 x 3
#>    a         b     c
#>    <lgl> <int> <dbl>
#>  1 FALSE     7  -1.5
#>  2 NA        1  NA
#>  3 FALSE     8   1.5
#>  4 FALSE     1  -0.5
#>  5 TRUE      6  -0.5
#>  6 NA        9   1.5
#>  7 FALSE     4   0.5
#>  8 FALSE     2   1.5
#>  9 NA        3  -1.5
#> 10 FALSE     5  -1.5

Basically this can be done using match.fun(funcname)
# Libraries
library(dplyr)
library(data.table)

# Seed
set.seed(12345)

# Property example
properties <-
  tibble(property = c("a", "b", "c"),
         datatype = c("logical", "integer", "double"))
       # datatype = c("boolean", "integer", "double"))
# Values example
values <-
  tibble(a = sample(c("TRUE", "FALSE", "CORRECT"), 10, replace = TRUE),
         b = as.character(sample(c(1:9, 1.4), 10)),
         c = sample(c(-1.5:1.5, "word"), 10, replace = TRUE))

setDT(properties)
setDT(values)

properties[,func_name:=paste0("as.",datatype)]

for (i in names(values)){
  set(values,j = i,value=match.fun(properties[property==i,func_name])(values[[i]]))

  print(match.fun(properties[property==i,func_name]))
}
#> function (x, ...)  .Primitive("as.logical")
#> function (x, ...)  .Primitive("as.integer")
#> Warning in match.fun(properties[property == i, func_name])(values[[i]]): NAs
#> introduced by coercion
#> function (x, ...)  .Primitive("as.double")

values
#>         a b    c
#>  1: FALSE 7 -1.5
#>  2:    NA 1   NA
#>  3: FALSE 8  1.5
#>  4: FALSE 1 -0.5
#>  5:  TRUE 6 -0.5
#>  6:    NA 9  1.5
#>  7: FALSE 4  0.5
#>  8: FALSE 2  1.5
#>  9:    NA 3 -1.5
#> 10: FALSE 5 -1.5

Created on 2020-04-20 by the reprex package (v0.3.0)
I changed your "boolean" to "logical" as there is no function called as.boolean
You can also try as.boolean <- as.logical to avoid modify your exsiting codes.

A: you can try the following code and see if it serves your purpose.
# Libraries
library(dplyr)

# Seed
set.seed(12345)

# Property example
properties <-
  tibble(property = c("a", "b", "c"),
         datatype = c("logical", "integer", "double"))

# Values example
values <-
  tibble( a = as.logical(sample(c("TRUE", "FALSE", "CORRECT"), 10, replace = TRUE)),
          b = sample(c(1:9, 1.4), 10) %>% ifelse( . -floor(.) == 0 , . ,NA ),
          c = as.numeric(sample(c(-1.5:1.5, "word"), 10, replace = TRUE)) )

Warning message:
In eval_tidy(xs[[i]], unique_output) : NAs introduced by coercion
values
# A tibble: 10 x 3
   a         b     c
   <lgl> <dbl> <dbl>
 1 FALSE     6  -1.5
 2 TRUE     NA  -0.5
 3 TRUE      3   1.5
 4 FALSE     5   0.5
 5 TRUE      2  -1.5
 6 NA        8   0.5
 7 TRUE      7   0.5
 8 TRUE      9   1.5
 9 NA        1  -1.5
10 NA        4  NA

You can check if it works for you, Cheers!


text:
Q: Reuse datastore models across services without symlink If App Engine service A and service B both depend on a datastore model, is there an effective way to share that model between both services without either duplicating the model or symlinking the file the model class definition is declared in?
Would like to hear anyone's experience with this. Maybe storing the shared dependencies in Cloud Storage and pulling the relevant files from there?

A: Not really an answer, just some considerations.
I see a few difficulties to consider if using GCS for storing the shared models:

*

*importing the models in your app code would be a bit more complex, you'll need to use GCS libraries to read the file(s) for dynamic importing as they would not be available in the local filesystem. As a side effect of the dynamic importing you may loose some development capabilities in your IDE (like auto-completion, object structure verifications, etc) Preserving them might be possible, but probably not trivial.

*splitting the model definitions across model files (for partial reuse, inheritance and/or inter-model references for example) would not be a simple task. The point above would need to be addressed in the model files as well, in addition to the application code.

*deploying the app code on GAE and the models on GCP will always be non-atomic, extra care for coordinating the deployments and probably backward/forward compatibility would be needed to minimize/eliminate transient failures.
IMHO the symlinks would be a simpler approach.


text:
Q: Why, fundamentally, are particles charged? This is something that has long bothered me, and I have asked a few physicists and chemists and never gotten a very satisfying answer. Why are particles charged? And I'm not asking (and this is the answer you often get) why some molecule might be negatively charged because the answer to that is simply is that there was one more negatively charged particle than positively charged particle. That doesn't answer my question, however, of why there are charged particles at all?
So, on a fundamental level, what makes one particle charged and another one neutral.
For instance, protons and neutrons have almost exactly the same mass, which I'm assuming that means they have very similar internal compositions, yet one is positively charged and the other neutral. What is going on that makes these particles different?
On a similar note, and I'd really like to know this, how is it that a proton and an electron have exactly equal and opposite charge, yet an electron is about 1000 times less massive than a proton?
I have particular trouble with this question because if the answer were something along the lines of "particle X which composes protons all have partial positive charges of n amount..." I would just ask why particle X has any charge and we'd be in the same predicament.
I'm sure there is a satisfactory answer to my question, I just can't find it and don't know what resources are reliable or detailed enough to be satisfactory.

A:
Why, fundamentally, are particles charged?

The answer to this and the similar questions is : because that is what we have observed and defined by measurements with innumerable data. It is an existential question. Physics is not about existential questions.
Physics is about observations with measurements of the way the natural world behaves and fitting with mathematical models the observed behavior. The models are successful, validated, when they can predict any future behavior accurately.
Starting with the Millikan oil drop experiments the electron was found to have a definite charge and the microcosm of elementary particles made mathematical sense , from nuclear physics to quark physics with assigned charges and masses and a number of quantum numbers. The ingenuity of physicists found that the standard model, a mathematical model ,  could describe all interactions ( almost) of elementary particles and their composites with great accuracy.
Once a mathematical model is successful many people , mainly theorists, tend to agree with a platonic philosophy ( mathematics creates nature), and that is why  your "why" question gets all these explanations from symmetries etc. But the physics truth is that a mathematical model is a tool, not a creator of nature. If we had had different observations we would have had different mathematical models.
IMO physics answers "why" questions by "how" using mathematical models and postulates that relate the mathematics to physical observables, one fits the observations. Why this is so? Because.

A: I am not sure how to answer all of your question but I can answer the neutron and proton part. The charge difference is due to their composition. A neutron is composed of two down quarks and one up quark. A proton is composed of two up quarks and one down. Up quarks have a charge of +2/3 and down quarks have a charge of -1/3. A neutron with composition udd has a charge of 2/3 - 1/3 - 1/3 = 0. A proton with composition uud has charge of 2/3 + 2/3 - 1/3 = +1.

A: This is ultimately a very deep question. We do not have a very easy ability to answer it at this time. Let me give you the pieces that we presently have.
The basic interactions.
The world as we know it today consists of five fundamental things that happen; they are all called "fields" and the first four are called "forces" or "interactions". In rough order from strongest to weakest, these 4 are as follows.

*

*Protons and neutrons are sticky and stick together into atomic nuclei. This is called the strong nuclear force or the strong interaction. Some matter does not feel the strong force; these particles are called "leptons." Some matter does, and they are called "quarks" (and combinations of them are called "hadrons").

*Radioactivity. Neutrons want to turn into a proton-plus-electron-plus-antineutrino triad. In particle physics this is known as the weak nuclear force, or the weak interaction.

*Chemistry. Protons attract electrons and repel protons; electrons repel each other too; they emit light under certain conditions. To particle physics, this is all known as "electromagnetism."

*Things fall down. Matter mysteriously attracts other matter through an unscreenable infinite-range force known as "gravity".

In those four interactions, and mostly in that third one, we think we can find mostly everything that happens in this world. The fifth interaction which is conspicuously absent is the "Higgs field", which we'll talk about in a moment.
We cannot give you a great explanation why Nature hasn't chosen fewer interactions or more interactions; in particular we cannot tell you a deep reason why Nature chose for there to be an electromagnetic interaction at all. We can give you details but you can always persist asking "why" until we find ourselves in ignorance.
And then there was unity.
We can tell you some other things about electric charge though. A full classical theory was available per James Clerk Maxwell, and a full quantum theory became available due to the works of Schwinger, Tomonaga, and Feynman. This became a template for understanding the strong force, with photons replaced by "gluons" and electric charge replaced with three "color charges" (called arbitrarily "red", "green", and "blue") which has to balance out either in the same way that electric charge does (quarks plus antiquarks) or else by having even amounts of the three charges.
In particular, physicists beat their heads against a wall trying to describe the weak interaction in a way that (a) didn't have unphysical consequences and (b) played nice with quantum relativity until 1961, when a young Ph.D. named Sheldon Glashow discovered that you could make relativistic quantum theory and the weak interaction play nice together if you "bundle in" the electromagnetic force and describe them both together, mediated by four types of 'virtual' particles: two of those particles, the Z boson of the weak interaction and the photon of electromagnetism, at very high energies can phase into each other.
Glashow's "electroweak" theory had some unphysical consequences at high energies, which were removed in the mid 60s by postulating this fifth fundamental interaction, which everyone calls the Higgs field. The Higgs field has a weak coupling to all of the "matter" particles but also to some of the "force" particles, giving them mass. In short, the Higgs explains why everything which is not a proton or a neutron doesn't zip off at the speed of light. We believe these days that we've definitively observed some statistical effects of the distinctive particle which quantizes the Higgs field, shedding most of our doubt about this explanation. The interaction-energy that these particles have due to interacting with the Higgs field grants them an effective mass via $E = mc^2$.
Does this habit of Nature unifying these forces go further? Maybe. So-called "grand unified theories" unify the electroweak interaction with the strong interaction, but they often have some strange predictions, like magnetic monopoles or that protons will eventually decay into positrons-plus-photons, which we've never actually seen happen. So it's very hard to endorse these theories at this stage. So-called "theories of everything" incorporate gravity as well.
However, here we're at a significant experimental loss: we simply don't have enough experimental confirmation to decisively say "yes, this grand-unified-theory is good; no, that theory is bad."
What the electroweak theory tells us about charge.
Okay, now that you know that the electromagnetic force is a low-temperature part of this electroweak theory, what does that tell us about electric charge? It says that electric charge comes about as part of two conserved quantities, called "weak isospin" or $T_3$ and "weak hypercharge" or $Y_W.$ The quarks, for some reason, have a weak hypercharge of +1/3. The leptons, for some reason, have weak hypercharge -1. Some things, in addition, have weak isospin +1/2, and some things have weak isospin -1/2, in the same units. What are those reasons? I don't think we really know. (Also don't get too attached to the pluses and minuses; there are 4 "antiparticles" for each of these particles that have the opposite sign for all of them.)
Electric charge in these units is $q(T_3, Y_W) = T_3 + \frac{Y_W}{2}$, leading to four classes of particles: the non-electromagnetic non-strong neutrinos $q(+ \frac 12, -1) = 0$, the electromagnetic non-strong electrons $q(-\frac 12, -1) = -1$, and the electromagnetic strong quarks "up" $q(+\frac 12, +\frac 13) = \frac 23$ and "down" $q(-\frac 12, +\frac 13) = -\frac 13.$
So for example a neutron is made of two downs and an up, total charge $2\cdot\frac{-1}{3} + \frac 23 = 0.$ The weak force will sometimes turn one of those downs into an up plus a $W^-$ boson $q(-1, 0) = -1$ , which then turns into an electron $q(-\frac 12, -1) = -1$ plus an electron antineutrino $q(-\frac 12, +1) = 0.$ The two ups and a down quark will then make up a proton $\frac{-1}{3} + 2\cdot\frac 23 = +1.$
Particles, in short, are charged because they have this intrinsic weak-isospin and this intrinsic weak-hypercharge which they cannot shed. We do not know why they have these exact parameters, except that all of the possibilities are fully represented.
Mass discrepancies.
We've secretly also answered why protons and neutrons have a mass so much higher than the electron: the electron is a single particle which does not feel the strong force; the protons and neutrons are made up of three quarks which are bound together by the strong force. (In general that is a property of the strong force: it is caused by a powerful three-way charge that we call a "color charge"; the color charge has to balance out either by having three particles which each have one the colors, or by having a particle and an antiparticle bound together with the same color charge; if it's not balanced out it will tear particles made with the other weaker forces apart until it is satisfied because it is so strong.) Satisfying the associated strong force comes with a binding energy $E$ which acts like a mass via $E = mc^2.$
Neutrinos and electrons, which don't feel this energy, only get a little bit of mass from their comparatively weak couplings to the Higgs field: up and down quarks also have a little mass from this mechanism. This is much smaller than the binding energy however; it is maybe 1% if the proton/neutron's mass, most of which comes from this strong force.
So that's the tip of the gory details that go into particle-physics. I don't think we can tell you yet why those particular weak hypercharges are associated with having color charge (feeling the strong force) or not; we wouldn't know until we could reliably test the correctness of grand-unified theories and determine which one our electroweak interaction is embedded in, if there even is one. (Nature might just say, "no, that's just the way I roll, no further questions.") In some GUTs, weak hypercharge is totally separate from color charge; in others part of weak hypercharge unifies with color charge at high-enough-energies.

A: The standard model of particle physics is built on gauge theory, which is a theory of local symmetries. This means that the symmetries act differently at different points in space (and time). For example, if you move everything in the universe 1m in one direction, nothing is changed. This is a global symmetry, because everything has been moved by the same amount in the same direction - in other words, it acts the same at every point.
A gauge symmetry is different, because it can act differently at different points. Consider rotating an object by a different amount at each point; it would clearly change the physics of object. In the equations of the standard model, however, you can, in a way,  rotate things by a different amount at each point. This isn't an actual physical rotation, but more a rotation of the equations. Imagine that each equation contains an angle, $\theta(x)$, that varies from point to point in space, but the physics doesn't actually depend in $\theta(x)$ in any way i.e $\theta(x)$ is completely redundant.
There is a mathematical theorem, Noether's theorem, saying that each continuous symmetry of a physical system leads to a conserved quantity, and the fact that we can choose $\theta(x)$ as we please means that we have come sort of conserved quantity. It turns out that the theory of this rotational symmetry leads to certain particles having an electric charge, which is conserved.
So your question ultimately comes down to symmetry.
In short, symmetry = conserved quantity.


text:
Q: NSCocoaErrorDomain Code=257 when trying to access "My Photo Stream" media in iOS 13 In iOS 13, I get an error when I try to access to "My Photo Stream" media, which doesn't exist in device.

Error Domain=NSCocoaErrorDomain Code=257 "ファイル"IMG_0010.JPG"を表示するためのアクセス権がないため、開けませんでした。" UserInfo={NSFilePath=/var/mobile/Media/PhotoStreamsData/8281221100/100APPLE/IMG_0010.JPG, NSUnderlyingError=0x283452820 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

But in iOS 12 and earlier, I don't get the error.
My actual code is like below.

// asset is Photo Stream media.

PHContentEditingInputRequestOptions *editOptions = [PHContentEditingInputRequestOptions new];
editOptions.networkAccessAllowed = YES;
editOptions.progressHandler = ^void(double progress, BOOL *stop) {};

[asset requestContentEditingInputWithOptions:editOptions
                           completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {

    NSError *error;
    NSData *data = [NSData dataWithContentsOfURL:contentEditingInput.fullSizeImageURL
                                         options:(NSDataReadingMappedIfSafe)
                                           error:&error];
    NSLog(@"%@", data); // "Error Domain=NSCocoaErrorDomain Code=257"

I found some people who are struggling with similar issues.
NSCocoaErrorDomain Code=257 file couldn't be opened because you don't have permission to view it : FileManager attributesOfItem returns nil in iOS13
I know Apple is putting so much effort into privacy.
So anything changed around it? And I'd like to know the way to solve my problem.


text:
Q: the enqueue call method of retrofit didn't work I'm learning retrofit lately and I saw a video from youtube. I copied all the codes that I've seen in that video but my code didn't work at all. Nothing happens after I play the app in avd. no errors no exceptions and no logs . Do you know why ??
this is my code
public class MainActivity extends AppCompatActivity {

TextView txtResult ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtResult = findViewById(R.id.txtResult);
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://jsonplaceholder.typicode.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
    Call<List<Post>> call = jsonPlaceHolderApi.getPosts();

    call.enqueue(new Callback<List<Post>>() {
        @Override
        public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {
            Log.e("MAIN ACTIVITY","AAA");

            if (!response.isSuccessful()){
                txtResult.setText("Code : " + response.code());
                return;
            }
            List<Post> posts = response.body();
            Log.e("MAIN ACTIVITY","BBB");

            for(Post item : posts){
                String content = "";
                content = content.concat("Id : " + item.getId());
                content = content.concat("User Id : " + item.getUserId());
                content = content.concat("Title : " + item.getTitle());
                content = content.concat("Text : " + item.getText());
                txtResult.append(content);
                Log.e("MAIN ACTIVITY","CCC");

            }

        }
        @Override
        public void onFailure(Call<List<Post>> call, Throwable t) {
            txtResult.setText(t.getMessage());
            Log.e("MAIN ACTIVITY","DDD");

        }
    });
}

}
public interface JsonPlaceHolderApi {

@GET("posts")
Call<List<Post>> getPosts();

}
I use 4 log.e in my code but non of them work
Update
I think it's because of that I tried to run in android api 29. It runs well in android oreo without any problem but apparently in android 10 we just can fetch imformation from website that has ssl certificate otherwise we hit with Network security config error. Is it right ?


text:
Q: How to print an array element from JSON into PHP If you access the webpage https://api.mercadolibre.com/items/MLB752465575 you will receive a JSON response. All I need to start is print the item "id" on the screen.
This is my code:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

  <?php

    $json_str = "https://api.mercadolibre.com/items/MLB752465575";

    $obj = json_decode($json_str);

    echo "id: $obj->id
";

  ?>

All I want is receive the MLB752465575 part into my browser.
How can I do it?

A: $json_str = "https://api.mercadolibre.com/items/MLB752465575";

The above does not retrieve the data it's saving the url to the var and that's not what you want.
You just need to fetch the content You can use cURL or file_get_contents()
cURL version:
<?php

$url = "https://api.mercadolibre.com/items/MLB752465575";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$r = curl_exec($curl);
curl_close($curl);
$array = json_decode($r, true);

echo "
";
print_r($array);
echo "
";

?>

file_get_contents version:
<?php
$r = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');

echo "
";
echo print_r(json_decode($r, true));
echo "
";
?>

Both of them will work unless the remote website requires you to be human (has extra verifications to stop robot requests). cURL would be a better way if that were the case because you can fake a user agent using a header array.
Once you have the array build it's just a matter of accessing the required data. using $r as an array result of the remote json structure.

A: Use curl to get the result, and json_decode to turn it into an array.
<?php
$url = "https://api.mercadolibre.com/items/MLB752465575";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode != 200) {
      echo "error " . $httpcode;
      curl_close($ch);
      return -1;
}
$result_arr = json_decode($result, true);
echo $result_arr['id'];
curl_close($ch);

A: $jsonResponse = file_get_contents('https://api.mercadolibre.com/items/MLB752465575');
$obj = json_decode($jsonResponse);

echo "id: {$obj->id}
";

What you did in your code was to json_decode the URL itself. You needed to get the content from the URL, and then decode the content.


text:
Q: Evaluating the elliptic integral $\int^1_0 \frac{K(k)}{\sqrt{1-k^2}}\,dk$ Find the elliptic integral $$\int\limits^1_0 \frac{K(k)}{\sqrt{1-k^2}}\,\mathrm{d}k,$$
where
$$K(k) = \int\limits_{0}^{1} \frac {\mathrm dt}{\sqrt{(1 - t^2)(1 - k^2t^2)}}=\int\limits_{0}^{\pi/2} \frac{\text{d}\vartheta}{\sqrt{1 - k^2 \sin^2\vartheta}}$$
My approach: Let $k=\dfrac{\sin\theta}{\sin\phi}$
Now after some calculation, I have reached the following: $$\int\limits_{0}^{\pi/2}\int\limits_{0}^{\phi}\dfrac{d\theta d\phi}{\sqrt{\sin^2\phi-\sin^2\theta}}$$
Now how to proceed from this point..please give some idea/hint.
Definition of elliptic integral: https://en.wikipedia.org/wiki/Elliptic_integral

A: *

*Replace $K$ with its $_2F_1$ representation (DLMF 19.5.1).

*Evaluate using the Euler integral representation of $_3F_2$ (DLMF 16.5.2).

*Simplify using Dixon's well-poised $_3F_2$ sum (DLMF 16.4.4).

*Simplify using the functional relations for $\Gamma$ (DLMF 5.5).

The result is
$$\frac{\Gamma(1/4)^4}{16\pi}\text{.}$$
In detail:
$\newcommand{\d}{\mathrm{d}}$
$$\begin{split}
  \int_0^1 \frac{K(k)}{\sqrt{1-k^2}}\d k
    &= \frac{\pi}{2} \int_0^1 \frac{_2F_1(\tfrac{1}{2},\tfrac{1}{2};1;k^2)} {\sqrt{1-k^2}}\d k \\
    &= \frac{\pi}{4} \int_0^1 \frac{_2F_1(\tfrac{1}{2},\tfrac{1}{2};1;x)} {\sqrt{x(1-x)}}\d x \\
    &= \frac{\pi^2}{4}\,_3F_2(\tfrac{1}{2},\tfrac{1}{2},\tfrac{1}{2};1,1;1) \\
    &= \frac{\pi^2}{4}\left(\frac{\Gamma(\tfrac{5}{4})\Gamma(1)\Gamma(1)\Gamma(\tfrac{1}{4})}{\Gamma(\tfrac{3}{2})\Gamma(\tfrac{3}{4})\Gamma(\tfrac{3}{4})\Gamma(\tfrac{1}{2})}\right) \\
    &= \frac{\Gamma(\tfrac{1}{4})^4}{16\pi}\text{.}
\end{split}$$


text:
Q: Erro ao cadastrar usuário em Django Quando desejo cadastrar um novo usuário em Django, recebo o seguinte aviso:
UNIQUE constraint failed: polls_usuario.matriculaUsuario
O que pode estar acontecendo?
views.py
def registrar(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        usuario_form = UsuarioForm(request.POST)
        if form.is_valid() and usuario_form.is_valid():
            user = form.save(commit=False)
            user.refresh_from_db()  # load the profile instance created by the signal
            user.usuario.matriculaUsuario = form.cleaned_data.get('matriculaUsuario')
            usuario_form.save()
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request,user)
            return render(request, 'polls/index.html', user)
            #return HttpResponseRedirect(reverse('/'))
            #return redirect('/')
    else:
        form = SignUpForm()
        usuario_form = UsuarioForm()
    return render(request, 'polls/registrar.html', {'form': form , 'usuario_form':usuario_form})

forms.py
class UsuarioForm(forms.ModelForm):
    class Meta:
        model = Usuario
        fields = ('matriculaUsuario',)

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(label='Primeiro Nome',max_length=30, required=False, help_text='Opcional.')
    last_name = forms.CharField(label='Último Nome',max_length=30, required=False, help_text='Opcional.')
    email = forms.EmailField(label='E-mail',max_length=254, help_text='Informe o seu e-mail (Requerido)')
    username = forms.CharField(label='Nome de usuário', min_length=4, max_length=150)
    password1 = forms.CharField(label='Senha', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirmação da senha', widget=forms.PasswordInput)

    matriculaUsuario = forms.CharField(label='Matrícula',max_length=12,validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])

    class Meta:
        model = User
        fields = ['first_name', 'last_name','username','matriculaUsuario','email','password1', 'password2',]
    def clean_username(self):
        username = self.cleaned_data['username'].lower()
        r = User.objects.filter(username=username)
        if r.count():
            raise  ValidationError("Nome de usuário já cadastrado")
        return username

    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        r = User.objects.filter(email=email)
        if r.count():
            raise  ValidationError("E-mail já cadastrado")
        return email

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise ValidationError("Senhas não conferem")

        return password2

    def save(self, commit=True):
        user = User.objects.create_user(
            self.cleaned_data['username'],
            self.cleaned_data['email'],
            self.cleaned_data['password1']
        )
        return user
class EditProfileForm(forms.ModelForm):
    first_name = forms.CharField(label='Nome')
    last_name = forms.CharField(label='Sobrenome')
    username = forms.CharField(min_length=4, max_length=150,help_text=("Insira um novo nome de usuário"), label='Nome de usuário')
    email = forms.EmailField(label='E-mail')
    matriculaUsuario = forms.CharField(label='Matrícula', max_length=12,validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])
    class Meta:
        model = User
        fields = ['first_name', 'last_name','username','matriculaUsuario','email']

models.py
class Usuario(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,null=True)
    matriculaUsuario = models.CharField(default='000000000000',max_length=12,primary_key=True,null=False,help_text=_('São requeridos os 12 dígitos referentes à sua matrícula'), validators=[ validators.RegexValidator(re.compile('^[0-9]{12}$'), _('Digite uma matrícula válida'), _('invalid'))])
    def __str__(self):
 return self.user.username
        @receiver(post_save, sender=User)
    def update_user_usuario(sender, instance, created, **kwargs):
        if created:
            Usuario.objects.create(user=instance)
        instance.usuario.save()

    @receiver(post_save, sender=User)
    def create_user_usuario(sender, instance, created, **kwargs):
        if created:
            Usuario.objects.create(user=instance)
    post_save.connect(create_user_usuario,sender=User)
@receiver(post_save, sender=User)
    def save_user_usuario(sender, instance, created,**kwargs):
        if created:
            instance.usuario.save()

EDIT

A: Entendi que vc precisa apenas estender o User adicionando alguns campos, sem necessariamente mudar nada no auth, ou seja, vc não esta customizando a autenticação, correto? mas não consegui entender o que vc quis fazer no model Usuario, a meu ver deveria ser mais simples, ou vc realmente customiza tudo ou apenas estende a classe User embutida no django, vou dar um exemplo da propria documentação (fazendo uma pequena adaptacao ao seu contexto, porém chamando o seu usario de Aluno) colocando a classe extendida no admin, coisa que vc não fez:
models.py
from django.db import models
from django.contrib.auth.models import User

class Aluno(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # Adicionando os campos (adicione qtos precisar)
    matricula = models.CharField('Matrícula', max_length=12)

admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Aluno

class AlunoInline(admin.StackedInline):
    model = Aluno
    can_delete = False
    verbose_name = 'Informações Pessoais'

class UserAdmin(BaseUserAdmin):
    inlines = (AlunoInline,)

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

@admin.register(Aluno)
class AlunoAdmin(admin.ModelAdmin):
    model = Aluno
    list_display = ('user', 'matricula',)

Pronto, agora vá no admin do django e vc terá:

Voce pode adiconar alunos (usuario) tanto pelo auth (AUTENTICATION AND AUTHORIZATION) quanto pelo USERS (Alunos)
Embora repl.it ainda tem algumas limitacoes com o django, deixei funcionando lá, para rodar é preciso fazer um fork, migrations e criar o superuser (só seguir as instrucoes do painel CLI no lado inferior direito).


text:
Q: Current node position Xpath 1.0 How can I get current node position in Xpath 1.0?
I'm trying /position() but it's not working. I also tried /@position().

A: It depends what you mean by "position" - the position() function doesn't necessarily bear any relation to the node's location in the XML tree it belongs to, it simply means the position of the current context node in the "current node list" (and the meaning of that depends on the host language that is evaluating the XPaths, in XSLT for example it means the list of nodes select-ed by the nearest apply-templates or for-each).
If you have an element named foo and you want to know whether it is the first, second, etc. foo within its parent (i.e. the number N you would need to get back to it as ../foo[N]) then you can do this by counting its preceding siblings with the same name
count(preceding-sibling::foo) + 1

However for this you need to know the name up front when you build the XPath expression - pure XPath 1.0 doesn't let you count the number of "preceding siblings that have the same name as the current node".
Some host languages may provide a variable or function that allows this - using XSLT as the example again, there you can use the current() function to refer to the current context node from anywhere in an expression, including inside predicates.  In XPath 2.0 you could do it with
for $cur in . return (count(preceding-sibling::*[name() = name($cur)]) + 1)

A: <xsl:template name="node-index-of">
    <xsl:param name="nodes" />
    <xsl:param name="node" />
    <xsl:param name="index" />
    <xsl:choose>
        <xsl:when test="$nodes[position()=$index]=$node">
            <xsl:value-of select="$index"/>
        </xsl:when>
        <xsl:when test="$index=count($nodes)">
            <xsl:value-of select="$index"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:call-template name="node-index-of">
                <xsl:with-param name="nodes" select="$nodes" />
                <xsl:with-param name="node" select="$node" />
                <xsl:with-param name="index">
                    <xsl:value-of select="$index+1"/>
                </xsl:with-param>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

$index begins from 1


text:
Q: In which direction is the slope greatest? You are standing on a steep hillside for which the height of the ground at a point $(x,y)$ is $f(x,y).$
If you head North you go uphill at a slope of $60^\circ$, if you go East then you go uphill at an angle of $30^\circ.$
In which direction is the slope greatest?
I know that this tells me that the directional derivative at $(0,0)$ in the direction $(0,1)$ is $\tan60$ and at $(0,0)$ in the direction $(1,0)$ is $\tan30.$ I also know that the direction of greatest change occurs in the direction of the gradient.
The solution says that the direction is $$\frac{1}{\sqrt{10}}\left(1 , 3 \right)$$
Could someone explain why this is?


text:
Q: ¿Cómo convertir de json a string en golang y echo? Tengo un json que recibo por post
{"endpoint" : "asistencia"}

Este lo recibo asi
json_map := make(map[string]interface{})

Ahora necesito asignarlo a una variable como string pero no se como se hace.
endpoint := c.String(json_map["endpoint"]) //Esto no funciona

No se como se debe hacer soy nuevo en golang

A: Existe un metodo especifico en la librería oficial de golang. Te recomiendo que lo investigues porque puedes "descodificar" datos estructurados directamente. Para tu ejemplo, el script completo sería algo así:
package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    myJsonString := `{"endpoint" : "asistencia"}`
    json_map := make(map[string]interface{})
    json.Unmarshal([]byte(myJsonString), &json_map)
    endpoint := json_map["endpoint"]
    fmt.Println(endpoint)
}


text:
Q: Plotting separatrices for nonlinear system Consider the system:
\begin{align*}
x'&=(1-x-y)x\\
y'&=(4-7x-3y)y
\end{align*}
The system has a saddle point at (1/4,3/4). How can I plot the separatrices on the phase portrait having domain $\{(x,y):\ 0\le x\le 1,\ 0\le y\le 2\}$?
Here is my attempt. Start with a vector plot.
Clear[x, y];
Clear[Derivative];
f[x_, y_] = (1 - x - y) x;
g[x_, y_] = (4 - 7 x - 3 y) y;
vp = VectorPlot[{f[x, y], g[x, y]}, {x, 0, 1}, {y, 0, 2},
   VectorScale -> {0.045, 0.5, None},
   VectorStyle -> {GrayLevel[0.8]},
   VectorPoints -> 16,
   Axes -> True, AxesLabel -> {x, y}];

Get the equilibrium points.
eqpts = Solve[{f[x, y] == 0, g[x, y] == 0}, {x, y}]

There is a saddle point at (1/4,3/4). Set an eps value.
eps=1/10000;

Define a function.
sol[{x0_, y0_, tmin_, tmax_}] :=
 NDSolveValue[{x'[t] == f[x[t], y[t]], y'[t] == g[x[t], y[t]],
   x[0] == x0, y[0] == y0}, {x[t], y[t]}, {t, tmin, tmax}]

Spend time (brute force) adjusting arguments to sol function to plot the separatrices.
sep1 = ParametricPlot[
   Evaluate@sol[{1/4 + eps, 3/4, 0, 40}], {t, 0, 40},
   PlotStyle -> {Red, Thick}];
sep2 = ParametricPlot[
   Evaluate@sol[{1/4 - eps, 3/4, 0, 40}], {t, 0, 40},
   PlotStyle -> {Red, Thick}];
sep3 = ParametricPlot[
   Evaluate@sol[{1/4 + eps, 3/4 + eps, -2.8, 0}], {t, -2.8, 0},
   PlotStyle -> {Red, Thick}];
sep4 = ParametricPlot[
   Evaluate@sol[{1/4 - eps, 3/4 - eps, -40, 0}], {t, -40, 0},
   PlotStyle -> {Red, Thick}];

Show everything together.
Show[vp, Graphics[{Black, PointSize[Large],
   Point[{x, y}] /. eqpts}], sep1, sep2, sep3, sep4]

Result:

Which worked. Just wondering if there would be a simpler approach, one that beginning students can easily understand.
P.S. All code pasted below for an easy copy and paste.
Clear[x, y];
Clear[Derivative];
f[x_, y_] = (1 - x - y) x;
g[x_, y_] = (4 - 7 x - 3 y) y;
vp = VectorPlot[{f[x, y], g[x, y]}, {x, 0, 1}, {y, 0, 2},
   VectorScale -> {0.045, 0.5, None},
   VectorStyle -> {GrayLevel[0.8]},
   VectorPoints -> 16,
   Axes -> True, AxesLabel -> {x, y}];
eqpts = Solve[{f[x, y] == 0, g[x, y] == 0}, {x, y}];
eps = 1/10000;
sol[{x0_, y0_, tmin_, tmax_}] :=
  NDSolveValue[{x'[t] == f[x[t], y[t]], y'[t] == g[x[t], y[t]],
    x[0] == x0, y[0] == y0}, {x[t], y[t]}, {t, tmin, tmax}];
sep1 = ParametricPlot[
   Evaluate@sol[{1/4 + eps, 3/4, 0, 40}], {t, 0, 40},
   PlotStyle -> {Red, Thick}];
sep2 = ParametricPlot[
   Evaluate@sol[{1/4 - eps, 3/4, 0, 40}], {t, 0, 40},
   PlotStyle -> {Red, Thick}];
sep3 = ParametricPlot[
   Evaluate@sol[{1/4 + eps, 3/4 + eps, -2.8, 0}], {t, -2.8, 0},
   PlotStyle -> {Red, Thick}];
sep4 = ParametricPlot[
   Evaluate@sol[{1/4 - eps, 3/4 - eps, -40, 0}], {t, -40, 0},
   PlotStyle -> {Red, Thick}];
Show[vp, Graphics[{Black, PointSize[Large],
   Point[{x, y}] /. eqpts}], sep1, sep2, sep3, sep4]

A: Perhaps this would be helpful:
e1 = (1 - x - y) x;
e2 = (4 - 7 x - 3 y) y;
sp = StreamPlot[{e1, e2}, {x, 0, 1}, {y, 0, 2},
   Epilog -> {Red, PointSize[0.02], Point[{{0, 0}, {1/4, 3/4}}]}];
{a, b, c, d} =
  ImplicitRegion[#, {x,
      y}] & /@ ({#1[e1, 0] && #2[e2, 0] && 0 < x < 1 && 0 < y < 2} & @@@
      Tuples[{Less, Greater}, 2]);
lab = "x'(t)" <> #1 <> ", " <> "y'(t)" <> #2 & @@@
   Tuples[{"<0", ">0"}, 2];
With[{col = {Red, Green, Blue, Yellow}},
 Legended[Show[sp,
   Sequence @@
    MapThread[
     RegionPlot[DiscretizeRegion[#, PrecisionGoal -> 10],
       PlotStyle -> {Opacity[0.3], #2}] &, {{a, b, c, d}, col}]],
  SwatchLegend[Lighter[#, 0.7] & /@ col, lab,
   LegendFunction -> "Panel"]]]

A: We can solve (approximately) for the initial conditions of solutions that approach an equilbrium by comparing the displacement vector from the equilibrium with the vector field of the ODE.  Such trajectory is characterized by the condition that these two vectors become parallel as the solution nears the equilibrium.  I used a similar idea before, which is buried in this answer.
sys = {(1 - x - y) x, (4 - 7 x - 3 y) y};
vars = {x, y};
equilibria = Solve[sys == {0, 0}, vars, Reals]
(*  {{x -> 0, y -> 4/3}, {x -> 1/4, y -> 3/4}, {x -> 1, y -> 0}, {x -> 0, y -> 0}}  *)

saddles = Pick[equilibria, Sign@Det@D[sys, {vars}] /. equilibria, -1]
(*  {{x -> 1/4, y -> 3/4}}  *)

Here is a function to get initial conditions for the separatrices.
sepICS[p0_, eps_] := With[{p1 = p0 + eps * Norm[p0] {Cos[t], Sin[t]}},
   p1 /. NSolve[Det[{p1 - p0, sys /. Thread[vars -> p1]}] == 0 && 0 <= t < 2 Pi]
   ];

We get parametrizations for the separatrices, stopping the integration when the solution gets close to the saddle and when it leaves the plot domain.  One problem with approaching a saddle point is that the initial condition, as well as the subsequent integration, is approximate.  If the solution is pushed too far, it will ricochet off along another separatrix (approximately).
separatrices = Flatten[
   Module[{eps = 10^-7,         (* tunable distance from equilibrium *)
     X0, dX},
    With[{Xa = 0, Xb = 1, Yc = 0, Yd = 2,  (* plot domain boundaries *)
        p0 = vars /. #,         (* equilibrium *)
        X = Through[vars[t]]},  (* variables at t *)
       X0 = X /. t -> 0;        (* initial values *)
       dX = D[X, t];            (* derivatives *)
       With[{X1 = X[[1]], X2 = X[[2]]},
        First@NDSolve[{
             dX == (sys /. v : Alternatives @@ vars :> v[t]),
             X0 == #,
             (*stop when close to saddle*)
             WhenEvent[Norm[X - p0] < 0.5 eps * Norm[p0], "StopIntegration"],
             (*stop when solution leaves plot domain*)
             WhenEvent[Abs[X1 - (Xa + Xb)/2] > (Xb - Xa)/2, "StopIntegration"],
             WhenEvent[Abs[X2 - (Yc + Yd)/2] > (Yd - Yc)/2, "StopIntegration"]},
            vars, {t, -100, 100}] & /@ sepICS[p0, eps]
        ]] & /@ saddles
    ],
 1];

sepPlots = ParametricPlot @@@ ({{x[t], y[t]},
       Hold[Flatten][{t, x["Domain"]}]} /. separatrices // ReleaseHold);

Show[
 background,
 vp,
 sepPlots,
 PlotRange -> All, Frame -> True, Axes -> False, AspectRatio -> 1]

The background is some attempt at mimicking ubpqdn's.  One can use the lines from the plots of the separatrices to construct poiygon's to illustrate the regions created by them.  It is a bit awkward to add the corner points.
sepLines = First@Cases[#, _Line, Infinity] & /@ sepPlots;
background = Graphics[
  Riffle[
   Lighter[#, 0.6] & /@ {Red, Purple, Yellow, Green},
   MapAt[Reverse,
     Partition[sepLines, 2, 1, 1], {{2}, {4}}] /. {Line[p1_],
      Line[p2_]} :> Polygon[
      Join[p1, p2,
       Nearest[Tuples[{{0, 1}, {0, 2}}], {p2[[-1, 1]], p1[[1, 2]]}, {1, 0.01}],
       Nearest[Tuples[{{0, 1}, {0, 2}}], {p1[[1, 1]], p2[[-1, 2]]}, {1, 0.01}]]]
   ],
  PlotRange -> All, Frame -> True, Axes -> False, AspectRatio -> 1
  ]

Addendum: Notes on the code.
1. v : x | y :> v[t]: The : is short for Pattern; | is short for Alternatives. So v : x | y defines the pattern symbol v to represent x or y. The whole v : x | y :> v[t], means replace x or y by x[t] or y[t] respectively. The rules {x -> x[t], y -> y[t]} are equivalent.
2. ParametricPlot @@@ ...:
The main problem here are the domains of the solutions. The variable separatrices contains a list of solutions of the form
{{x -> x1ifn, y -> y1ifn}, {x -> x2ifn, y -> y2ifn},...}

where x1ifn, y1ifn etc. are interpolating functions.  Each pair x1ifn, y1ifn has the same domain, but another pair x2ifn, y2ifn will have a different domain.  So what is an easy way to plot all of the solutions?  If ifn is an InterpolatingFunction, then ifn["Domain"] returns a list of domains for each input; in this case, it will have the form {{tmin, tmax}}.  Flatten[{t, x["Domain"]}] will have the form {t, tmin, tmax} as needed for ParametricPlot.  The problem is that the x in x["Domain"] has to be replaced by an InterpolatingFunction and evaluated before Flatten is evaluated.  Hence the Hold[Flatten], to prevent flattening until after the /. separatrices has been executed; the ReleaseHold then lets the domains be evaluated and flattened. Since separatrices is a list of solutions (each of which is a list of Rules), the replacement yields a list of the form:
{{{x1ifn[t], y1ifn[t]}, Hold[Flatten][{t, {{tmin1, tmax1}}}]},
 {{x2ifn[t], y2ifn[t]}, Hold[Flatten][{t, {{tmin2, tmax2}}}]},
 ...}

After ReleaseHold, these elements will be ready to have ParametricPlot applied to them with @@@.  This replaces the {} around each element with ParametricPlot[]:
{ParametricPlot[{x1ifn[t], y1ifn[t]}, {t, tmin1, tmax1}],
 ParametricPlot[{x2ifn[t], y2ifn[t]}, {t, tmin2, tmax2}],
 ...}

These automatically evaluate to the plots of each separatrix.


text:
Q: Get image color code's in RGB mode using php Is it possible to get the RGB colorcode from an image using php? If so, how?

A: You can do this using imagecolorat function.
Example:
<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

var_dump($r, $g, $b);


text:
Q: Desktop notifications for review queues? I know we have desktop notifications for chat, but can we get desktop notifications for review queues? I want to participate in more review tasks for some of the Stack Exchange communities I'm a member of such as Puzzling, Arqade, Code Review, etc.
However, due to these communities having less traffic, review tasks are seemingly far and few between. I'm constantly on my computer writing code, so I have the opportunity to participate in review queues throughout the day, but unfortunately, I forget to refresh my browser window and often miss out on potential tasks I could assist with.
I'm wondering if we could get desktop notifications for review queues as an opt-in feature, similar to chat's desktop notifications?

A: It's great that you want to help moderating some of the sites in the network. However, the principle behind the review queues is that they propose actions which need to be done within a couple of hours or a few days. Not the kind of please-react-ASAP actions notifications are meant for. If a site doesn't offer many review opportunities for you, it's a good sign: it means there are enough reviewers in the community to share the workload, with the additional benefit of having a diverse team looking at the items, instead of just a single user, irrespective of how good a reviewer that user is.
That said, there are user scripts which provide similar functionality. There is a Generic Review Tool which I learned of here; I haven't checked it out yet (holidays...) but you could give it a try.

A: The problem is that other people often get to review queues pretty quickly - there's a fair chance that by the time you notice and react to a notification (don't forget it's not just you getting the notification, it's everyone) someone else will have got their first and claimed that review for their own gamification (or to improve the quality of the SE network, whichever reason floats your boat).
In essence, many of the notifications will be fake news.
The chat and other notifications just continue to go up because they're not being resolved in the same way.


text:
Q: Command line to switch from user session to console session Windows Server 2003
If I already RDP to a remote host with user session, is there any command that I can switch to console session without closing current session and re-RDP again with "mstsc /console" parameter? Thanks.

EDIT:
After RDP to the remote host with session ID 1, there are 2 cases.
1. session 0 is created, so I can right click and connect to that session. Is there any command line to do the same?
2. session 0 is not created. Is there a command line to do the same too?
And I need to switch back and forth.

A: The shadow command can be used to shadow a session on Windows 2003 Server. You might use this to interact with the console session when logged in with a user session.


text:
Q: What is this little box at the end of my code in Microsoft Visual Studio 2015? This little box circled in blue

A: It is the end of file marker.  You will not see it if you switch off whitespace characters


text:
Q: Maps solo muestra el primer punto añadido Tengo un mapa al que añado varios puntos (parece que correctamente) pero el mapa solo me muestra el primero...
Aqui un fiddle que muestra el mal funcionamiento

ACLARACIONES

*

*No hay errores

*He comentado la parte de ajax que recoge los datos y simulado la respuesta minimizada en una variable para hacer el fiddle, pero esa parte va bien

*Los datos se pasan correctamente y parece que el array de markers[] se llena correctamente

Alguien ve que està pasando?
Creía que al hacer la llamada ajax podia ser la asincronia de javascript para el array de markers, pero el fiddle falla igual

A: Hay un error en los datos que le estas pasando, más exactamente en la longitud:
var data = "NOM;ADREÇA;TELEFON;HORARI;WEB;BLOG;X;Y;TIPUS\n\r" +
  "2d2despuma SHOP;Carrer de la Manigua 6
08027 Barcelona;+34 654 24 15 81;;http://www.2d2dspuma.com/;;41.422483;2.17941715;2\n\r" +
  "Quatre Pedres;Carrer Lleo
Badalona;+34 93 384 01 36;;http://www.4pedres.cat/;;41.4381275;2.232936;1\n\r" +
  "2d2despuma BAR;Carrer de la Manigua 8
08027 Barcelona;+34 654 24 15 81;;http://www.2d2dspuma.com/;;41.422483;2.17941715;1"

Le estás incluyendo una coma (,) adicional: 2.179417,15.
De hecho en los alert que pusiste se ve.


text:
Q: async MVVM command returning immediately Following some excellent help in a similar question I asked recently, and a similar example shown in this SO answer, I tried to apply this to a command in an MVVM view model as follows...
private async void BookAppointmentCommandExecute() {
  Debug.WriteLine("VM Start");
  IsBusy = true;
  await Task.Run(() => Service.BookAppointment(Appointment.ID, PatientID));
  IsBusy = false;
  Debug.WriteLine("VM Done");
}

The WCF service call looks like this...
[OperationContract]
public void BookAppointment(int appointmentID, int patientID) {
  Debug.WriteLine("Svc Start");
  Task.Delay(1000);
  AppointmentsServiceLogic.BookAppointment(appointmentID, patientID);
  Debug.WriteLine("Svc Done");
}

The Task.Delay was added to simulate network latency, so I can check if the busy indicator on the view is displayed correctly. It wasn't.
In both cases, the Debug.WriteLine statements were added to help me see what was going on.
Unlike the two samples I linked, my code doesn't suspend execution at the await line in the command method, but instead carries on immediately. From the results in the Output window, I can see the delay caused by the Task.Delay happens after the command method has finished executing...
40:30:409 VM Start
40:30:409 Svc Start
40:30:409 VM Done
40:31:410 Svc Done

As you can see, the command method completed immediately, then there was a one second delay (after IsBusy had been set back to false), and only then did the service method return. I thought the idea was that the command method's execution was suspended until the awaiteded method had completed.
Anyone able to explain what I'm doing wrong?

A: You seem to have a misunderstanding on how async-await works. Check out the blog of Stephen Cleary for an introduction: http://blog.stephencleary.com/2012/02/async-and-await.html
Some quick sample code to illustrate your problem:
Debug.WriteLine("Start");
await MyAsyncTask();
Debug.WriteLine("End");

The await keyword executes the Task following it (so the method MyAsyncTask) to execute asynchronous, but waits for it to finish before continuing execution (which means "End" is printed to the console after MyAsyncTask finished exceution)
Another example:
Debug.WriteLine("Start");
MyAsyncTask();
Debug.WriteLine("End");

Now "End" is written to the console immediately after MyAsyncTask was started, so before its completion.
Applied to your specific example I'd say a way to do this would be
private async void BookAppointmentCommandExecute() {
    Debug.WriteLine("VM Start");
    IsBusy = true;
    await Service.BookAppointment(Appointment.ID, PatientID); //as I've changed the return type of the method below, I can now directly await it
    IsBusy = false;
    Debug.WriteLine("VM Done");
}

//the method should return Task, so you can use the await keyword to wait for its completion
//I've marked the method with the async keyword so I can use the await keyword within
[OperationContract]
public async Task BookAppointment(int appointmentID, int patientID) {
    Debug.WriteLine("Svc Start");
    await Task.Delay(1000);
    //(depending if AppointmentsServiceLogic.BookAppointment is implemented asynchronous)
    await AppointmentsServiceLogic.BookAppointment(appointmentID, patientID);
    //or
    await Task.Run(() => AppointmentsServiceLogic.BookAppointment(appointmentID, patientID));
    Debug.WriteLine("Svc Done");
}


text:
Q: Argument(s) are different! Wanted: I am writing a unit test for my below code
public class Class1 {
   protected void execute(String a, String b) {
   try{
      process(a,b);
   }
   catch(Exception E){
       Class2.write(e,Class1.class.getSimpleName())
    }
  }

  private void process(String a, String b) {
     validate(a,b);
     // Doing some processing on a and b values
  }

 private void validate (String a, String b) {
    if(a==null || a.isEmpty() || b==null || b.isEmpty())
       throw new IllegalArgumentException("Input value cannot be null or empty");
 }

}

For the above code, I am trying to write a UT which covers the exception use case. Below is my UT code,
@Test

public void test1(){
 try {

            PowerMockito.mockStatic(Class2.class);
            PowerMockito.when(Class2.class, "write", Mockito.anyObject(), Mockito.anyString())
                    .thenCallRealMethod();
            Class1 class1 = new Class1();
            Class2.write(new IllegalArgumentException("Input value cannot be null or empty"),Class1.class.getSimpleClassName());
            PowerMockito.verifyStatic(Class2.class, VerificationModeFactory.times(1));
            class1.execute(Mockito.anyString(),Mockito.anyString());
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.getMessage());
        }
}

I am getting the below exception when I execute the above test
Argument(s) are different! Wanted:
Class2.write{
java.lang.IllegalArgumentException:Input value cannot be null or empty,
Class1
}

Actual invocation has different arguments:
Class2.write{
java.lang.IllegalArgumentException:Input value cannot be null or empty,
Class1
}

Can someone please help me on resolving this issue?
I really appreciate your help and time
Thanks in Advance

A: Your Problem:
IllegalArgumentException does not use the string message for equality. It would be safer to test the string message or the class type. I would prefer that the test detect the type rather than the message, as the string message should not be used for control flow, it is an implementation detail.
System.out.println(Objects.equals(
    new IllegalArgumentException(),
    new IllegalArgumentException()));
// false

System.out.println(Objects.equals(
    new IllegalArgumentException().getClass(),
    new IllegalArgumentException().getClass()));
// true

So to mock this I would use matchers:
any(IllegalArgumentException.class), eq(Class1.class.getSimpleName())

Issues with your design:
I'm going to end with an argument against how this code is structured, being that it is not built around dependency injection. Rather than calling the static method Class2::write, you could be calling an instance method.
For example, create the interface:
public interface Writer {
    void write(Exception e, String source);
}

You can now refactor the class to provide two ctors, one that accepts any writer, and one that defaults to Class2.
public class Class1 {
    private final Writer writer;

    public Class1() {
        this(Class2::write);
    }

    public Class1(Writer writer) {
        this.writer = writer;
    }

    protected void execute(String a, String b) {
        try {
            process(a,b);
        }
        catch (Exception E) {
            writer.write(e, Class1.class.getSimpleName());
        }
    }
    ...
}

Using this strategy you can now simply create an instance mock of Writer. This avoids having to mock as static method which changes the bytecode of your application, and also make your class more flexible as it can support many different writer implementations now. Anything that is modifying the bytecode of the application should be used very sparingly, such as replacing static method calls, does not truly validate the runtime execution of your code.
In my opinion, the majority of the PowerMockito/PowerMock only help verify code which was not built with testability / flexibility in mind. You shouldn't need to use anything outside of the Mockito/EasyMock tool-set for well structured code. There are some exceptions but the tool-set should be used very sparingly.


text:
Q: How to position an element at the bottom of the screen on load but not make it fixed? I am trying to position a chevron down arrow at the bottom of my page that would allow the user to smooth scroll to the next section on click. I would like the position to always be close to the bottom no matter what device or size of the screen and I do not want it to stay in place. It should scroll along with the rest of the site. When the user clicks it it will scroll to the next section and there will be a new chevron down arrow also at the bottom of the screen linking to the next section.
HTML

CSS
.chevron-down {
  /* magic code here */
}

A: There are probably a few ways to go about it, but absolute positioning combined with a couple of CSS3 features was my first thought. Use top:100vh to send the chevron to the bottom of the screen, then translateY(-100%) to bring it just above the bottom (so it isn't below the viewport at the start):
.chevron-down {
    position:absolute;
    top:100vh;
    transform:translateY(-100%);
    width:100%;
}

Here's a Bootply to demonstrate. Hope this helps! Let me know if you have any questions.

A: you can use vh dimension ( viewport height ) in your css ,
you should give your div a height by vh , for example:
div { height : 10vh }

it means your div has a height as long as 10 percent of every viewport that is showed on . after that get it a relative position and 90vh top
div {
    height : 10vh;
    position : relative;
    top : 90vh;
}

not that => height + top = 100
hope to be useful


text:
Q: Allow suggested edits on privilege wikis All privilege pages on MSO are wikis that periodically get pushed out to the entire network. They're also one type of post that doesn't currently work with suggested edits. Apparently you need editing privileges here on MSO to edit them.
Wouldn't it make sense to enable suggested edits for privilege wikis? A lot of users across the network view them. If they notice errors or things that could be improved, they either don't realize that they're community-editable, or they lack the rep to actually carry out improvements themselves — so they create new meta topics about it.

A: I think a better approach would be to post suggested changes here on Meta.
Given the visibility of such changes, some community vetting would seem to be in order. One or two edit reviewers checking a box off doesn't really qualify as such.

A: Rather, I think the privilege wikis should work like tag wikis:

*

*anyone can suggest an edit;

*any user with 5000 reputation on Meta can approve a suggested edit;

*any user with 20000 reputation on Meta can make unsupervised edits.

An even more stringent approach would be to make the privileges work like site FAQs, that only moderators can edit, but since there has (as far as I know) never been any abuse, I don't think this is warranted. (Granted, perhaps the absence of abuse is due to nobody knowing that the privilege wikis are editable, which threads like this are changing.)


text:
Q: How to define span tag within an option of a drop down list I am using HAML to create a drop down list as shown below:
%select.categories
  %option{:category => 'question'}
    Top Questions in
    %span#topic-name
  %option{:category => 'muse'}
    Top Muses in
    %span#topic-name
  %option{:category => 'user'}
    Top Users in
    %span#topic-name
.clear

My intention is to add the topic name to the span id 'topic-name'. However when I try to find the span using jQuery $('#topic-name'), an empty array was returned.
I checked the generated HTML and I was not able to see the span tags defined

Can anyone advise me on how I can create a span with the purpose of adding a 'topic name'
Thanks

A: HTML cannot be inserted inside option elements - only text. What you are asking cannot be achieved.
Alternatively, you could add the topic name as a data-x parameter, although this would only be valid in HTML5. I don't know how to achieve this in HAML, but the HTML would look like:
<select>
    <option data-topicname="ABC">Top Questions in</option>
</select>

A: The only way to do this is to use a plugin which simulates combobox behavior. I don't know about for jQuery, but ExtJS components have capabilities like that--but they're not provided by standard HTML and CSS as Rory mentioned.
This might be a good starting point:
http://www.designdim.com/2011/07/10-important-jquery-selectboxdropdown-plugins/

A: As @Rory McCrossan said, you cannot have a span inside of an option. It is invalid HTML.
You can however find the Option you want to modify and use JQuery's .append() function to insert the new text.
For example:
%select.categories
    %option{:id =>'optQuestion', :category => 'question'}
        Top Questions in

The JQuery to add text would be
$('optQuestion').append("some text"); // where "some text" is what you want to insert

If you have multiple copies of the same select and want to update them all with the same "some text" you can use a class instead of an ID for your targeting.

A: you ca use optgroup html tag
see docu here
http://www.w3schools.com/tags/att_optgroup_label.asp

A: That looks like a good candidate for an optgroup which allows for a non-selectable "header" option and groups its enclosed options together.


text:
Q: How to auto send error of try catch block to Sentry in Node JS I am building a Node JS application. I am using Sentry, https://docs.sentry.io/platforms/node/ in my application to monitor and report errors. But I am having a problem with global reporting for try catch block.
For example, I have a code block as follow.
const getUser = async (id) => {
  try {
     //do the database operation and return user
 } catch (e) {
    return {
      data: null,
      message: e.message
    }
 }
}

As you can see in the code, I am catching the error in the Try catch block. If I want to report the error to Sentry, I have to put in the following line in the catch block.
Sentry.captureException(e);

Basically, I am explicitly reporting the error. Is there a way to globally and automatically catch the error within the catch block and report it to the sentry. For, example, something like in PHP or Laravel. We will just have to initialize and configure the Sentry in one centralized place of the application and app will report any errors to the Sentry.

A: Sentry starts monitoring the whole application just by adding, the init function, somewhere in a global scope.
For example :
    Sentry.init({
  debug: appConfig.env === 'staging',
  dsn: appConfig.sentryDSN,
  environment: appConfig.env,
  integrations: [new Integrations.BrowserTracing()],
  release: [pjson.name, pjson.version].join('@'),
  tracesSampleRate: 1.0,
  ignoreErrors: [],
  normalizeDepth: 10, // Or however deep you want your state context to be.
  // (breadcrumb: Breadcrumb, hint?: BreadcrumbHint | undefined) => Breadcrumb | null
  beforeBreadcrumb(breadcrumb: Sentry.Breadcrumb, hint: Sentry.BreadcrumbHint | undefined) {
    return breadcrumb.category === 'xhr' ? breadcrumb : null;
  },
});

You can stay just to that 'conf/init' if you like, this captures some errors, which are: `every error that inherits from the 'Error' object, like: TypeError, RangeError, ReferenceError, SyntaxError, etc , for more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
But its better to handle the errors explicitly, and have the power to control what you want to send to Sentry(add/filter breadcrumbs, add tags, extra data etc).
In my reactjs app i have a middleware that all the errors are sent there, and inside there there is a logic..
Similarly i d suggest an error middleware where all the errors are send there, and at that middleware you exlicitly handle & send them to Sentry.
I assume the the tech stack node + express, so i d suggest, in the routes catch, to call next(error):
router.get('/path', function(req, res, next){
    const getUser = async (id) => {
    try {
       //do the database operation and return user
    } catch (error) {
      //return {
      //  data: null,
      //  message: e.message
      // }
      next(error)
    }
  }
})

**OR based on Express 5, route handlers that return Promise will call next(value) automatically when they reject or throw an error **:
app.get('/path', async function (req, res, next) {
  var user = await getUser(id)
  res.send(user)
})

And into the app.js, you put the error handler middleware where it handles the errors..:
app.use(function(err, req, res, next){
    // filter the error
    // send it to Sentry
    if(condition){
          // add custom breadcrumb
          Sentry.addBreadcrumb({
            type: Sentry.Severity.Error,
            category,
            message,
            level: Sentry.Severity.Error,
          });

         Sentry.configureScope((scope: any) => {
           scope.setTag('section', section);// add tag
           Sentry.captureException(error, scope); // capture the error
         });
     }
  })


text:
Q: Get values from URL as array. JInput How can I get string values from URL and save them as array, right now URL looks like this somename[]=xxxxxxxxx&somename[]=zzzzzzzzz&somename[]=zsdasd
$jinput = JFactory::getApplication()->input;
$nameArray = $jinput->get('somename');

If I var_dump $nameArray I get this Array and I var_dump $jinput I get this:
[data:protected] => Array
    (
        [somename] => Array
            (
            [0] => xxxxxxxxx
            [1] => zzzzzzzzz
            [2] => zsdasd
        )

    [option] => com_content
    [view] => featured
    [Itemid] => 101
)

I want to echo $nameArray like $nameArray[0] and get results "xxxxxxxxxx" but now i get Array instead.

A: Try something like this,
$somename = JRequest::getVar('somename',array(),'', 'ARRAY');

echo "<pre/>";
print_r($somename);

Hope its helps..


text:
Q: .htaccess redirect refers to folder I have these htaccess-rules:
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.de\/subpage$ [NC]
RewriteRule ^(.*)$ http://www.domain.de/subpage.html/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?subdomain\.domain\.de$ [NC]
RewriteRule ^(.*)$ http://www.domain.de/subpage.htm/$1 [R=301,L]

I don't get it. Usually htaccess-redirects are no problem, but this here drives me crazy.
When I open mydomain.de/subpage it tries to open the folder (or throws an 404 for not existing resource). Instead I want my htaccess-rule to trigger. What am I missing?

A: Okay, got it. Starkeen gave me a direction. Had to use variatons of condition-types: this is my working result:
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.de(/)?$ [NC]
RewriteCond %{REQUEST_URI} subpage
RewriteRule ^(.*)$ http://www.mydomain.de/new_page_html [R=301,L]


text:
Q: How to unit test an Angular directive with an Input? I have the below directive which is added to an element using the copy-to-clipboard attribute, and copies the content of the attribute to the users clipboard on click:
@Directive({
  selector: '[copy-to-clipboard]'
})
export class CopyToClipboardDirective {
  @Input('copy-to-clipboard') public payload: string;

  @HostListener('click', ['$event'])
  onClick(event: MouseEvent): void {
    event.preventDefault();
    if (!this.payload) {
      return;
    }

    const listener = (e: ClipboardEvent) => {
      const clipboard = e.clipboardData;
      clipboard.setData('text', this.payload.toString());
      e.preventDefault();
    };

    document.addEventListener('copy', listener, false);
    document.execCommand('copy');
    document.removeEventListener('copy', listener, false);
  }
}

And my unit test is setup as the following:
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {CopyToClipboardDirective} from './copy-to-clipboard.directive';
import {Component} from '@angular/core';

@Component({
  template: `<input [copy-to-clipboard]="'this is the passed string'" role="button" type="button">`
})
class MockCopyToClipboardComponent {}

fdescribe('Directive: CopyToClipboard', () => {
  let fixture: ComponentFixture<MockCopyToClipboardComponent>;
  let component: MockCopyToClipboardComponent;
  let element;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [CopyToClipboardDirective, MockCopyToClipboardComponent]
    });
    fixture = TestBed.createComponent(MockCopyToClipboardComponent);
    element = fixture.debugElement.nativeElement;
    component = fixture.componentInstance;
  });

  it('should run the copy command', () => {
    spyOn(document, 'execCommand');
    element.querySelector('input').click();
    fixture.detectChanges();
    expect(document.execCommand).toHaveBeenCalled();
  });
});

I'm getting an error back to say that the expected condition never occurs. I'm trying to set up the test to confirm that the document.execCommand has in fact been called, and not sure how I can confirm that the copied value matches that of the input string?

A: I run your test and found that the value of CopyToClipboardDirective#payload was never set. You can make this work by placing fixture.detectChanges() at the end of the beforeEach function.
beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [CopyToClipboardDirective, MockCopyToClipboardComponent]
    });
    fixture = TestBed.createComponent(MockCopyToClipboardComponent);
    element = fixture.debugElement.nativeElement;
    component = fixture.componentInstance;
    fixture.detectChanges(); // >>>>>> ADD this line
});

it('should run the copy command', () => {
    spyOn(document, 'execCommand');
    element.querySelector('input').click();
    // fixture.detectChanges(); // >>>>>> REMOVE this line
    expect(document.execCommand).toHaveBeenCalledWith('copy');
});

To check, what text was copied to the clipboard, you can try to read it back using Clipboard#readText. Since readText returns a Promise, you need to deal with its asynchronous nature. The following example used the done function to do this.
it('should run the copy command', (done) => {
    spyOn(document, 'execCommand');
    element.querySelector('input').click();
    expect(document.execCommand).toHaveBeenCalledWith('copy');

    element.querySelector('input').focus();
    navigator.clipboard.readText()
    .then(t => {
      expect(t).toBe('this is the passed string');
      done();
    })
    .catch(err => {
      fail(err);
    });
});


text:
Q: Calculated column value for Yes/No field in sharepoint I am developing a KPi, where am using a column named Complete which contains Yes/No field in it. For this if i write a calculated value for yes/no field:
=IF(CompletedTask=1,"Yes","No")

its not working. What should be the correct calcualted value for this field. IF Yes it should display 1 and no means 0. It should set the value using this calculation. thanks in advance!!

A: The correct formula should be like that:
=IF([CompletedTask], "Yes", "No")

A: Please try it like this:
=IF([CompletedTask]=1, "Yes", "No")

below is the reference for other formulas:
Link


text:
Q: C programming can't end loop I am writing a code where user inputs starting value, maximum value and step value. I calculate the results properly and all the formulas are correct, but there is one problem. I am unable to stop the loop so that my answers are displayed properly. When I run, it just starts the loop and I get lots of answers spammed on screen.
#include <stdio.h>
#include <math.h>

float funqcia(float x, float y, float k);

int main()
{
    float y;
    float A;
    float B;
    float H;
    float x;
    float t;
    int e=0;
    int N=15;
    int k = 0;
    while(e==0)
    {
        printf("enter starting value here: ");
        scanf("%fl",&A);
        printf("enter maximum value: ");
        scanf("%fl", &B);
        printf("enter step: ");
        scanf("%fl", &H);
        if(B > A)
        {
            e=1;
        }
        else
        {
            printf("Sorry, stopping value should be higher than starting value.");
        }
    }
    while(e==1)
    {
        printf("%s","_________________________________________________");
        printf("%s","\n");
        printf("%s","|                                                |");
        printf("%s","\n");
        printf("%s","|       Results are shown below                  |");
        printf("%s","\n");
        printf("%s","|                                                |");
        printf("%s","\n");
        printf("%s","--------------------------------------------------");
        printf("%s","\n");
        t=0;
        /*for(int i=0;i<N;i++)
        {
            if(i>0)
            {
                if (B<=y)
                {
                break;
                }
                t=pow(2,i)*pow(H,i-1);
                x=x+t;
                printf("%s","| ");
                printf("%fl",x);
                printf("%s","         | ");
                funqcia(x,y);
                printf("%s","\n");
            }
            else
            {
                if (B<=y)
                {
                    break;
                }
                x=A;
                printf("%s","| ");
                printf("%fl",x);
                printf("%s","         | ");
                funqcia(x,y);
                printf("%s","\n");
            }
        }*/
        for (int i=0;i<N;i++)
        {
            t=pow(2,i)*pow(H,i-1);
            x=x+t;
            if (i == 0)
            {
                x=A;
            }
            y=funqcia(x,y,k);
            if (B<=k)
            {
                break;
            }
            else
            {
                printf("x=%fl\ty=%fl", x,y);
                //}
            }
        }
    }
}

float funqcia(float x, float y, float k)
{
    y=((3+exp(x-1))/(1+pow(x,2)*(3-tan(x))));
    if(isinf(y))
    {
        printf("this is infinity");
    }
    else
    {
        printf("y: %fl",y);
    }
    k=y;
    return k;
}

A: You seem to have initialized variable e to 0 at the onset of your program. And you have a check while(e==0), somewhere when the B>A condition is true then e changes to 1 now. Next you have while(e==1) and some piece of code to display the calculations and results, here the value of e never changes from one to something else. As it is always 1,the while condition gives it a green signal to continue the loop till infinity and somehow messup your results on the screen.


text:
Q: Mac OSX - common commands not working I'm new to using Terminal. Using common commands like date etc., throws an error "command not found". From what I've understood from the internet is that, my path is incorrectly set. SO I tried using  $PATH and it shows this -  /usr/local/Cellar/smlnj/110.82/: is a directory.
What does this mean? also commands to uninstall smlnj is not working, it just shows "command not found"!

A:
What does this mean?

In the terminal, $PATH expands to /usr/local/Cellar/smlnj/110.82/. The terminal expects to receive commands, but that is a directory
You've probably overwritten the value of $PATH, since it should include things like /usr/env, where commands like date etc. are stored. The easiest way to fix this would be to restart your terminal.


text:
Q: POST запрос [JavaScript] Есть post запрос в js, возвращает "followed", по условию должен перезагрузить страницу, но js все равно выполняет функцию else, и в alert результат "followed". В чем может быть ошибка?
$.post("/index.php?plugin=follow&act=follow", {user_id: user_id}, function(result){
   if(result === 'followed') {

      // reload Page
      window.location.reload();
   } else {

      // show Error
      alert(result);
   }
});

A: Короче попытался вместо запроса на
$.post("/index.php?plugin=follow&act=follow"

сделать напрямую на index.php
$.post("/index.php?follow"

и в нем
if(isset($_GET['follow'])){
    echo 'followed';
    die();
}

Все заработало! Буду искать причину